babylon.max.js 5.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252
  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. */
  608. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  609. var _this = this;
  610. this._isReady = false;
  611. this._vertexSourceCodeOverride = vertexSourceCode;
  612. this._fragmentSourceCodeOverride = fragmentSourceCode;
  613. this.onError = function (effect, error) {
  614. if (onError) {
  615. onError(error);
  616. }
  617. };
  618. this.onCompiled = function () {
  619. var scenes = _this.getEngine().scenes;
  620. for (var i = 0; i < scenes.length; i++) {
  621. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  622. }
  623. if (onCompiled) {
  624. onCompiled(_this._program);
  625. }
  626. };
  627. this._fallbacks = null;
  628. this._prepareEffect();
  629. };
  630. /**
  631. * Gets the uniform locations of the the specified variable names
  632. * @param names THe names of the variables to lookup.
  633. * @returns Array of locations in the same order as variable names.
  634. */
  635. Effect.prototype.getSpecificUniformLocations = function (names) {
  636. var engine = this._engine;
  637. return engine.getUniforms(this._program, names);
  638. };
  639. /**
  640. * Prepares the effect
  641. */
  642. Effect.prototype._prepareEffect = function () {
  643. var attributesNames = this._attributesNames;
  644. var defines = this.defines;
  645. var fallbacks = this._fallbacks;
  646. this._valueCache = {};
  647. var previousProgram = this._program;
  648. try {
  649. var engine = this._engine;
  650. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  651. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  652. }
  653. else {
  654. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  655. }
  656. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  657. if (engine.supportsUniformBuffers) {
  658. for (var name in this._uniformBuffersNames) {
  659. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  660. }
  661. }
  662. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  663. this._attributes = engine.getAttributes(this._program, attributesNames);
  664. var index;
  665. for (index = 0; index < this._samplers.length; index++) {
  666. var sampler = this.getUniform(this._samplers[index]);
  667. if (sampler == null) {
  668. this._samplers.splice(index, 1);
  669. index--;
  670. }
  671. }
  672. engine.bindSamplers(this);
  673. this._compilationError = "";
  674. this._isReady = true;
  675. if (this.onCompiled) {
  676. this.onCompiled(this);
  677. }
  678. this.onCompileObservable.notifyObservers(this);
  679. this.onCompileObservable.clear();
  680. // Unbind mesh reference in fallbacks
  681. if (this._fallbacks) {
  682. this._fallbacks.unBindMesh();
  683. }
  684. if (previousProgram) {
  685. this.getEngine()._deleteProgram(previousProgram);
  686. }
  687. }
  688. catch (e) {
  689. this._compilationError = e.message;
  690. // Let's go through fallbacks then
  691. BABYLON.Tools.Error("Unable to compile effect:");
  692. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  693. return " " + uniform;
  694. }));
  695. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  696. return " " + attribute;
  697. }));
  698. BABYLON.Tools.Error("Error: " + this._compilationError);
  699. if (previousProgram) {
  700. this._program = previousProgram;
  701. this._isReady = true;
  702. if (this.onError) {
  703. this.onError(this, this._compilationError);
  704. }
  705. this.onErrorObservable.notifyObservers(this);
  706. }
  707. if (fallbacks && fallbacks.isMoreFallbacks) {
  708. BABYLON.Tools.Error("Trying next fallback.");
  709. this.defines = fallbacks.reduce(this.defines, this);
  710. this._prepareEffect();
  711. }
  712. else { // Sorry we did everything we can
  713. if (this.onError) {
  714. this.onError(this, this._compilationError);
  715. }
  716. this.onErrorObservable.notifyObservers(this);
  717. this.onErrorObservable.clear();
  718. // Unbind mesh reference in fallbacks
  719. if (this._fallbacks) {
  720. this._fallbacks.unBindMesh();
  721. }
  722. }
  723. }
  724. };
  725. Object.defineProperty(Effect.prototype, "isSupported", {
  726. /**
  727. * Checks if the effect is supported. (Must be called after compilation)
  728. */
  729. get: function () {
  730. return this._compilationError === "";
  731. },
  732. enumerable: true,
  733. configurable: true
  734. });
  735. /**
  736. * Binds a texture to the engine to be used as output of the shader.
  737. * @param channel Name of the output variable.
  738. * @param texture Texture to bind.
  739. */
  740. Effect.prototype._bindTexture = function (channel, texture) {
  741. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  742. };
  743. /**
  744. * Sets a texture on the engine to be used in the shader.
  745. * @param channel Name of the sampler variable.
  746. * @param texture Texture to set.
  747. */
  748. Effect.prototype.setTexture = function (channel, texture) {
  749. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  750. };
  751. /**
  752. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  753. * @param channel Name of the sampler variable.
  754. * @param texture Texture to set.
  755. */
  756. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  757. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  758. };
  759. /**
  760. * Sets an array of textures on the engine to be used in the shader.
  761. * @param channel Name of the variable.
  762. * @param textures Textures to set.
  763. */
  764. Effect.prototype.setTextureArray = function (channel, textures) {
  765. if (this._samplers.indexOf(channel + "Ex") === -1) {
  766. var initialPos = this._samplers.indexOf(channel);
  767. for (var index = 1; index < textures.length; index++) {
  768. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  769. }
  770. }
  771. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  772. };
  773. /**
  774. * 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)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the input texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /**
  782. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  783. * 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)
  784. * @param channel Name of the sampler variable.
  785. * @param postProcess Post process to get the output texture from.
  786. */
  787. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  788. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  789. };
  790. /** @hidden */
  791. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  792. var cache = this._valueCache[uniformName];
  793. var flag = matrix.updateFlag;
  794. if (cache !== undefined && cache === flag) {
  795. return false;
  796. }
  797. this._valueCache[uniformName] = flag;
  798. return true;
  799. };
  800. /** @hidden */
  801. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  802. var cache = this._valueCache[uniformName];
  803. if (!cache) {
  804. cache = [x, y];
  805. this._valueCache[uniformName] = cache;
  806. return true;
  807. }
  808. var changed = false;
  809. if (cache[0] !== x) {
  810. cache[0] = x;
  811. changed = true;
  812. }
  813. if (cache[1] !== y) {
  814. cache[1] = y;
  815. changed = true;
  816. }
  817. return changed;
  818. };
  819. /** @hidden */
  820. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  821. var cache = this._valueCache[uniformName];
  822. if (!cache) {
  823. cache = [x, y, z];
  824. this._valueCache[uniformName] = cache;
  825. return true;
  826. }
  827. var changed = false;
  828. if (cache[0] !== x) {
  829. cache[0] = x;
  830. changed = true;
  831. }
  832. if (cache[1] !== y) {
  833. cache[1] = y;
  834. changed = true;
  835. }
  836. if (cache[2] !== z) {
  837. cache[2] = z;
  838. changed = true;
  839. }
  840. return changed;
  841. };
  842. /** @hidden */
  843. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  844. var cache = this._valueCache[uniformName];
  845. if (!cache) {
  846. cache = [x, y, z, w];
  847. this._valueCache[uniformName] = cache;
  848. return true;
  849. }
  850. var changed = false;
  851. if (cache[0] !== x) {
  852. cache[0] = x;
  853. changed = true;
  854. }
  855. if (cache[1] !== y) {
  856. cache[1] = y;
  857. changed = true;
  858. }
  859. if (cache[2] !== z) {
  860. cache[2] = z;
  861. changed = true;
  862. }
  863. if (cache[3] !== w) {
  864. cache[3] = w;
  865. changed = true;
  866. }
  867. return changed;
  868. };
  869. /**
  870. * Binds a buffer to a uniform.
  871. * @param buffer Buffer to bind.
  872. * @param name Name of the uniform variable to bind to.
  873. */
  874. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  875. var bufferName = this._uniformBuffersNames[name];
  876. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  877. return;
  878. }
  879. Effect._baseCache[bufferName] = buffer;
  880. this._engine.bindUniformBufferBase(buffer, bufferName);
  881. };
  882. /**
  883. * Binds block to a uniform.
  884. * @param blockName Name of the block to bind.
  885. * @param index Index to bind.
  886. */
  887. Effect.prototype.bindUniformBlock = function (blockName, index) {
  888. this._engine.bindUniformBlock(this._program, blockName, index);
  889. };
  890. /**
  891. * Sets an interger value on a uniform variable.
  892. * @param uniformName Name of the variable.
  893. * @param value Value to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setInt = function (uniformName, value) {
  897. var cache = this._valueCache[uniformName];
  898. if (cache !== undefined && cache === value)
  899. return this;
  900. this._valueCache[uniformName] = value;
  901. this._engine.setInt(this.getUniform(uniformName), value);
  902. return this;
  903. };
  904. /**
  905. * Sets an int array on a uniform variable.
  906. * @param uniformName Name of the variable.
  907. * @param array array to be set.
  908. * @returns this effect.
  909. */
  910. Effect.prototype.setIntArray = function (uniformName, array) {
  911. this._valueCache[uniformName] = null;
  912. this._engine.setIntArray(this.getUniform(uniformName), array);
  913. return this;
  914. };
  915. /**
  916. * 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)
  917. * @param uniformName Name of the variable.
  918. * @param array array to be set.
  919. * @returns this effect.
  920. */
  921. Effect.prototype.setIntArray2 = function (uniformName, array) {
  922. this._valueCache[uniformName] = null;
  923. this._engine.setIntArray2(this.getUniform(uniformName), array);
  924. return this;
  925. };
  926. /**
  927. * 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)
  928. * @param uniformName Name of the variable.
  929. * @param array array to be set.
  930. * @returns this effect.
  931. */
  932. Effect.prototype.setIntArray3 = function (uniformName, array) {
  933. this._valueCache[uniformName] = null;
  934. this._engine.setIntArray3(this.getUniform(uniformName), array);
  935. return this;
  936. };
  937. /**
  938. * 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)
  939. * @param uniformName Name of the variable.
  940. * @param array array to be set.
  941. * @returns this effect.
  942. */
  943. Effect.prototype.setIntArray4 = function (uniformName, array) {
  944. this._valueCache[uniformName] = null;
  945. this._engine.setIntArray4(this.getUniform(uniformName), array);
  946. return this;
  947. };
  948. /**
  949. * Sets an float array on a uniform variable.
  950. * @param uniformName Name of the variable.
  951. * @param array array to be set.
  952. * @returns this effect.
  953. */
  954. Effect.prototype.setFloatArray = function (uniformName, array) {
  955. this._valueCache[uniformName] = null;
  956. this._engine.setFloatArray(this.getUniform(uniformName), array);
  957. return this;
  958. };
  959. /**
  960. * 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)
  961. * @param uniformName Name of the variable.
  962. * @param array array to be set.
  963. * @returns this effect.
  964. */
  965. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  966. this._valueCache[uniformName] = null;
  967. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  968. return this;
  969. };
  970. /**
  971. * 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)
  972. * @param uniformName Name of the variable.
  973. * @param array array to be set.
  974. * @returns this effect.
  975. */
  976. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  977. this._valueCache[uniformName] = null;
  978. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  979. return this;
  980. };
  981. /**
  982. * 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)
  983. * @param uniformName Name of the variable.
  984. * @param array array to be set.
  985. * @returns this effect.
  986. */
  987. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  988. this._valueCache[uniformName] = null;
  989. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  990. return this;
  991. };
  992. /**
  993. * Sets an array on a uniform variable.
  994. * @param uniformName Name of the variable.
  995. * @param array array to be set.
  996. * @returns this effect.
  997. */
  998. Effect.prototype.setArray = function (uniformName, array) {
  999. this._valueCache[uniformName] = null;
  1000. this._engine.setArray(this.getUniform(uniformName), array);
  1001. return this;
  1002. };
  1003. /**
  1004. * 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)
  1005. * @param uniformName Name of the variable.
  1006. * @param array array to be set.
  1007. * @returns this effect.
  1008. */
  1009. Effect.prototype.setArray2 = function (uniformName, array) {
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setArray2(this.getUniform(uniformName), array);
  1012. return this;
  1013. };
  1014. /**
  1015. * 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)
  1016. * @param uniformName Name of the variable.
  1017. * @param array array to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setArray3 = function (uniformName, array) {
  1021. this._valueCache[uniformName] = null;
  1022. this._engine.setArray3(this.getUniform(uniformName), array);
  1023. return this;
  1024. };
  1025. /**
  1026. * 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)
  1027. * @param uniformName Name of the variable.
  1028. * @param array array to be set.
  1029. * @returns this effect.
  1030. */
  1031. Effect.prototype.setArray4 = function (uniformName, array) {
  1032. this._valueCache[uniformName] = null;
  1033. this._engine.setArray4(this.getUniform(uniformName), array);
  1034. return this;
  1035. };
  1036. /**
  1037. * Sets matrices on a uniform variable.
  1038. * @param uniformName Name of the variable.
  1039. * @param matrices matrices to be set.
  1040. * @returns this effect.
  1041. */
  1042. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1043. if (!matrices) {
  1044. return this;
  1045. }
  1046. this._valueCache[uniformName] = null;
  1047. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1048. return this;
  1049. };
  1050. /**
  1051. * Sets matrix on a uniform variable.
  1052. * @param uniformName Name of the variable.
  1053. * @param matrix matrix to be set.
  1054. * @returns this effect.
  1055. */
  1056. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1057. if (this._cacheMatrix(uniformName, matrix)) {
  1058. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1059. }
  1060. return this;
  1061. };
  1062. /**
  1063. * 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)
  1064. * @param uniformName Name of the variable.
  1065. * @param matrix matrix to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1069. this._valueCache[uniformName] = null;
  1070. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1071. return this;
  1072. };
  1073. /**
  1074. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1075. * @param uniformName Name of the variable.
  1076. * @param matrix matrix to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1080. this._valueCache[uniformName] = null;
  1081. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1082. return this;
  1083. };
  1084. /**
  1085. * Sets a float on a uniform variable.
  1086. * @param uniformName Name of the variable.
  1087. * @param value value to be set.
  1088. * @returns this effect.
  1089. */
  1090. Effect.prototype.setFloat = function (uniformName, value) {
  1091. var cache = this._valueCache[uniformName];
  1092. if (cache !== undefined && cache === value)
  1093. return this;
  1094. this._valueCache[uniformName] = value;
  1095. this._engine.setFloat(this.getUniform(uniformName), value);
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets a boolean on a uniform variable.
  1100. * @param uniformName Name of the variable.
  1101. * @param bool value to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setBool = function (uniformName, bool) {
  1105. var cache = this._valueCache[uniformName];
  1106. if (cache !== undefined && cache === bool)
  1107. return this;
  1108. this._valueCache[uniformName] = bool;
  1109. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1110. return this;
  1111. };
  1112. /**
  1113. * Sets a Vector2 on a uniform variable.
  1114. * @param uniformName Name of the variable.
  1115. * @param vector2 vector2 to be set.
  1116. * @returns this effect.
  1117. */
  1118. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1119. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1120. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1121. }
  1122. return this;
  1123. };
  1124. /**
  1125. * Sets a float2 on a uniform variable.
  1126. * @param uniformName Name of the variable.
  1127. * @param x First float in float2.
  1128. * @param y Second float in float2.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1132. if (this._cacheFloat2(uniformName, x, y)) {
  1133. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a Vector3 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param vector3 Value to be set.
  1141. * @returns this effect.
  1142. */
  1143. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1144. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1145. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1146. }
  1147. return this;
  1148. };
  1149. /**
  1150. * Sets a float3 on a uniform variable.
  1151. * @param uniformName Name of the variable.
  1152. * @param x First float in float3.
  1153. * @param y Second float in float3.
  1154. * @param z Third float in float3.
  1155. * @returns this effect.
  1156. */
  1157. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1158. if (this._cacheFloat3(uniformName, x, y, z)) {
  1159. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1160. }
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a Vector4 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param vector4 Value to be set.
  1167. * @returns this effect.
  1168. */
  1169. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1170. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1171. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1172. }
  1173. return this;
  1174. };
  1175. /**
  1176. * Sets a float4 on a uniform variable.
  1177. * @param uniformName Name of the variable.
  1178. * @param x First float in float4.
  1179. * @param y Second float in float4.
  1180. * @param z Third float in float4.
  1181. * @param w Fourth float in float4.
  1182. * @returns this effect.
  1183. */
  1184. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1185. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1186. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1187. }
  1188. return this;
  1189. };
  1190. /**
  1191. * Sets a Color3 on a uniform variable.
  1192. * @param uniformName Name of the variable.
  1193. * @param color3 Value to be set.
  1194. * @returns this effect.
  1195. */
  1196. Effect.prototype.setColor3 = function (uniformName, color3) {
  1197. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1198. this._engine.setColor3(this.getUniform(uniformName), color3);
  1199. }
  1200. return this;
  1201. };
  1202. /**
  1203. * Sets a Color4 on a uniform variable.
  1204. * @param uniformName Name of the variable.
  1205. * @param color3 Value to be set.
  1206. * @param alpha Alpha value to be set.
  1207. * @returns this effect.
  1208. */
  1209. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1210. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1211. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1212. }
  1213. return this;
  1214. };
  1215. /**
  1216. * Sets a Color4 on a uniform variable
  1217. * @param uniformName defines the name of the variable
  1218. * @param color4 defines the value to be set
  1219. * @returns this effect.
  1220. */
  1221. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1222. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1223. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1224. }
  1225. return this;
  1226. };
  1227. /**
  1228. * This function will add a new shader to the shader store
  1229. * @param name the name of the shader
  1230. * @param pixelShader optional pixel shader content
  1231. * @param vertexShader optional vertex shader content
  1232. */
  1233. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1234. if (pixelShader) {
  1235. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1236. }
  1237. if (vertexShader) {
  1238. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1239. }
  1240. };
  1241. /**
  1242. * Resets the cache of effects.
  1243. */
  1244. Effect.ResetCache = function () {
  1245. Effect._baseCache = {};
  1246. };
  1247. Effect._uniqueIdSeed = 0;
  1248. Effect._baseCache = {};
  1249. /**
  1250. * Store of each shader (The can be looked up using effect.key)
  1251. */
  1252. Effect.ShadersStore = {};
  1253. /**
  1254. * Store of each included file for a shader (The can be looked up using effect.key)
  1255. */
  1256. Effect.IncludesShadersStore = {};
  1257. return Effect;
  1258. }());
  1259. BABYLON.Effect = Effect;
  1260. })(BABYLON || (BABYLON = {}));
  1261. //# sourceMappingURL=babylon.effect.js.map
  1262. //# sourceMappingURL=babylon.types.js.map
  1263. var BABYLON;
  1264. (function (BABYLON) {
  1265. var KeyboardEventTypes = /** @class */ (function () {
  1266. function KeyboardEventTypes() {
  1267. }
  1268. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1269. get: function () {
  1270. return KeyboardEventTypes._KEYDOWN;
  1271. },
  1272. enumerable: true,
  1273. configurable: true
  1274. });
  1275. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1276. get: function () {
  1277. return KeyboardEventTypes._KEYUP;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. KeyboardEventTypes._KEYDOWN = 0x01;
  1283. KeyboardEventTypes._KEYUP = 0x02;
  1284. return KeyboardEventTypes;
  1285. }());
  1286. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1287. var KeyboardInfo = /** @class */ (function () {
  1288. function KeyboardInfo(type, event) {
  1289. this.type = type;
  1290. this.event = event;
  1291. }
  1292. return KeyboardInfo;
  1293. }());
  1294. BABYLON.KeyboardInfo = KeyboardInfo;
  1295. /**
  1296. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1297. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1298. */
  1299. var KeyboardInfoPre = /** @class */ (function (_super) {
  1300. __extends(KeyboardInfoPre, _super);
  1301. function KeyboardInfoPre(type, event) {
  1302. var _this = _super.call(this, type, event) || this;
  1303. _this.skipOnPointerObservable = false;
  1304. return _this;
  1305. }
  1306. return KeyboardInfoPre;
  1307. }(KeyboardInfo));
  1308. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1309. })(BABYLON || (BABYLON = {}));
  1310. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1311. var BABYLON;
  1312. (function (BABYLON) {
  1313. var PointerEventTypes = /** @class */ (function () {
  1314. function PointerEventTypes() {
  1315. }
  1316. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1317. get: function () {
  1318. return PointerEventTypes._POINTERDOWN;
  1319. },
  1320. enumerable: true,
  1321. configurable: true
  1322. });
  1323. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1324. get: function () {
  1325. return PointerEventTypes._POINTERUP;
  1326. },
  1327. enumerable: true,
  1328. configurable: true
  1329. });
  1330. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1331. get: function () {
  1332. return PointerEventTypes._POINTERMOVE;
  1333. },
  1334. enumerable: true,
  1335. configurable: true
  1336. });
  1337. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1338. get: function () {
  1339. return PointerEventTypes._POINTERWHEEL;
  1340. },
  1341. enumerable: true,
  1342. configurable: true
  1343. });
  1344. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1345. get: function () {
  1346. return PointerEventTypes._POINTERPICK;
  1347. },
  1348. enumerable: true,
  1349. configurable: true
  1350. });
  1351. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1352. get: function () {
  1353. return PointerEventTypes._POINTERTAP;
  1354. },
  1355. enumerable: true,
  1356. configurable: true
  1357. });
  1358. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1359. get: function () {
  1360. return PointerEventTypes._POINTERDOUBLETAP;
  1361. },
  1362. enumerable: true,
  1363. configurable: true
  1364. });
  1365. PointerEventTypes._POINTERDOWN = 0x01;
  1366. PointerEventTypes._POINTERUP = 0x02;
  1367. PointerEventTypes._POINTERMOVE = 0x04;
  1368. PointerEventTypes._POINTERWHEEL = 0x08;
  1369. PointerEventTypes._POINTERPICK = 0x10;
  1370. PointerEventTypes._POINTERTAP = 0x20;
  1371. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1372. return PointerEventTypes;
  1373. }());
  1374. BABYLON.PointerEventTypes = PointerEventTypes;
  1375. var PointerInfoBase = /** @class */ (function () {
  1376. function PointerInfoBase(type, event) {
  1377. this.type = type;
  1378. this.event = event;
  1379. }
  1380. return PointerInfoBase;
  1381. }());
  1382. BABYLON.PointerInfoBase = PointerInfoBase;
  1383. /**
  1384. * This class is used to store pointer related info for the onPrePointerObservable event.
  1385. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1386. */
  1387. var PointerInfoPre = /** @class */ (function (_super) {
  1388. __extends(PointerInfoPre, _super);
  1389. function PointerInfoPre(type, event, localX, localY) {
  1390. var _this = _super.call(this, type, event) || this;
  1391. /**
  1392. * Ray from a pointer if availible (eg. 6dof controller)
  1393. */
  1394. _this.ray = null;
  1395. _this.skipOnPointerObservable = false;
  1396. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1397. return _this;
  1398. }
  1399. return PointerInfoPre;
  1400. }(PointerInfoBase));
  1401. BABYLON.PointerInfoPre = PointerInfoPre;
  1402. /**
  1403. * This type contains all the data related to a pointer event in Babylon.js.
  1404. * 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.
  1405. */
  1406. var PointerInfo = /** @class */ (function (_super) {
  1407. __extends(PointerInfo, _super);
  1408. function PointerInfo(type, event, pickInfo) {
  1409. var _this = _super.call(this, type, event) || this;
  1410. _this.pickInfo = pickInfo;
  1411. return _this;
  1412. }
  1413. return PointerInfo;
  1414. }(PointerInfoBase));
  1415. BABYLON.PointerInfo = PointerInfo;
  1416. })(BABYLON || (BABYLON = {}));
  1417. //# sourceMappingURL=babylon.pointerEvents.js.map
  1418. var BABYLON;
  1419. (function (BABYLON) {
  1420. BABYLON.ToGammaSpace = 1 / 2.2;
  1421. BABYLON.ToLinearSpace = 2.2;
  1422. BABYLON.Epsilon = 0.001;
  1423. /**
  1424. * Class used to hold a RBG color
  1425. */
  1426. var Color3 = /** @class */ (function () {
  1427. /**
  1428. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1429. * @param r defines the red component (between 0 and 1, default is 0)
  1430. * @param g defines the green component (between 0 and 1, default is 0)
  1431. * @param b defines the blue component (between 0 and 1, default is 0)
  1432. */
  1433. function Color3(
  1434. /**
  1435. * Defines the red component (between 0 and 1, default is 0)
  1436. */
  1437. r,
  1438. /**
  1439. * Defines the green component (between 0 and 1, default is 0)
  1440. */
  1441. g,
  1442. /**
  1443. * Defines the blue component (between 0 and 1, default is 0)
  1444. */
  1445. b) {
  1446. if (r === void 0) { r = 0; }
  1447. if (g === void 0) { g = 0; }
  1448. if (b === void 0) { b = 0; }
  1449. this.r = r;
  1450. this.g = g;
  1451. this.b = b;
  1452. }
  1453. /**
  1454. * Creates a string with the Color3 current values
  1455. * @returns the string representation of the Color3 object
  1456. */
  1457. Color3.prototype.toString = function () {
  1458. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1459. };
  1460. /**
  1461. * Returns the string "Color3"
  1462. * @returns "Color3"
  1463. */
  1464. Color3.prototype.getClassName = function () {
  1465. return "Color3";
  1466. };
  1467. /**
  1468. * Compute the Color3 hash code
  1469. * @returns an unique number that can be used to hash Color3 objects
  1470. */
  1471. Color3.prototype.getHashCode = function () {
  1472. var hash = this.r || 0;
  1473. hash = (hash * 397) ^ (this.g || 0);
  1474. hash = (hash * 397) ^ (this.b || 0);
  1475. return hash;
  1476. };
  1477. // Operators
  1478. /**
  1479. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1480. * @param array defines the array where to store the r,g,b components
  1481. * @param index defines an optional index in the target array to define where to start storing values
  1482. * @returns the current Color3 object
  1483. */
  1484. Color3.prototype.toArray = function (array, index) {
  1485. if (index === undefined) {
  1486. index = 0;
  1487. }
  1488. array[index] = this.r;
  1489. array[index + 1] = this.g;
  1490. array[index + 2] = this.b;
  1491. return this;
  1492. };
  1493. /**
  1494. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1495. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1496. * @returns a new {BABYLON.Color4} object
  1497. */
  1498. Color3.prototype.toColor4 = function (alpha) {
  1499. if (alpha === void 0) { alpha = 1; }
  1500. return new Color4(this.r, this.g, this.b, alpha);
  1501. };
  1502. /**
  1503. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1504. * @returns the new array
  1505. */
  1506. Color3.prototype.asArray = function () {
  1507. var result = new Array();
  1508. this.toArray(result, 0);
  1509. return result;
  1510. };
  1511. /**
  1512. * Returns the luminance value
  1513. * @returns a float value
  1514. */
  1515. Color3.prototype.toLuminance = function () {
  1516. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1517. };
  1518. /**
  1519. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1520. * @param otherColor defines the second operand
  1521. * @returns the new Color3 object
  1522. */
  1523. Color3.prototype.multiply = function (otherColor) {
  1524. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1525. };
  1526. /**
  1527. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1528. * @param otherColor defines the second operand
  1529. * @param result defines the Color3 object where to store the result
  1530. * @returns the current Color3
  1531. */
  1532. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1533. result.r = this.r * otherColor.r;
  1534. result.g = this.g * otherColor.g;
  1535. result.b = this.b * otherColor.b;
  1536. return this;
  1537. };
  1538. /**
  1539. * Determines equality between Color3 objects
  1540. * @param otherColor defines the second operand
  1541. * @returns true if the rgb values are equal to the given ones
  1542. */
  1543. Color3.prototype.equals = function (otherColor) {
  1544. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1545. };
  1546. /**
  1547. * Determines equality between the current Color3 object and a set of r,b,g values
  1548. * @param r defines the red component to check
  1549. * @param g defines the green component to check
  1550. * @param b defines the blue component to check
  1551. * @returns true if the rgb values are equal to the given ones
  1552. */
  1553. Color3.prototype.equalsFloats = function (r, g, b) {
  1554. return this.r === r && this.g === g && this.b === b;
  1555. };
  1556. /**
  1557. * Multiplies in place each rgb value by scale
  1558. * @param scale defines the scaling factor
  1559. * @returns the updated Color3
  1560. */
  1561. Color3.prototype.scale = function (scale) {
  1562. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1563. };
  1564. /**
  1565. * Multiplies the rgb values by scale and stores the result into "result"
  1566. * @param scale defines the scaling factor
  1567. * @param result defines the Color3 object where to store the result
  1568. * @returns the unmodified current Color3
  1569. */
  1570. Color3.prototype.scaleToRef = function (scale, result) {
  1571. result.r = this.r * scale;
  1572. result.g = this.g * scale;
  1573. result.b = this.b * scale;
  1574. return this;
  1575. };
  1576. /**
  1577. * Scale the current Color3 values by a factor and add the result to a given Color3
  1578. * @param scale defines the scale factor
  1579. * @param result defines color to store the result into
  1580. * @returns the unmodified current Color3
  1581. */
  1582. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1583. result.r += this.r * scale;
  1584. result.g += this.g * scale;
  1585. result.b += this.b * scale;
  1586. return this;
  1587. };
  1588. /**
  1589. * Clamps the rgb values by the min and max values and stores the result into "result"
  1590. * @param min defines minimum clamping value (default is 0)
  1591. * @param max defines maximum clamping value (default is 1)
  1592. * @param result defines color to store the result into
  1593. * @returns the original Color3
  1594. */
  1595. Color3.prototype.clampToRef = function (min, max, result) {
  1596. if (min === void 0) { min = 0; }
  1597. if (max === void 0) { max = 1; }
  1598. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1599. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1600. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1601. return this;
  1602. };
  1603. /**
  1604. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1605. * @param otherColor defines the second operand
  1606. * @returns the new Color3
  1607. */
  1608. Color3.prototype.add = function (otherColor) {
  1609. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1610. };
  1611. /**
  1612. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1613. * @param otherColor defines the second operand
  1614. * @param result defines Color3 object to store the result into
  1615. * @returns the unmodified current Color3
  1616. */
  1617. Color3.prototype.addToRef = function (otherColor, result) {
  1618. result.r = this.r + otherColor.r;
  1619. result.g = this.g + otherColor.g;
  1620. result.b = this.b + otherColor.b;
  1621. return this;
  1622. };
  1623. /**
  1624. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1625. * @param otherColor defines the second operand
  1626. * @returns the new Color3
  1627. */
  1628. Color3.prototype.subtract = function (otherColor) {
  1629. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1630. };
  1631. /**
  1632. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1633. * @param otherColor defines the second operand
  1634. * @param result defines Color3 object to store the result into
  1635. * @returns the unmodified current Color3
  1636. */
  1637. Color3.prototype.subtractToRef = function (otherColor, result) {
  1638. result.r = this.r - otherColor.r;
  1639. result.g = this.g - otherColor.g;
  1640. result.b = this.b - otherColor.b;
  1641. return this;
  1642. };
  1643. /**
  1644. * Copy the current object
  1645. * @returns a new Color3 copied the current one
  1646. */
  1647. Color3.prototype.clone = function () {
  1648. return new Color3(this.r, this.g, this.b);
  1649. };
  1650. /**
  1651. * Copies the rgb values from the source in the current Color3
  1652. * @param source defines the source Color3 object
  1653. * @returns the updated Color3 object
  1654. */
  1655. Color3.prototype.copyFrom = function (source) {
  1656. this.r = source.r;
  1657. this.g = source.g;
  1658. this.b = source.b;
  1659. return this;
  1660. };
  1661. /**
  1662. * Updates the Color3 rgb values from the given floats
  1663. * @param r defines the red component to read from
  1664. * @param g defines the green component to read from
  1665. * @param b defines the blue component to read from
  1666. * @returns the current Color3 object
  1667. */
  1668. Color3.prototype.copyFromFloats = function (r, g, b) {
  1669. this.r = r;
  1670. this.g = g;
  1671. this.b = b;
  1672. return this;
  1673. };
  1674. /**
  1675. * Updates the Color3 rgb values from the given floats
  1676. * @param r defines the red component to read from
  1677. * @param g defines the green component to read from
  1678. * @param b defines the blue component to read from
  1679. * @returns the current Color3 object
  1680. */
  1681. Color3.prototype.set = function (r, g, b) {
  1682. return this.copyFromFloats(r, g, b);
  1683. };
  1684. /**
  1685. * Compute the Color3 hexadecimal code as a string
  1686. * @returns a string containing the hexadecimal representation of the Color3 object
  1687. */
  1688. Color3.prototype.toHexString = function () {
  1689. var intR = (this.r * 255) | 0;
  1690. var intG = (this.g * 255) | 0;
  1691. var intB = (this.b * 255) | 0;
  1692. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1693. };
  1694. /**
  1695. * Computes a new Color3 converted from the current one to linear space
  1696. * @returns a new Color3 object
  1697. */
  1698. Color3.prototype.toLinearSpace = function () {
  1699. var convertedColor = new Color3();
  1700. this.toLinearSpaceToRef(convertedColor);
  1701. return convertedColor;
  1702. };
  1703. /**
  1704. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1705. * @param convertedColor defines the Color3 object where to store the linear space version
  1706. * @returns the unmodified Color3
  1707. */
  1708. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1709. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1710. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1711. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1712. return this;
  1713. };
  1714. /**
  1715. * Computes a new Color3 converted from the current one to gamma space
  1716. * @returns a new Color3 object
  1717. */
  1718. Color3.prototype.toGammaSpace = function () {
  1719. var convertedColor = new Color3();
  1720. this.toGammaSpaceToRef(convertedColor);
  1721. return convertedColor;
  1722. };
  1723. /**
  1724. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1725. * @param convertedColor defines the Color3 object where to store the gamma space version
  1726. * @returns the unmodified Color3
  1727. */
  1728. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1729. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1730. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1731. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1732. return this;
  1733. };
  1734. // Statics
  1735. /**
  1736. * Creates a new Color3 from the string containing valid hexadecimal values
  1737. * @param hex defines a string containing valid hexadecimal values
  1738. * @returns a new Color3 object
  1739. */
  1740. Color3.FromHexString = function (hex) {
  1741. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1742. return new Color3(0, 0, 0);
  1743. }
  1744. var r = parseInt(hex.substring(1, 3), 16);
  1745. var g = parseInt(hex.substring(3, 5), 16);
  1746. var b = parseInt(hex.substring(5, 7), 16);
  1747. return Color3.FromInts(r, g, b);
  1748. };
  1749. /**
  1750. * Creates a new Vector3 from the starting index of the given array
  1751. * @param array defines the source array
  1752. * @param offset defines an offset in the source array
  1753. * @returns a new Color3 object
  1754. */
  1755. Color3.FromArray = function (array, offset) {
  1756. if (offset === void 0) { offset = 0; }
  1757. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1758. };
  1759. /**
  1760. * Creates a new Color3 from integer values (< 256)
  1761. * @param r defines the red component to read from (value between 0 and 255)
  1762. * @param g defines the green component to read from (value between 0 and 255)
  1763. * @param b defines the blue component to read from (value between 0 and 255)
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.FromInts = function (r, g, b) {
  1767. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1768. };
  1769. /**
  1770. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1771. * @param start defines the start Color3 value
  1772. * @param end defines the end Color3 value
  1773. * @param amount defines the gradient value between start and end
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Lerp = function (start, end, amount) {
  1777. var r = start.r + ((end.r - start.r) * amount);
  1778. var g = start.g + ((end.g - start.g) * amount);
  1779. var b = start.b + ((end.b - start.b) * amount);
  1780. return new Color3(r, g, b);
  1781. };
  1782. /**
  1783. * Returns a Color3 value containing a red color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Red = function () { return new Color3(1, 0, 0); };
  1787. /**
  1788. * Returns a Color3 value containing a green color
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.Green = function () { return new Color3(0, 1, 0); };
  1792. /**
  1793. * Returns a Color3 value containing a blue color
  1794. * @returns a new Color3 object
  1795. */
  1796. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1797. /**
  1798. * Returns a Color3 value containing a black color
  1799. * @returns a new Color3 object
  1800. */
  1801. Color3.Black = function () { return new Color3(0, 0, 0); };
  1802. /**
  1803. * Returns a Color3 value containing a white color
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.White = function () { return new Color3(1, 1, 1); };
  1807. /**
  1808. * Returns a Color3 value containing a purple color
  1809. * @returns a new Color3 object
  1810. */
  1811. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1812. /**
  1813. * Returns a Color3 value containing a magenta color
  1814. * @returns a new Color3 object
  1815. */
  1816. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1817. /**
  1818. * Returns a Color3 value containing a yellow color
  1819. * @returns a new Color3 object
  1820. */
  1821. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1822. /**
  1823. * Returns a Color3 value containing a gray color
  1824. * @returns a new Color3 object
  1825. */
  1826. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1827. /**
  1828. * Returns a Color3 value containing a teal color
  1829. * @returns a new Color3 object
  1830. */
  1831. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1832. /**
  1833. * Returns a Color3 value containing a random color
  1834. * @returns a new Color3 object
  1835. */
  1836. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1837. return Color3;
  1838. }());
  1839. BABYLON.Color3 = Color3;
  1840. /**
  1841. * Class used to hold a RBGA color
  1842. */
  1843. var Color4 = /** @class */ (function () {
  1844. /**
  1845. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1846. * @param r defines the red component (between 0 and 1, default is 0)
  1847. * @param g defines the green component (between 0 and 1, default is 0)
  1848. * @param b defines the blue component (between 0 and 1, default is 0)
  1849. * @param a defines the alpha component (between 0 and 1, default is 1)
  1850. */
  1851. function Color4(
  1852. /**
  1853. * Defines the red component (between 0 and 1, default is 0)
  1854. */
  1855. r,
  1856. /**
  1857. * Defines the green component (between 0 and 1, default is 0)
  1858. */
  1859. g,
  1860. /**
  1861. * Defines the blue component (between 0 and 1, default is 0)
  1862. */
  1863. b,
  1864. /**
  1865. * Defines the alpha component (between 0 and 1, default is 1)
  1866. */
  1867. a) {
  1868. if (r === void 0) { r = 0; }
  1869. if (g === void 0) { g = 0; }
  1870. if (b === void 0) { b = 0; }
  1871. if (a === void 0) { a = 1; }
  1872. this.r = r;
  1873. this.g = g;
  1874. this.b = b;
  1875. this.a = a;
  1876. }
  1877. // Operators
  1878. /**
  1879. * Adds in place the given Color4 values to the current Color4 object
  1880. * @param right defines the second operand
  1881. * @returns the current updated Color4 object
  1882. */
  1883. Color4.prototype.addInPlace = function (right) {
  1884. this.r += right.r;
  1885. this.g += right.g;
  1886. this.b += right.b;
  1887. this.a += right.a;
  1888. return this;
  1889. };
  1890. /**
  1891. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1892. * @returns the new array
  1893. */
  1894. Color4.prototype.asArray = function () {
  1895. var result = new Array();
  1896. this.toArray(result, 0);
  1897. return result;
  1898. };
  1899. /**
  1900. * Stores from the starting index in the given array the Color4 successive values
  1901. * @param array defines the array where to store the r,g,b components
  1902. * @param index defines an optional index in the target array to define where to start storing values
  1903. * @returns the current Color4 object
  1904. */
  1905. Color4.prototype.toArray = function (array, index) {
  1906. if (index === undefined) {
  1907. index = 0;
  1908. }
  1909. array[index] = this.r;
  1910. array[index + 1] = this.g;
  1911. array[index + 2] = this.b;
  1912. array[index + 3] = this.a;
  1913. return this;
  1914. };
  1915. /**
  1916. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1917. * @param right defines the second operand
  1918. * @returns a new Color4 object
  1919. */
  1920. Color4.prototype.add = function (right) {
  1921. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1922. };
  1923. /**
  1924. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1925. * @param right defines the second operand
  1926. * @returns a new Color4 object
  1927. */
  1928. Color4.prototype.subtract = function (right) {
  1929. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1930. };
  1931. /**
  1932. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1933. * @param right defines the second operand
  1934. * @param result defines the Color4 object where to store the result
  1935. * @returns the current Color4 object
  1936. */
  1937. Color4.prototype.subtractToRef = function (right, result) {
  1938. result.r = this.r - right.r;
  1939. result.g = this.g - right.g;
  1940. result.b = this.b - right.b;
  1941. result.a = this.a - right.a;
  1942. return this;
  1943. };
  1944. /**
  1945. * Creates a new Color4 with the current Color4 values multiplied by scale
  1946. * @param scale defines the scaling factor to apply
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.scale = function (scale) {
  1950. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1951. };
  1952. /**
  1953. * Multiplies the current Color4 values by scale and stores the result in "result"
  1954. * @param scale defines the scaling factor to apply
  1955. * @param result defines the Color4 object where to store the result
  1956. * @returns the current unmodified Color4
  1957. */
  1958. Color4.prototype.scaleToRef = function (scale, result) {
  1959. result.r = this.r * scale;
  1960. result.g = this.g * scale;
  1961. result.b = this.b * scale;
  1962. result.a = this.a * scale;
  1963. return this;
  1964. };
  1965. /**
  1966. * Scale the current Color4 values by a factor and add the result to a given Color4
  1967. * @param scale defines the scale factor
  1968. * @param result defines the Color4 object where to store the result
  1969. * @returns the unmodified current Color4
  1970. */
  1971. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1972. result.r += this.r * scale;
  1973. result.g += this.g * scale;
  1974. result.b += this.b * scale;
  1975. result.a += this.a * scale;
  1976. return this;
  1977. };
  1978. /**
  1979. * Clamps the rgb values by the min and max values and stores the result into "result"
  1980. * @param min defines minimum clamping value (default is 0)
  1981. * @param max defines maximum clamping value (default is 1)
  1982. * @param result defines color to store the result into.
  1983. * @returns the cuurent Color4
  1984. */
  1985. Color4.prototype.clampToRef = function (min, max, result) {
  1986. if (min === void 0) { min = 0; }
  1987. if (max === void 0) { max = 1; }
  1988. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1989. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1990. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1991. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1992. return this;
  1993. };
  1994. /**
  1995. * Multipy an Color4 value by another and return a new Color4 object
  1996. * @param color defines the Color4 value to multiply by
  1997. * @returns a new Color4 object
  1998. */
  1999. Color4.prototype.multiply = function (color) {
  2000. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2001. };
  2002. /**
  2003. * Multipy a Color4 value by another and push the result in a reference value
  2004. * @param color defines the Color4 value to multiply by
  2005. * @param result defines the Color4 to fill the result in
  2006. * @returns the result Color4
  2007. */
  2008. Color4.prototype.multiplyToRef = function (color, result) {
  2009. result.r = this.r * color.r;
  2010. result.g = this.g * color.g;
  2011. result.b = this.b * color.b;
  2012. result.a = this.a * color.a;
  2013. return result;
  2014. };
  2015. /**
  2016. * Creates a string with the Color4 current values
  2017. * @returns the string representation of the Color4 object
  2018. */
  2019. Color4.prototype.toString = function () {
  2020. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2021. };
  2022. /**
  2023. * Returns the string "Color4"
  2024. * @returns "Color4"
  2025. */
  2026. Color4.prototype.getClassName = function () {
  2027. return "Color4";
  2028. };
  2029. /**
  2030. * Compute the Color4 hash code
  2031. * @returns an unique number that can be used to hash Color4 objects
  2032. */
  2033. Color4.prototype.getHashCode = function () {
  2034. var hash = this.r || 0;
  2035. hash = (hash * 397) ^ (this.g || 0);
  2036. hash = (hash * 397) ^ (this.b || 0);
  2037. hash = (hash * 397) ^ (this.a || 0);
  2038. return hash;
  2039. };
  2040. /**
  2041. * Creates a new Color4 copied from the current one
  2042. * @returns a new Color4 object
  2043. */
  2044. Color4.prototype.clone = function () {
  2045. return new Color4(this.r, this.g, this.b, this.a);
  2046. };
  2047. /**
  2048. * Copies the given Color4 values into the current one
  2049. * @param source defines the source Color4 object
  2050. * @returns the current updated Color4 object
  2051. */
  2052. Color4.prototype.copyFrom = function (source) {
  2053. this.r = source.r;
  2054. this.g = source.g;
  2055. this.b = source.b;
  2056. this.a = source.a;
  2057. return this;
  2058. };
  2059. /**
  2060. * Copies the given float values into the current one
  2061. * @param r defines the red component to read from
  2062. * @param g defines the green component to read from
  2063. * @param b defines the blue component to read from
  2064. * @param a defines the alpha component to read from
  2065. * @returns the current updated Color4 object
  2066. */
  2067. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2068. this.r = r;
  2069. this.g = g;
  2070. this.b = b;
  2071. this.a = a;
  2072. return this;
  2073. };
  2074. /**
  2075. * Copies the given float values into the current one
  2076. * @param r defines the red component to read from
  2077. * @param g defines the green component to read from
  2078. * @param b defines the blue component to read from
  2079. * @param a defines the alpha component to read from
  2080. * @returns the current updated Color4 object
  2081. */
  2082. Color4.prototype.set = function (r, g, b, a) {
  2083. return this.copyFromFloats(r, g, b, a);
  2084. };
  2085. /**
  2086. * Compute the Color4 hexadecimal code as a string
  2087. * @returns a string containing the hexadecimal representation of the Color4 object
  2088. */
  2089. Color4.prototype.toHexString = function () {
  2090. var intR = (this.r * 255) | 0;
  2091. var intG = (this.g * 255) | 0;
  2092. var intB = (this.b * 255) | 0;
  2093. var intA = (this.a * 255) | 0;
  2094. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2095. };
  2096. /**
  2097. * Computes a new Color4 converted from the current one to linear space
  2098. * @returns a new Color4 object
  2099. */
  2100. Color4.prototype.toLinearSpace = function () {
  2101. var convertedColor = new Color4();
  2102. this.toLinearSpaceToRef(convertedColor);
  2103. return convertedColor;
  2104. };
  2105. /**
  2106. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2107. * @param convertedColor defines the Color4 object where to store the linear space version
  2108. * @returns the unmodified Color4
  2109. */
  2110. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2111. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2112. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2113. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2114. convertedColor.a = this.a;
  2115. return this;
  2116. };
  2117. /**
  2118. * Computes a new Color4 converted from the current one to gamma space
  2119. * @returns a new Color4 object
  2120. */
  2121. Color4.prototype.toGammaSpace = function () {
  2122. var convertedColor = new Color4();
  2123. this.toGammaSpaceToRef(convertedColor);
  2124. return convertedColor;
  2125. };
  2126. /**
  2127. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2128. * @param convertedColor defines the Color4 object where to store the gamma space version
  2129. * @returns the unmodified Color4
  2130. */
  2131. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2132. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2133. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2134. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2135. convertedColor.a = this.a;
  2136. return this;
  2137. };
  2138. // Statics
  2139. /**
  2140. * Creates a new Color4 from the string containing valid hexadecimal values
  2141. * @param hex defines a string containing valid hexadecimal values
  2142. * @returns a new Color4 object
  2143. */
  2144. Color4.FromHexString = function (hex) {
  2145. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2146. return new Color4(0.0, 0.0, 0.0, 0.0);
  2147. }
  2148. var r = parseInt(hex.substring(1, 3), 16);
  2149. var g = parseInt(hex.substring(3, 5), 16);
  2150. var b = parseInt(hex.substring(5, 7), 16);
  2151. var a = parseInt(hex.substring(7, 9), 16);
  2152. return Color4.FromInts(r, g, b, a);
  2153. };
  2154. /**
  2155. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2156. * @param left defines the start value
  2157. * @param right defines the end value
  2158. * @param amount defines the gradient factor
  2159. * @returns a new Color4 object
  2160. */
  2161. Color4.Lerp = function (left, right, amount) {
  2162. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2163. Color4.LerpToRef(left, right, amount, result);
  2164. return result;
  2165. };
  2166. /**
  2167. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2168. * @param left defines the start value
  2169. * @param right defines the end value
  2170. * @param amount defines the gradient factor
  2171. * @param result defines the Color4 object where to store data
  2172. */
  2173. Color4.LerpToRef = function (left, right, amount, result) {
  2174. result.r = left.r + (right.r - left.r) * amount;
  2175. result.g = left.g + (right.g - left.g) * amount;
  2176. result.b = left.b + (right.b - left.b) * amount;
  2177. result.a = left.a + (right.a - left.a) * amount;
  2178. };
  2179. /**
  2180. * Creates a new Color4 from the starting index element of the given array
  2181. * @param array defines the source array to read from
  2182. * @param offset defines the offset in the source array
  2183. * @returns a new Color4 object
  2184. */
  2185. Color4.FromArray = function (array, offset) {
  2186. if (offset === void 0) { offset = 0; }
  2187. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2188. };
  2189. /**
  2190. * Creates a new Color3 from integer values (< 256)
  2191. * @param r defines the red component to read from (value between 0 and 255)
  2192. * @param g defines the green component to read from (value between 0 and 255)
  2193. * @param b defines the blue component to read from (value between 0 and 255)
  2194. * @param a defines the alpha component to read from (value between 0 and 255)
  2195. * @returns a new Color3 object
  2196. */
  2197. Color4.FromInts = function (r, g, b, a) {
  2198. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2199. };
  2200. /**
  2201. * Check the content of a given array and convert it to an array containing RGBA data
  2202. * If the original array was already containing count * 4 values then it is returned directly
  2203. * @param colors defines the array to check
  2204. * @param count defines the number of RGBA data to expect
  2205. * @returns an array containing count * 4 values (RGBA)
  2206. */
  2207. Color4.CheckColors4 = function (colors, count) {
  2208. // Check if color3 was used
  2209. if (colors.length === count * 3) {
  2210. var colors4 = [];
  2211. for (var index = 0; index < colors.length; index += 3) {
  2212. var newIndex = (index / 3) * 4;
  2213. colors4[newIndex] = colors[index];
  2214. colors4[newIndex + 1] = colors[index + 1];
  2215. colors4[newIndex + 2] = colors[index + 2];
  2216. colors4[newIndex + 3] = 1.0;
  2217. }
  2218. return colors4;
  2219. }
  2220. return colors;
  2221. };
  2222. return Color4;
  2223. }());
  2224. BABYLON.Color4 = Color4;
  2225. /**
  2226. * Class representing a vector containing 2 coordinates
  2227. */
  2228. var Vector2 = /** @class */ (function () {
  2229. /**
  2230. * Creates a new Vector2 from the given x and y coordinates
  2231. * @param x defines the first coordinate
  2232. * @param y defines the second coordinate
  2233. */
  2234. function Vector2(
  2235. /** defines the first coordinate */
  2236. x,
  2237. /** defines the second coordinate */
  2238. y) {
  2239. if (x === void 0) { x = 0; }
  2240. if (y === void 0) { y = 0; }
  2241. this.x = x;
  2242. this.y = y;
  2243. }
  2244. /**
  2245. * Gets a string with the Vector2 coordinates
  2246. * @returns a string with the Vector2 coordinates
  2247. */
  2248. Vector2.prototype.toString = function () {
  2249. return "{X: " + this.x + " Y:" + this.y + "}";
  2250. };
  2251. /**
  2252. * Gets class name
  2253. * @returns the string "Vector2"
  2254. */
  2255. Vector2.prototype.getClassName = function () {
  2256. return "Vector2";
  2257. };
  2258. /**
  2259. * Gets current vector hash code
  2260. * @returns the Vector2 hash code as a number
  2261. */
  2262. Vector2.prototype.getHashCode = function () {
  2263. var hash = this.x || 0;
  2264. hash = (hash * 397) ^ (this.y || 0);
  2265. return hash;
  2266. };
  2267. // Operators
  2268. /**
  2269. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2270. * @param array defines the source array
  2271. * @param index defines the offset in source array
  2272. * @returns the current Vector2
  2273. */
  2274. Vector2.prototype.toArray = function (array, index) {
  2275. if (index === void 0) { index = 0; }
  2276. array[index] = this.x;
  2277. array[index + 1] = this.y;
  2278. return this;
  2279. };
  2280. /**
  2281. * Copy the current vector to an array
  2282. * @returns a new array with 2 elements: the Vector2 coordinates.
  2283. */
  2284. Vector2.prototype.asArray = function () {
  2285. var result = new Array();
  2286. this.toArray(result, 0);
  2287. return result;
  2288. };
  2289. /**
  2290. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2291. * @param source defines the source Vector2
  2292. * @returns the current updated Vector2
  2293. */
  2294. Vector2.prototype.copyFrom = function (source) {
  2295. this.x = source.x;
  2296. this.y = source.y;
  2297. return this;
  2298. };
  2299. /**
  2300. * Sets the Vector2 coordinates with the given floats
  2301. * @param x defines the first coordinate
  2302. * @param y defines the second coordinate
  2303. * @returns the current updated Vector2
  2304. */
  2305. Vector2.prototype.copyFromFloats = function (x, y) {
  2306. this.x = x;
  2307. this.y = y;
  2308. return this;
  2309. };
  2310. /**
  2311. * Sets the Vector2 coordinates with the given floats
  2312. * @param x defines the first coordinate
  2313. * @param y defines the second coordinate
  2314. * @returns the current updated Vector2
  2315. */
  2316. Vector2.prototype.set = function (x, y) {
  2317. return this.copyFromFloats(x, y);
  2318. };
  2319. /**
  2320. * Add another vector with the current one
  2321. * @param otherVector defines the other vector
  2322. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2323. */
  2324. Vector2.prototype.add = function (otherVector) {
  2325. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2326. };
  2327. /**
  2328. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2329. * @param otherVector defines the other vector
  2330. * @param result defines the target vector
  2331. * @returns the unmodified current Vector2
  2332. */
  2333. Vector2.prototype.addToRef = function (otherVector, result) {
  2334. result.x = this.x + otherVector.x;
  2335. result.y = this.y + otherVector.y;
  2336. return this;
  2337. };
  2338. /**
  2339. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2340. * @param otherVector defines the other vector
  2341. * @returns the current updated Vector2
  2342. */
  2343. Vector2.prototype.addInPlace = function (otherVector) {
  2344. this.x += otherVector.x;
  2345. this.y += otherVector.y;
  2346. return this;
  2347. };
  2348. /**
  2349. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2350. * @param otherVector defines the other vector
  2351. * @returns a new Vector2
  2352. */
  2353. Vector2.prototype.addVector3 = function (otherVector) {
  2354. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2355. };
  2356. /**
  2357. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2358. * @param otherVector defines the other vector
  2359. * @returns a new Vector2
  2360. */
  2361. Vector2.prototype.subtract = function (otherVector) {
  2362. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2363. };
  2364. /**
  2365. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2366. * @param otherVector defines the other vector
  2367. * @param result defines the target vector
  2368. * @returns the unmodified current Vector2
  2369. */
  2370. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2371. result.x = this.x - otherVector.x;
  2372. result.y = this.y - otherVector.y;
  2373. return this;
  2374. };
  2375. /**
  2376. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2377. * @param otherVector defines the other vector
  2378. * @returns the current updated Vector2
  2379. */
  2380. Vector2.prototype.subtractInPlace = function (otherVector) {
  2381. this.x -= otherVector.x;
  2382. this.y -= otherVector.y;
  2383. return this;
  2384. };
  2385. /**
  2386. * Multiplies in place the current Vector2 coordinates by the given ones
  2387. * @param otherVector defines the other vector
  2388. * @returns the current updated Vector2
  2389. */
  2390. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2391. this.x *= otherVector.x;
  2392. this.y *= otherVector.y;
  2393. return this;
  2394. };
  2395. /**
  2396. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2397. * @param otherVector defines the other vector
  2398. * @returns a new Vector2
  2399. */
  2400. Vector2.prototype.multiply = function (otherVector) {
  2401. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2402. };
  2403. /**
  2404. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2405. * @param otherVector defines the other vector
  2406. * @param result defines the target vector
  2407. * @returns the unmodified current Vector2
  2408. */
  2409. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2410. result.x = this.x * otherVector.x;
  2411. result.y = this.y * otherVector.y;
  2412. return this;
  2413. };
  2414. /**
  2415. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2416. * @param x defines the first coordinate
  2417. * @param y defines the second coordinate
  2418. * @returns a new Vector2
  2419. */
  2420. Vector2.prototype.multiplyByFloats = function (x, y) {
  2421. return new Vector2(this.x * x, this.y * y);
  2422. };
  2423. /**
  2424. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2425. * @param otherVector defines the other vector
  2426. * @returns a new Vector2
  2427. */
  2428. Vector2.prototype.divide = function (otherVector) {
  2429. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2430. };
  2431. /**
  2432. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2433. * @param otherVector defines the other vector
  2434. * @param result defines the target vector
  2435. * @returns the unmodified current Vector2
  2436. */
  2437. Vector2.prototype.divideToRef = function (otherVector, result) {
  2438. result.x = this.x / otherVector.x;
  2439. result.y = this.y / otherVector.y;
  2440. return this;
  2441. };
  2442. /**
  2443. * Divides the current Vector2 coordinates by the given ones
  2444. * @param otherVector defines the other vector
  2445. * @returns the current updated Vector2
  2446. */
  2447. Vector2.prototype.divideInPlace = function (otherVector) {
  2448. return this.divideToRef(otherVector, this);
  2449. };
  2450. /**
  2451. * Gets a new Vector2 with current Vector2 negated coordinates
  2452. * @returns a new Vector2
  2453. */
  2454. Vector2.prototype.negate = function () {
  2455. return new Vector2(-this.x, -this.y);
  2456. };
  2457. /**
  2458. * Multiply the Vector2 coordinates by scale
  2459. * @param scale defines the scaling factor
  2460. * @returns the current updated Vector2
  2461. */
  2462. Vector2.prototype.scaleInPlace = function (scale) {
  2463. this.x *= scale;
  2464. this.y *= scale;
  2465. return this;
  2466. };
  2467. /**
  2468. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2469. * @param scale defines the scaling factor
  2470. * @returns a new Vector2
  2471. */
  2472. Vector2.prototype.scale = function (scale) {
  2473. var result = new Vector2(0, 0);
  2474. this.scaleToRef(scale, result);
  2475. return result;
  2476. };
  2477. /**
  2478. * Scale the current Vector2 values by a factor to a given Vector2
  2479. * @param scale defines the scale factor
  2480. * @param result defines the Vector2 object where to store the result
  2481. * @returns the unmodified current Vector2
  2482. */
  2483. Vector2.prototype.scaleToRef = function (scale, result) {
  2484. result.x = this.x * scale;
  2485. result.y = this.y * scale;
  2486. return this;
  2487. };
  2488. /**
  2489. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2490. * @param scale defines the scale factor
  2491. * @param result defines the Vector2 object where to store the result
  2492. * @returns the unmodified current Vector2
  2493. */
  2494. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2495. result.x += this.x * scale;
  2496. result.y += this.y * scale;
  2497. return this;
  2498. };
  2499. /**
  2500. * Gets a boolean if two vectors are equals
  2501. * @param otherVector defines the other vector
  2502. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2503. */
  2504. Vector2.prototype.equals = function (otherVector) {
  2505. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2506. };
  2507. /**
  2508. * Gets a boolean if two vectors are equals (using an epsilon value)
  2509. * @param otherVector defines the other vector
  2510. * @param epsilon defines the minimal distance to consider equality
  2511. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2512. */
  2513. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2514. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2515. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2516. };
  2517. /**
  2518. * Gets a new Vector2 from current Vector2 floored values
  2519. * @returns a new Vector2
  2520. */
  2521. Vector2.prototype.floor = function () {
  2522. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2523. };
  2524. /**
  2525. * Gets a new Vector2 from current Vector2 floored values
  2526. * @returns a new Vector2
  2527. */
  2528. Vector2.prototype.fract = function () {
  2529. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2530. };
  2531. // Properties
  2532. /**
  2533. * Gets the length of the vector
  2534. * @returns the vector length (float)
  2535. */
  2536. Vector2.prototype.length = function () {
  2537. return Math.sqrt(this.x * this.x + this.y * this.y);
  2538. };
  2539. /**
  2540. * Gets the vector squared length
  2541. * @returns the vector squared length (float)
  2542. */
  2543. Vector2.prototype.lengthSquared = function () {
  2544. return (this.x * this.x + this.y * this.y);
  2545. };
  2546. // Methods
  2547. /**
  2548. * Normalize the vector
  2549. * @returns the current updated Vector2
  2550. */
  2551. Vector2.prototype.normalize = function () {
  2552. var len = this.length();
  2553. if (len === 0)
  2554. return this;
  2555. var num = 1.0 / len;
  2556. this.x *= num;
  2557. this.y *= num;
  2558. return this;
  2559. };
  2560. /**
  2561. * Gets a new Vector2 copied from the Vector2
  2562. * @returns a new Vector2
  2563. */
  2564. Vector2.prototype.clone = function () {
  2565. return new Vector2(this.x, this.y);
  2566. };
  2567. // Statics
  2568. /**
  2569. * Gets a new Vector2(0, 0)
  2570. * @returns a new Vector2
  2571. */
  2572. Vector2.Zero = function () {
  2573. return new Vector2(0, 0);
  2574. };
  2575. /**
  2576. * Gets a new Vector2(1, 1)
  2577. * @returns a new Vector2
  2578. */
  2579. Vector2.One = function () {
  2580. return new Vector2(1, 1);
  2581. };
  2582. /**
  2583. * Gets a new Vector2 set from the given index element of the given array
  2584. * @param array defines the data source
  2585. * @param offset defines the offset in the data source
  2586. * @returns a new Vector2
  2587. */
  2588. Vector2.FromArray = function (array, offset) {
  2589. if (offset === void 0) { offset = 0; }
  2590. return new Vector2(array[offset], array[offset + 1]);
  2591. };
  2592. /**
  2593. * Sets "result" from the given index element of the given array
  2594. * @param array defines the data source
  2595. * @param offset defines the offset in the data source
  2596. * @param result defines the target vector
  2597. */
  2598. Vector2.FromArrayToRef = function (array, offset, result) {
  2599. result.x = array[offset];
  2600. result.y = array[offset + 1];
  2601. };
  2602. /**
  2603. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2604. * @param value1 defines 1st point of control
  2605. * @param value2 defines 2nd point of control
  2606. * @param value3 defines 3rd point of control
  2607. * @param value4 defines 4th point of control
  2608. * @param amount defines the interpolation factor
  2609. * @returns a new Vector2
  2610. */
  2611. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2612. var squared = amount * amount;
  2613. var cubed = amount * squared;
  2614. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2615. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2616. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2617. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2618. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2619. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2620. return new Vector2(x, y);
  2621. };
  2622. /**
  2623. * 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".
  2624. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2625. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2626. * @param value defines the value to clamp
  2627. * @param min defines the lower limit
  2628. * @param max defines the upper limit
  2629. * @returns a new Vector2
  2630. */
  2631. Vector2.Clamp = function (value, min, max) {
  2632. var x = value.x;
  2633. x = (x > max.x) ? max.x : x;
  2634. x = (x < min.x) ? min.x : x;
  2635. var y = value.y;
  2636. y = (y > max.y) ? max.y : y;
  2637. y = (y < min.y) ? min.y : y;
  2638. return new Vector2(x, y);
  2639. };
  2640. /**
  2641. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2642. * @param value1 defines the 1st control point
  2643. * @param tangent1 defines the outgoing tangent
  2644. * @param value2 defines the 2nd control point
  2645. * @param tangent2 defines the incoming tangent
  2646. * @param amount defines the interpolation factor
  2647. * @returns a new Vector2
  2648. */
  2649. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2650. var squared = amount * amount;
  2651. var cubed = amount * squared;
  2652. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2653. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2654. var part3 = (cubed - (2.0 * squared)) + amount;
  2655. var part4 = cubed - squared;
  2656. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2657. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2658. return new Vector2(x, y);
  2659. };
  2660. /**
  2661. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2662. * @param start defines the start vector
  2663. * @param end defines the end vector
  2664. * @param amount defines the interpolation factor
  2665. * @returns a new Vector2
  2666. */
  2667. Vector2.Lerp = function (start, end, amount) {
  2668. var x = start.x + ((end.x - start.x) * amount);
  2669. var y = start.y + ((end.y - start.y) * amount);
  2670. return new Vector2(x, y);
  2671. };
  2672. /**
  2673. * Gets the dot product of the vector "left" and the vector "right"
  2674. * @param left defines first vector
  2675. * @param right defines second vector
  2676. * @returns the dot product (float)
  2677. */
  2678. Vector2.Dot = function (left, right) {
  2679. return left.x * right.x + left.y * right.y;
  2680. };
  2681. /**
  2682. * Returns a new Vector2 equal to the normalized given vector
  2683. * @param vector defines the vector to normalize
  2684. * @returns a new Vector2
  2685. */
  2686. Vector2.Normalize = function (vector) {
  2687. var newVector = vector.clone();
  2688. newVector.normalize();
  2689. return newVector;
  2690. };
  2691. /**
  2692. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2693. * @param left defines 1st vector
  2694. * @param right defines 2nd vector
  2695. * @returns a new Vector2
  2696. */
  2697. Vector2.Minimize = function (left, right) {
  2698. var x = (left.x < right.x) ? left.x : right.x;
  2699. var y = (left.y < right.y) ? left.y : right.y;
  2700. return new Vector2(x, y);
  2701. };
  2702. /**
  2703. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2704. * @param left defines 1st vector
  2705. * @param right defines 2nd vector
  2706. * @returns a new Vector2
  2707. */
  2708. Vector2.Maximize = function (left, right) {
  2709. var x = (left.x > right.x) ? left.x : right.x;
  2710. var y = (left.y > right.y) ? left.y : right.y;
  2711. return new Vector2(x, y);
  2712. };
  2713. /**
  2714. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2715. * @param vector defines the vector to transform
  2716. * @param transformation defines the matrix to apply
  2717. * @returns a new Vector2
  2718. */
  2719. Vector2.Transform = function (vector, transformation) {
  2720. var r = Vector2.Zero();
  2721. Vector2.TransformToRef(vector, transformation, r);
  2722. return r;
  2723. };
  2724. /**
  2725. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2726. * @param vector defines the vector to transform
  2727. * @param transformation defines the matrix to apply
  2728. * @param result defines the target vector
  2729. */
  2730. Vector2.TransformToRef = function (vector, transformation, result) {
  2731. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2732. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2733. result.x = x;
  2734. result.y = y;
  2735. };
  2736. /**
  2737. * Determines if a given vector is included in a triangle
  2738. * @param p defines the vector to test
  2739. * @param p0 defines 1st triangle point
  2740. * @param p1 defines 2nd triangle point
  2741. * @param p2 defines 3rd triangle point
  2742. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2743. */
  2744. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2745. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2746. var sign = a < 0 ? -1 : 1;
  2747. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2748. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2749. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2750. };
  2751. /**
  2752. * Gets the distance between the vectors "value1" and "value2"
  2753. * @param value1 defines first vector
  2754. * @param value2 defines second vector
  2755. * @returns the distance between vectors
  2756. */
  2757. Vector2.Distance = function (value1, value2) {
  2758. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2759. };
  2760. /**
  2761. * Returns the squared distance between the vectors "value1" and "value2"
  2762. * @param value1 defines first vector
  2763. * @param value2 defines second vector
  2764. * @returns the squared distance between vectors
  2765. */
  2766. Vector2.DistanceSquared = function (value1, value2) {
  2767. var x = value1.x - value2.x;
  2768. var y = value1.y - value2.y;
  2769. return (x * x) + (y * y);
  2770. };
  2771. /**
  2772. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2773. * @param value1 defines first vector
  2774. * @param value2 defines second vector
  2775. * @returns a new Vector2
  2776. */
  2777. Vector2.Center = function (value1, value2) {
  2778. var center = value1.add(value2);
  2779. center.scaleInPlace(0.5);
  2780. return center;
  2781. };
  2782. /**
  2783. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2784. * @param p defines the middle point
  2785. * @param segA defines one point of the segment
  2786. * @param segB defines the other point of the segment
  2787. * @returns the shortest distance
  2788. */
  2789. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2790. var l2 = Vector2.DistanceSquared(segA, segB);
  2791. if (l2 === 0.0) {
  2792. return Vector2.Distance(p, segA);
  2793. }
  2794. var v = segB.subtract(segA);
  2795. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2796. var proj = segA.add(v.multiplyByFloats(t, t));
  2797. return Vector2.Distance(p, proj);
  2798. };
  2799. return Vector2;
  2800. }());
  2801. BABYLON.Vector2 = Vector2;
  2802. /**
  2803. * Classed used to store (x,y,z) vector representation
  2804. * A Vector3 is the main object used in 3D geometry
  2805. * It can represent etiher the coordinates of a point the space, either a direction
  2806. * Reminder: Babylon.js uses a left handed forward facing system
  2807. */
  2808. var Vector3 = /** @class */ (function () {
  2809. /**
  2810. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2811. * @param x defines the first coordinates (on X axis)
  2812. * @param y defines the second coordinates (on Y axis)
  2813. * @param z defines the third coordinates (on Z axis)
  2814. */
  2815. function Vector3(
  2816. /**
  2817. * Defines the first coordinates (on X axis)
  2818. */
  2819. x,
  2820. /**
  2821. * Defines the second coordinates (on Y axis)
  2822. */
  2823. y,
  2824. /**
  2825. * Defines the third coordinates (on Z axis)
  2826. */
  2827. z) {
  2828. if (x === void 0) { x = 0; }
  2829. if (y === void 0) { y = 0; }
  2830. if (z === void 0) { z = 0; }
  2831. this.x = x;
  2832. this.y = y;
  2833. this.z = z;
  2834. }
  2835. /**
  2836. * Creates a string representation of the Vector3
  2837. * @returns a string with the Vector3 coordinates.
  2838. */
  2839. Vector3.prototype.toString = function () {
  2840. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2841. };
  2842. /**
  2843. * Gets the class name
  2844. * @returns the string "Vector3"
  2845. */
  2846. Vector3.prototype.getClassName = function () {
  2847. return "Vector3";
  2848. };
  2849. /**
  2850. * Creates the Vector3 hash code
  2851. * @returns a number which tends to be unique between Vector3 instances
  2852. */
  2853. Vector3.prototype.getHashCode = function () {
  2854. var hash = this.x || 0;
  2855. hash = (hash * 397) ^ (this.y || 0);
  2856. hash = (hash * 397) ^ (this.z || 0);
  2857. return hash;
  2858. };
  2859. // Operators
  2860. /**
  2861. * Creates an array containing three elements : the coordinates of the Vector3
  2862. * @returns a new array of numbers
  2863. */
  2864. Vector3.prototype.asArray = function () {
  2865. var result = [];
  2866. this.toArray(result, 0);
  2867. return result;
  2868. };
  2869. /**
  2870. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2871. * @param array defines the destination array
  2872. * @param index defines the offset in the destination array
  2873. * @returns the current Vector3
  2874. */
  2875. Vector3.prototype.toArray = function (array, index) {
  2876. if (index === void 0) { index = 0; }
  2877. array[index] = this.x;
  2878. array[index + 1] = this.y;
  2879. array[index + 2] = this.z;
  2880. return this;
  2881. };
  2882. /**
  2883. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2884. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2885. */
  2886. Vector3.prototype.toQuaternion = function () {
  2887. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2888. };
  2889. /**
  2890. * Adds the given vector to the current Vector3
  2891. * @param otherVector defines the second operand
  2892. * @returns the current updated Vector3
  2893. */
  2894. Vector3.prototype.addInPlace = function (otherVector) {
  2895. this.x += otherVector.x;
  2896. this.y += otherVector.y;
  2897. this.z += otherVector.z;
  2898. return this;
  2899. };
  2900. /**
  2901. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2902. * @param otherVector defines the second operand
  2903. * @returns the resulting Vector3
  2904. */
  2905. Vector3.prototype.add = function (otherVector) {
  2906. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2907. };
  2908. /**
  2909. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2910. * @param otherVector defines the second operand
  2911. * @param result defines the Vector3 object where to store the result
  2912. * @returns the current Vector3
  2913. */
  2914. Vector3.prototype.addToRef = function (otherVector, result) {
  2915. result.x = this.x + otherVector.x;
  2916. result.y = this.y + otherVector.y;
  2917. result.z = this.z + otherVector.z;
  2918. return this;
  2919. };
  2920. /**
  2921. * Subtract the given vector from the current Vector3
  2922. * @param otherVector defines the second operand
  2923. * @returns the current updated Vector3
  2924. */
  2925. Vector3.prototype.subtractInPlace = function (otherVector) {
  2926. this.x -= otherVector.x;
  2927. this.y -= otherVector.y;
  2928. this.z -= otherVector.z;
  2929. return this;
  2930. };
  2931. /**
  2932. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2933. * @param otherVector defines the second operand
  2934. * @returns the resulting Vector3
  2935. */
  2936. Vector3.prototype.subtract = function (otherVector) {
  2937. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2938. };
  2939. /**
  2940. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2941. * @param otherVector defines the second operand
  2942. * @param result defines the Vector3 object where to store the result
  2943. * @returns the current Vector3
  2944. */
  2945. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2946. result.x = this.x - otherVector.x;
  2947. result.y = this.y - otherVector.y;
  2948. result.z = this.z - otherVector.z;
  2949. return this;
  2950. };
  2951. /**
  2952. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2953. * @param x defines the x coordinate of the operand
  2954. * @param y defines the y coordinate of the operand
  2955. * @param z defines the z coordinate of the operand
  2956. * @returns the resulting Vector3
  2957. */
  2958. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2959. return new Vector3(this.x - x, this.y - y, this.z - z);
  2960. };
  2961. /**
  2962. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2963. * @param x defines the x coordinate of the operand
  2964. * @param y defines the y coordinate of the operand
  2965. * @param z defines the z coordinate of the operand
  2966. * @param result defines the Vector3 object where to store the result
  2967. * @returns the current Vector3
  2968. */
  2969. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2970. result.x = this.x - x;
  2971. result.y = this.y - y;
  2972. result.z = this.z - z;
  2973. return this;
  2974. };
  2975. /**
  2976. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2977. * @returns a new Vector3
  2978. */
  2979. Vector3.prototype.negate = function () {
  2980. return new Vector3(-this.x, -this.y, -this.z);
  2981. };
  2982. /**
  2983. * Multiplies the Vector3 coordinates by the float "scale"
  2984. * @param scale defines the multiplier factor
  2985. * @returns the current updated Vector3
  2986. */
  2987. Vector3.prototype.scaleInPlace = function (scale) {
  2988. this.x *= scale;
  2989. this.y *= scale;
  2990. this.z *= scale;
  2991. return this;
  2992. };
  2993. /**
  2994. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2995. * @param scale defines the multiplier factor
  2996. * @returns a new Vector3
  2997. */
  2998. Vector3.prototype.scale = function (scale) {
  2999. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3000. };
  3001. /**
  3002. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3003. * @param scale defines the multiplier factor
  3004. * @param result defines the Vector3 object where to store the result
  3005. * @returns the current Vector3
  3006. */
  3007. Vector3.prototype.scaleToRef = function (scale, result) {
  3008. result.x = this.x * scale;
  3009. result.y = this.y * scale;
  3010. result.z = this.z * scale;
  3011. return this;
  3012. };
  3013. /**
  3014. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3015. * @param scale defines the scale factor
  3016. * @param result defines the Vector3 object where to store the result
  3017. * @returns the unmodified current Vector3
  3018. */
  3019. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3020. result.x += this.x * scale;
  3021. result.y += this.y * scale;
  3022. result.z += this.z * scale;
  3023. return this;
  3024. };
  3025. /**
  3026. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3027. * @param otherVector defines the second operand
  3028. * @returns true if both vectors are equals
  3029. */
  3030. Vector3.prototype.equals = function (otherVector) {
  3031. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3032. };
  3033. /**
  3034. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3035. * @param otherVector defines the second operand
  3036. * @param epsilon defines the minimal distance to define values as equals
  3037. * @returns true if both vectors are distant less than epsilon
  3038. */
  3039. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3040. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3041. 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);
  3042. };
  3043. /**
  3044. * Returns true if the current Vector3 coordinates equals the given floats
  3045. * @param x defines the x coordinate of the operand
  3046. * @param y defines the y coordinate of the operand
  3047. * @param z defines the z coordinate of the operand
  3048. * @returns true if both vectors are equals
  3049. */
  3050. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3051. return this.x === x && this.y === y && this.z === z;
  3052. };
  3053. /**
  3054. * Multiplies the current Vector3 coordinates by the given ones
  3055. * @param otherVector defines the second operand
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3059. this.x *= otherVector.x;
  3060. this.y *= otherVector.y;
  3061. this.z *= otherVector.z;
  3062. return this;
  3063. };
  3064. /**
  3065. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3066. * @param otherVector defines the second operand
  3067. * @returns the new Vector3
  3068. */
  3069. Vector3.prototype.multiply = function (otherVector) {
  3070. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3071. };
  3072. /**
  3073. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3074. * @param otherVector defines the second operand
  3075. * @param result defines the Vector3 object where to store the result
  3076. * @returns the current Vector3
  3077. */
  3078. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3079. result.x = this.x * otherVector.x;
  3080. result.y = this.y * otherVector.y;
  3081. result.z = this.z * otherVector.z;
  3082. return this;
  3083. };
  3084. /**
  3085. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3086. * @param x defines the x coordinate of the operand
  3087. * @param y defines the y coordinate of the operand
  3088. * @param z defines the z coordinate of the operand
  3089. * @returns the new Vector3
  3090. */
  3091. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3092. return new Vector3(this.x * x, this.y * y, this.z * z);
  3093. };
  3094. /**
  3095. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3096. * @param otherVector defines the second operand
  3097. * @returns the new Vector3
  3098. */
  3099. Vector3.prototype.divide = function (otherVector) {
  3100. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3101. };
  3102. /**
  3103. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3104. * @param otherVector defines the second operand
  3105. * @param result defines the Vector3 object where to store the result
  3106. * @returns the current Vector3
  3107. */
  3108. Vector3.prototype.divideToRef = function (otherVector, result) {
  3109. result.x = this.x / otherVector.x;
  3110. result.y = this.y / otherVector.y;
  3111. result.z = this.z / otherVector.z;
  3112. return this;
  3113. };
  3114. /**
  3115. * Divides the current Vector3 coordinates by the given ones.
  3116. * @param otherVector defines the second operand
  3117. * @returns the current updated Vector3
  3118. */
  3119. Vector3.prototype.divideInPlace = function (otherVector) {
  3120. return this.divideToRef(otherVector, this);
  3121. };
  3122. /**
  3123. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3124. * @param other defines the second operand
  3125. * @returns the current updated Vector3
  3126. */
  3127. Vector3.prototype.minimizeInPlace = function (other) {
  3128. if (other.x < this.x)
  3129. this.x = other.x;
  3130. if (other.y < this.y)
  3131. this.y = other.y;
  3132. if (other.z < this.z)
  3133. this.z = other.z;
  3134. return this;
  3135. };
  3136. /**
  3137. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3138. * @param other defines the second operand
  3139. * @returns the current updated Vector3
  3140. */
  3141. Vector3.prototype.maximizeInPlace = function (other) {
  3142. if (other.x > this.x)
  3143. this.x = other.x;
  3144. if (other.y > this.y)
  3145. this.y = other.y;
  3146. if (other.z > this.z)
  3147. this.z = other.z;
  3148. return this;
  3149. };
  3150. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3151. /**
  3152. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3153. */
  3154. get: function () {
  3155. var absX = Math.abs(this.x);
  3156. var absY = Math.abs(this.y);
  3157. if (absX !== absY) {
  3158. return true;
  3159. }
  3160. var absZ = Math.abs(this.z);
  3161. if (absX !== absZ) {
  3162. return true;
  3163. }
  3164. if (absY !== absZ) {
  3165. return true;
  3166. }
  3167. return false;
  3168. },
  3169. enumerable: true,
  3170. configurable: true
  3171. });
  3172. /**
  3173. * Gets a new Vector3 from current Vector3 floored values
  3174. * @returns a new Vector3
  3175. */
  3176. Vector3.prototype.floor = function () {
  3177. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3178. };
  3179. /**
  3180. * Gets a new Vector3 from current Vector3 floored values
  3181. * @returns a new Vector3
  3182. */
  3183. Vector3.prototype.fract = function () {
  3184. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3185. };
  3186. // Properties
  3187. /**
  3188. * Gets the length of the Vector3
  3189. * @returns the length of the Vecto3
  3190. */
  3191. Vector3.prototype.length = function () {
  3192. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3193. };
  3194. /**
  3195. * Gets the squared length of the Vector3
  3196. * @returns squared length of the Vector3
  3197. */
  3198. Vector3.prototype.lengthSquared = function () {
  3199. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3200. };
  3201. /**
  3202. * Normalize the current Vector3.
  3203. * Please note that this is an in place operation.
  3204. * @returns the current updated Vector3
  3205. */
  3206. Vector3.prototype.normalize = function () {
  3207. var len = this.length();
  3208. if (len === 0 || len === 1.0)
  3209. return this;
  3210. var num = 1.0 / len;
  3211. this.x *= num;
  3212. this.y *= num;
  3213. this.z *= num;
  3214. return this;
  3215. };
  3216. /**
  3217. * Normalize the current Vector3 to a new vector
  3218. * @returns the new Vector3
  3219. */
  3220. Vector3.prototype.normalizeToNew = function () {
  3221. var normalized = new Vector3(0, 0, 0);
  3222. this.normalizeToRef(normalized);
  3223. return normalized;
  3224. };
  3225. /**
  3226. * Normalize the current Vector3 to the reference
  3227. * @param reference define the Vector3 to update
  3228. * @returns the updated Vector3
  3229. */
  3230. Vector3.prototype.normalizeToRef = function (reference) {
  3231. var len = this.length();
  3232. if (len === 0 || len === 1.0) {
  3233. reference.set(this.x, this.y, this.z);
  3234. return reference;
  3235. }
  3236. var scale = 1.0 / len;
  3237. this.scaleToRef(scale, reference);
  3238. return reference;
  3239. };
  3240. /**
  3241. * Creates a new Vector3 copied from the current Vector3
  3242. * @returns the new Vector3
  3243. */
  3244. Vector3.prototype.clone = function () {
  3245. return new Vector3(this.x, this.y, this.z);
  3246. };
  3247. /**
  3248. * Copies the given vector coordinates to the current Vector3 ones
  3249. * @param source defines the source Vector3
  3250. * @returns the current updated Vector3
  3251. */
  3252. Vector3.prototype.copyFrom = function (source) {
  3253. this.x = source.x;
  3254. this.y = source.y;
  3255. this.z = source.z;
  3256. return this;
  3257. };
  3258. /**
  3259. * Copies the given floats to the current Vector3 coordinates
  3260. * @param x defines the x coordinate of the operand
  3261. * @param y defines the y coordinate of the operand
  3262. * @param z defines the z coordinate of the operand
  3263. * @returns the current updated Vector3
  3264. */
  3265. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3266. this.x = x;
  3267. this.y = y;
  3268. this.z = z;
  3269. return this;
  3270. };
  3271. /**
  3272. * Copies the given floats to the current Vector3 coordinates
  3273. * @param x defines the x coordinate of the operand
  3274. * @param y defines the y coordinate of the operand
  3275. * @param z defines the z coordinate of the operand
  3276. * @returns the current updated Vector3
  3277. */
  3278. Vector3.prototype.set = function (x, y, z) {
  3279. return this.copyFromFloats(x, y, z);
  3280. };
  3281. // Statics
  3282. /**
  3283. * Get the clip factor between two vectors
  3284. * @param vector0 defines the first operand
  3285. * @param vector1 defines the second operand
  3286. * @param axis defines the axis to use
  3287. * @param size defines the size along the axis
  3288. * @returns the clip factor
  3289. */
  3290. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3291. var d0 = Vector3.Dot(vector0, axis) - size;
  3292. var d1 = Vector3.Dot(vector1, axis) - size;
  3293. var s = d0 / (d0 - d1);
  3294. return s;
  3295. };
  3296. /**
  3297. * Get angle between two vectors
  3298. * @param vector0 angle between vector0 and vector1
  3299. * @param vector1 angle between vector0 and vector1
  3300. * @param normal direction of the normal
  3301. * @return the angle between vector0 and vector1
  3302. */
  3303. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3304. var v0 = vector0.clone().normalize();
  3305. var v1 = vector1.clone().normalize();
  3306. var dot = Vector3.Dot(v0, v1);
  3307. var n = Vector3.Cross(v0, v1);
  3308. if (Vector3.Dot(n, normal) > 0) {
  3309. return Math.acos(dot);
  3310. }
  3311. return -Math.acos(dot);
  3312. };
  3313. /**
  3314. * Returns a new Vector3 set from the index "offset" of the given array
  3315. * @param array defines the source array
  3316. * @param offset defines the offset in the source array
  3317. * @returns the new Vector3
  3318. */
  3319. Vector3.FromArray = function (array, offset) {
  3320. if (!offset) {
  3321. offset = 0;
  3322. }
  3323. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3327. * This function is deprecated. Use FromArray instead
  3328. * @param array defines the source array
  3329. * @param offset defines the offset in the source array
  3330. * @returns the new Vector3
  3331. */
  3332. Vector3.FromFloatArray = function (array, offset) {
  3333. return Vector3.FromArray(array, offset);
  3334. };
  3335. /**
  3336. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3337. * @param array defines the source array
  3338. * @param offset defines the offset in the source array
  3339. * @param result defines the Vector3 where to store the result
  3340. */
  3341. Vector3.FromArrayToRef = function (array, offset, result) {
  3342. result.x = array[offset];
  3343. result.y = array[offset + 1];
  3344. result.z = array[offset + 2];
  3345. };
  3346. /**
  3347. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3348. * This function is deprecated. Use FromArrayToRef instead.
  3349. * @param array defines the source array
  3350. * @param offset defines the offset in the source array
  3351. * @param result defines the Vector3 where to store the result
  3352. */
  3353. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3354. return Vector3.FromArrayToRef(array, offset, result);
  3355. };
  3356. /**
  3357. * Sets the given vector "result" with the given floats.
  3358. * @param x defines the x coordinate of the source
  3359. * @param y defines the y coordinate of the source
  3360. * @param z defines the z coordinate of the source
  3361. * @param result defines the Vector3 where to store the result
  3362. */
  3363. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3364. result.x = x;
  3365. result.y = y;
  3366. result.z = z;
  3367. };
  3368. /**
  3369. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3370. * @returns a new empty Vector3
  3371. */
  3372. Vector3.Zero = function () {
  3373. return new Vector3(0.0, 0.0, 0.0);
  3374. };
  3375. /**
  3376. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3377. * @returns a new unit Vector3
  3378. */
  3379. Vector3.One = function () {
  3380. return new Vector3(1.0, 1.0, 1.0);
  3381. };
  3382. /**
  3383. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3384. * @returns a new up Vector3
  3385. */
  3386. Vector3.Up = function () {
  3387. return new Vector3(0.0, 1.0, 0.0);
  3388. };
  3389. /**
  3390. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3391. * @returns a new down Vector3
  3392. */
  3393. Vector3.Down = function () {
  3394. return new Vector3(0.0, -1.0, 0.0);
  3395. };
  3396. /**
  3397. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3398. * @returns a new forward Vector3
  3399. */
  3400. Vector3.Forward = function () {
  3401. return new Vector3(0.0, 0.0, 1.0);
  3402. };
  3403. /**
  3404. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3405. * @returns a new right Vector3
  3406. */
  3407. Vector3.Right = function () {
  3408. return new Vector3(1.0, 0.0, 0.0);
  3409. };
  3410. /**
  3411. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3412. * @returns a new left Vector3
  3413. */
  3414. Vector3.Left = function () {
  3415. return new Vector3(-1.0, 0.0, 0.0);
  3416. };
  3417. /**
  3418. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3419. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3420. * @param vector defines the Vector3 to transform
  3421. * @param transformation defines the transformation matrix
  3422. * @returns the transformed Vector3
  3423. */
  3424. Vector3.TransformCoordinates = function (vector, transformation) {
  3425. var result = Vector3.Zero();
  3426. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3427. return result;
  3428. };
  3429. /**
  3430. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3431. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3432. * @param vector defines the Vector3 to transform
  3433. * @param transformation defines the transformation matrix
  3434. * @param result defines the Vector3 where to store the result
  3435. */
  3436. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3437. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3438. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3439. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3440. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3441. result.x = x / w;
  3442. result.y = y / w;
  3443. result.z = z / w;
  3444. };
  3445. /**
  3446. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3447. * This method computes tranformed coordinates only, not transformed direction vectors
  3448. * @param x define the x coordinate of the source vector
  3449. * @param y define the y coordinate of the source vector
  3450. * @param z define the z coordinate of the source vector
  3451. * @param transformation defines the transformation matrix
  3452. * @param result defines the Vector3 where to store the result
  3453. */
  3454. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3455. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3456. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3457. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3458. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3459. result.x = rx / rw;
  3460. result.y = ry / rw;
  3461. result.z = rz / rw;
  3462. };
  3463. /**
  3464. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3465. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3466. * @param vector defines the Vector3 to transform
  3467. * @param transformation defines the transformation matrix
  3468. * @returns the new Vector3
  3469. */
  3470. Vector3.TransformNormal = function (vector, transformation) {
  3471. var result = Vector3.Zero();
  3472. Vector3.TransformNormalToRef(vector, transformation, result);
  3473. return result;
  3474. };
  3475. /**
  3476. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3477. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3478. * @param vector defines the Vector3 to transform
  3479. * @param transformation defines the transformation matrix
  3480. * @param result defines the Vector3 where to store the result
  3481. */
  3482. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3483. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3484. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3485. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3486. result.x = x;
  3487. result.y = y;
  3488. result.z = z;
  3489. };
  3490. /**
  3491. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3492. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3493. * @param x define the x coordinate of the source vector
  3494. * @param y define the y coordinate of the source vector
  3495. * @param z define the z coordinate of the source vector
  3496. * @param transformation defines the transformation matrix
  3497. * @param result defines the Vector3 where to store the result
  3498. */
  3499. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3500. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3501. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3502. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3503. };
  3504. /**
  3505. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3506. * @param value1 defines the first control point
  3507. * @param value2 defines the second control point
  3508. * @param value3 defines the third control point
  3509. * @param value4 defines the fourth control point
  3510. * @param amount defines the amount on the spline to use
  3511. * @returns the new Vector3
  3512. */
  3513. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3514. var squared = amount * amount;
  3515. var cubed = amount * squared;
  3516. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3517. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3518. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3519. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3520. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3521. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3522. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3523. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3524. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3525. return new Vector3(x, y, z);
  3526. };
  3527. /**
  3528. * 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"
  3529. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3530. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3531. * @param value defines the current value
  3532. * @param min defines the lower range value
  3533. * @param max defines the upper range value
  3534. * @returns the new Vector3
  3535. */
  3536. Vector3.Clamp = function (value, min, max) {
  3537. var x = value.x;
  3538. x = (x > max.x) ? max.x : x;
  3539. x = (x < min.x) ? min.x : x;
  3540. var y = value.y;
  3541. y = (y > max.y) ? max.y : y;
  3542. y = (y < min.y) ? min.y : y;
  3543. var z = value.z;
  3544. z = (z > max.z) ? max.z : z;
  3545. z = (z < min.z) ? min.z : z;
  3546. return new Vector3(x, y, z);
  3547. };
  3548. /**
  3549. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3550. * @param value1 defines the first control point
  3551. * @param tangent1 defines the first tangent vector
  3552. * @param value2 defines the second control point
  3553. * @param tangent2 defines the second tangent vector
  3554. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3555. * @returns the new Vector3
  3556. */
  3557. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3558. var squared = amount * amount;
  3559. var cubed = amount * squared;
  3560. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3561. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3562. var part3 = (cubed - (2.0 * squared)) + amount;
  3563. var part4 = cubed - squared;
  3564. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3565. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3566. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3567. return new Vector3(x, y, z);
  3568. };
  3569. /**
  3570. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3571. * @param start defines the start value
  3572. * @param end defines the end value
  3573. * @param amount max defines amount between both (between 0 and 1)
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Lerp = function (start, end, amount) {
  3577. var result = new Vector3(0, 0, 0);
  3578. Vector3.LerpToRef(start, end, amount, result);
  3579. return result;
  3580. };
  3581. /**
  3582. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3583. * @param start defines the start value
  3584. * @param end defines the end value
  3585. * @param amount max defines amount between both (between 0 and 1)
  3586. * @param result defines the Vector3 where to store the result
  3587. */
  3588. Vector3.LerpToRef = function (start, end, amount, result) {
  3589. result.x = start.x + ((end.x - start.x) * amount);
  3590. result.y = start.y + ((end.y - start.y) * amount);
  3591. result.z = start.z + ((end.z - start.z) * amount);
  3592. };
  3593. /**
  3594. * Returns the dot product (float) between the vectors "left" and "right"
  3595. * @param left defines the left operand
  3596. * @param right defines the right operand
  3597. * @returns the dot product
  3598. */
  3599. Vector3.Dot = function (left, right) {
  3600. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3601. };
  3602. /**
  3603. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3604. * The cross product is then orthogonal to both "left" and "right"
  3605. * @param left defines the left operand
  3606. * @param right defines the right operand
  3607. * @returns the cross product
  3608. */
  3609. Vector3.Cross = function (left, right) {
  3610. var result = Vector3.Zero();
  3611. Vector3.CrossToRef(left, right, result);
  3612. return result;
  3613. };
  3614. /**
  3615. * Sets the given vector "result" with the cross product of "left" and "right"
  3616. * The cross product is then orthogonal to both "left" and "right"
  3617. * @param left defines the left operand
  3618. * @param right defines the right operand
  3619. * @param result defines the Vector3 where to store the result
  3620. */
  3621. Vector3.CrossToRef = function (left, right, result) {
  3622. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3623. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3624. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3625. result.copyFrom(MathTmp.Vector3[0]);
  3626. };
  3627. /**
  3628. * Returns a new Vector3 as the normalization of the given vector
  3629. * @param vector defines the Vector3 to normalize
  3630. * @returns the new Vector3
  3631. */
  3632. Vector3.Normalize = function (vector) {
  3633. var result = Vector3.Zero();
  3634. Vector3.NormalizeToRef(vector, result);
  3635. return result;
  3636. };
  3637. /**
  3638. * Sets the given vector "result" with the normalization of the given first vector
  3639. * @param vector defines the Vector3 to normalize
  3640. * @param result defines the Vector3 where to store the result
  3641. */
  3642. Vector3.NormalizeToRef = function (vector, result) {
  3643. result.copyFrom(vector);
  3644. result.normalize();
  3645. };
  3646. /**
  3647. * Project a Vector3 onto screen space
  3648. * @param vector defines the Vector3 to project
  3649. * @param world defines the world matrix to use
  3650. * @param transform defines the transform (view x projection) matrix to use
  3651. * @param viewport defines the screen viewport to use
  3652. * @returns the new Vector3
  3653. */
  3654. Vector3.Project = function (vector, world, transform, viewport) {
  3655. var cw = viewport.width;
  3656. var ch = viewport.height;
  3657. var cx = viewport.x;
  3658. var cy = viewport.y;
  3659. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3660. 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);
  3661. var matrix = MathTmp.Matrix[0];
  3662. world.multiplyToRef(transform, matrix);
  3663. matrix.multiplyToRef(viewportMatrix, matrix);
  3664. return Vector3.TransformCoordinates(vector, matrix);
  3665. };
  3666. /**
  3667. * Unproject from screen space to object space
  3668. * @param source defines the screen space Vector3 to use
  3669. * @param viewportWidth defines the current width of the viewport
  3670. * @param viewportHeight defines the current height of the viewport
  3671. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3672. * @param transform defines the transform (view x projection) matrix to use
  3673. * @returns the new Vector3
  3674. */
  3675. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3676. var matrix = MathTmp.Matrix[0];
  3677. world.multiplyToRef(transform, matrix);
  3678. matrix.invert();
  3679. source.x = source.x / viewportWidth * 2 - 1;
  3680. source.y = -(source.y / viewportHeight * 2 - 1);
  3681. var vector = Vector3.TransformCoordinates(source, matrix);
  3682. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3683. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3684. vector = vector.scale(1.0 / num);
  3685. }
  3686. return vector;
  3687. };
  3688. /**
  3689. * Unproject from screen space to object space
  3690. * @param source defines the screen space Vector3 to use
  3691. * @param viewportWidth defines the current width of the viewport
  3692. * @param viewportHeight defines the current height of the viewport
  3693. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3694. * @param view defines the view matrix to use
  3695. * @param projection defines the projection matrix to use
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3699. var result = Vector3.Zero();
  3700. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3701. return result;
  3702. };
  3703. /**
  3704. * Unproject from screen space to object space
  3705. * @param source defines the screen space Vector3 to use
  3706. * @param viewportWidth defines the current width of the viewport
  3707. * @param viewportHeight defines the current height of the viewport
  3708. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3709. * @param view defines the view matrix to use
  3710. * @param projection defines the projection matrix to use
  3711. * @param result defines the Vector3 where to store the result
  3712. */
  3713. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3714. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3715. };
  3716. /**
  3717. * Unproject from screen space to object space
  3718. * @param sourceX defines the screen space x coordinate to use
  3719. * @param sourceY defines the screen space y coordinate to use
  3720. * @param sourceZ defines the screen space z coordinate to use
  3721. * @param viewportWidth defines the current width of the viewport
  3722. * @param viewportHeight defines the current height of the viewport
  3723. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3724. * @param view defines the view matrix to use
  3725. * @param projection defines the projection matrix to use
  3726. * @param result defines the Vector3 where to store the result
  3727. */
  3728. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3729. var matrix = MathTmp.Matrix[0];
  3730. world.multiplyToRef(view, matrix);
  3731. matrix.multiplyToRef(projection, matrix);
  3732. matrix.invert();
  3733. var screenSource = MathTmp.Vector3[0];
  3734. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3735. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3736. screenSource.z = 2 * sourceZ - 1.0;
  3737. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3738. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3739. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3740. result.scaleInPlace(1.0 / num);
  3741. }
  3742. };
  3743. /**
  3744. * Gets the minimal coordinate values between two Vector3
  3745. * @param left defines the first operand
  3746. * @param right defines the second operand
  3747. * @returns the new Vector3
  3748. */
  3749. Vector3.Minimize = function (left, right) {
  3750. var min = left.clone();
  3751. min.minimizeInPlace(right);
  3752. return min;
  3753. };
  3754. /**
  3755. * Gets the maximal coordinate values between two Vector3
  3756. * @param left defines the first operand
  3757. * @param right defines the second operand
  3758. * @returns the new Vector3
  3759. */
  3760. Vector3.Maximize = function (left, right) {
  3761. var max = left.clone();
  3762. max.maximizeInPlace(right);
  3763. return max;
  3764. };
  3765. /**
  3766. * Returns the distance between the vectors "value1" and "value2"
  3767. * @param value1 defines the first operand
  3768. * @param value2 defines the second operand
  3769. * @returns the distance
  3770. */
  3771. Vector3.Distance = function (value1, value2) {
  3772. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3773. };
  3774. /**
  3775. * Returns the squared distance between the vectors "value1" and "value2"
  3776. * @param value1 defines the first operand
  3777. * @param value2 defines the second operand
  3778. * @returns the squared distance
  3779. */
  3780. Vector3.DistanceSquared = function (value1, value2) {
  3781. var x = value1.x - value2.x;
  3782. var y = value1.y - value2.y;
  3783. var z = value1.z - value2.z;
  3784. return (x * x) + (y * y) + (z * z);
  3785. };
  3786. /**
  3787. * Returns a new Vector3 located at the center between "value1" and "value2"
  3788. * @param value1 defines the first operand
  3789. * @param value2 defines the second operand
  3790. * @returns the new Vector3
  3791. */
  3792. Vector3.Center = function (value1, value2) {
  3793. var center = value1.add(value2);
  3794. center.scaleInPlace(0.5);
  3795. return center;
  3796. };
  3797. /**
  3798. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3799. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3800. * to something in order to rotate it from its local system to the given target system
  3801. * Note: axis1, axis2 and axis3 are normalized during this operation
  3802. * @param axis1 defines the first axis
  3803. * @param axis2 defines the second axis
  3804. * @param axis3 defines the third axis
  3805. * @returns a new Vector3
  3806. */
  3807. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3808. var rotation = Vector3.Zero();
  3809. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3810. return rotation;
  3811. };
  3812. /**
  3813. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3814. * @param axis1 defines the first axis
  3815. * @param axis2 defines the second axis
  3816. * @param axis3 defines the third axis
  3817. * @param ref defines the Vector3 where to store the result
  3818. */
  3819. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3820. var quat = MathTmp.Quaternion[0];
  3821. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3822. quat.toEulerAnglesToRef(ref);
  3823. };
  3824. return Vector3;
  3825. }());
  3826. BABYLON.Vector3 = Vector3;
  3827. //Vector4 class created for EulerAngle class conversion to Quaternion
  3828. var Vector4 = /** @class */ (function () {
  3829. /**
  3830. * Creates a Vector4 object from the given floats.
  3831. */
  3832. function Vector4(x, y, z, w) {
  3833. this.x = x;
  3834. this.y = y;
  3835. this.z = z;
  3836. this.w = w;
  3837. }
  3838. /**
  3839. * Returns the string with the Vector4 coordinates.
  3840. */
  3841. Vector4.prototype.toString = function () {
  3842. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3843. };
  3844. /**
  3845. * Returns the string "Vector4".
  3846. */
  3847. Vector4.prototype.getClassName = function () {
  3848. return "Vector4";
  3849. };
  3850. /**
  3851. * Returns the Vector4 hash code.
  3852. */
  3853. Vector4.prototype.getHashCode = function () {
  3854. var hash = this.x || 0;
  3855. hash = (hash * 397) ^ (this.y || 0);
  3856. hash = (hash * 397) ^ (this.z || 0);
  3857. hash = (hash * 397) ^ (this.w || 0);
  3858. return hash;
  3859. };
  3860. // Operators
  3861. /**
  3862. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.asArray = function () {
  3865. var result = new Array();
  3866. this.toArray(result, 0);
  3867. return result;
  3868. };
  3869. /**
  3870. * Populates the given array from the given index with the Vector4 coordinates.
  3871. * Returns the Vector4.
  3872. */
  3873. Vector4.prototype.toArray = function (array, index) {
  3874. if (index === undefined) {
  3875. index = 0;
  3876. }
  3877. array[index] = this.x;
  3878. array[index + 1] = this.y;
  3879. array[index + 2] = this.z;
  3880. array[index + 3] = this.w;
  3881. return this;
  3882. };
  3883. /**
  3884. * Adds the given vector to the current Vector4.
  3885. * Returns the updated Vector4.
  3886. */
  3887. Vector4.prototype.addInPlace = function (otherVector) {
  3888. this.x += otherVector.x;
  3889. this.y += otherVector.y;
  3890. this.z += otherVector.z;
  3891. this.w += otherVector.w;
  3892. return this;
  3893. };
  3894. /**
  3895. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3896. */
  3897. Vector4.prototype.add = function (otherVector) {
  3898. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3899. };
  3900. /**
  3901. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3902. * Returns the current Vector4.
  3903. */
  3904. Vector4.prototype.addToRef = function (otherVector, result) {
  3905. result.x = this.x + otherVector.x;
  3906. result.y = this.y + otherVector.y;
  3907. result.z = this.z + otherVector.z;
  3908. result.w = this.w + otherVector.w;
  3909. return this;
  3910. };
  3911. /**
  3912. * Subtract in place the given vector from the current Vector4.
  3913. * Returns the updated Vector4.
  3914. */
  3915. Vector4.prototype.subtractInPlace = function (otherVector) {
  3916. this.x -= otherVector.x;
  3917. this.y -= otherVector.y;
  3918. this.z -= otherVector.z;
  3919. this.w -= otherVector.w;
  3920. return this;
  3921. };
  3922. /**
  3923. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3924. */
  3925. Vector4.prototype.subtract = function (otherVector) {
  3926. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3927. };
  3928. /**
  3929. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3930. * Returns the current Vector4.
  3931. */
  3932. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3933. result.x = this.x - otherVector.x;
  3934. result.y = this.y - otherVector.y;
  3935. result.z = this.z - otherVector.z;
  3936. result.w = this.w - otherVector.w;
  3937. return this;
  3938. };
  3939. /**
  3940. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3941. */
  3942. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3943. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3944. };
  3945. /**
  3946. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3947. * Returns the current Vector4.
  3948. */
  3949. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3950. result.x = this.x - x;
  3951. result.y = this.y - y;
  3952. result.z = this.z - z;
  3953. result.w = this.w - w;
  3954. return this;
  3955. };
  3956. /**
  3957. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3958. */
  3959. Vector4.prototype.negate = function () {
  3960. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3961. };
  3962. /**
  3963. * Multiplies the current Vector4 coordinates by scale (float).
  3964. * Returns the updated Vector4.
  3965. */
  3966. Vector4.prototype.scaleInPlace = function (scale) {
  3967. this.x *= scale;
  3968. this.y *= scale;
  3969. this.z *= scale;
  3970. this.w *= scale;
  3971. return this;
  3972. };
  3973. /**
  3974. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3975. */
  3976. Vector4.prototype.scale = function (scale) {
  3977. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3978. };
  3979. /**
  3980. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3981. * Returns the current Vector4.
  3982. */
  3983. Vector4.prototype.scaleToRef = function (scale, result) {
  3984. result.x = this.x * scale;
  3985. result.y = this.y * scale;
  3986. result.z = this.z * scale;
  3987. result.w = this.w * scale;
  3988. return this;
  3989. };
  3990. /**
  3991. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3992. * @param scale defines the scale factor
  3993. * @param result defines the Vector4 object where to store the result
  3994. * @returns the unmodified current Vector4
  3995. */
  3996. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3997. result.x += this.x * scale;
  3998. result.y += this.y * scale;
  3999. result.z += this.z * scale;
  4000. result.w += this.w * scale;
  4001. return this;
  4002. };
  4003. /**
  4004. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4005. */
  4006. Vector4.prototype.equals = function (otherVector) {
  4007. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4008. };
  4009. /**
  4010. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4011. */
  4012. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4013. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4014. return otherVector
  4015. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4016. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4017. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4018. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4019. };
  4020. /**
  4021. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4022. */
  4023. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4024. return this.x === x && this.y === y && this.z === z && this.w === w;
  4025. };
  4026. /**
  4027. * Multiplies in place the current Vector4 by the given one.
  4028. * Returns the updated Vector4.
  4029. */
  4030. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4031. this.x *= otherVector.x;
  4032. this.y *= otherVector.y;
  4033. this.z *= otherVector.z;
  4034. this.w *= otherVector.w;
  4035. return this;
  4036. };
  4037. /**
  4038. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4039. */
  4040. Vector4.prototype.multiply = function (otherVector) {
  4041. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4042. };
  4043. /**
  4044. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4045. * Returns the current Vector4.
  4046. */
  4047. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4048. result.x = this.x * otherVector.x;
  4049. result.y = this.y * otherVector.y;
  4050. result.z = this.z * otherVector.z;
  4051. result.w = this.w * otherVector.w;
  4052. return this;
  4053. };
  4054. /**
  4055. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4056. */
  4057. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4058. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4059. };
  4060. /**
  4061. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4062. */
  4063. Vector4.prototype.divide = function (otherVector) {
  4064. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4065. };
  4066. /**
  4067. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4068. * Returns the current Vector4.
  4069. */
  4070. Vector4.prototype.divideToRef = function (otherVector, result) {
  4071. result.x = this.x / otherVector.x;
  4072. result.y = this.y / otherVector.y;
  4073. result.z = this.z / otherVector.z;
  4074. result.w = this.w / otherVector.w;
  4075. return this;
  4076. };
  4077. /**
  4078. * Divides the current Vector3 coordinates by the given ones.
  4079. * @returns the updated Vector3.
  4080. */
  4081. Vector4.prototype.divideInPlace = function (otherVector) {
  4082. return this.divideToRef(otherVector, this);
  4083. };
  4084. /**
  4085. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4086. * @param other defines the second operand
  4087. * @returns the current updated Vector4
  4088. */
  4089. Vector4.prototype.minimizeInPlace = function (other) {
  4090. if (other.x < this.x)
  4091. this.x = other.x;
  4092. if (other.y < this.y)
  4093. this.y = other.y;
  4094. if (other.z < this.z)
  4095. this.z = other.z;
  4096. if (other.w < this.w)
  4097. this.w = other.w;
  4098. return this;
  4099. };
  4100. /**
  4101. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4102. * @param other defines the second operand
  4103. * @returns the current updated Vector4
  4104. */
  4105. Vector4.prototype.maximizeInPlace = function (other) {
  4106. if (other.x > this.x)
  4107. this.x = other.x;
  4108. if (other.y > this.y)
  4109. this.y = other.y;
  4110. if (other.z > this.z)
  4111. this.z = other.z;
  4112. if (other.w > this.w)
  4113. this.w = other.w;
  4114. return this;
  4115. };
  4116. /**
  4117. * Gets a new Vector4 from current Vector4 floored values
  4118. * @returns a new Vector4
  4119. */
  4120. Vector4.prototype.floor = function () {
  4121. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4122. };
  4123. /**
  4124. * Gets a new Vector4 from current Vector3 floored values
  4125. * @returns a new Vector4
  4126. */
  4127. Vector4.prototype.fract = function () {
  4128. 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));
  4129. };
  4130. // Properties
  4131. /**
  4132. * Returns the Vector4 length (float).
  4133. */
  4134. Vector4.prototype.length = function () {
  4135. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4136. };
  4137. /**
  4138. * Returns the Vector4 squared length (float).
  4139. */
  4140. Vector4.prototype.lengthSquared = function () {
  4141. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4142. };
  4143. // Methods
  4144. /**
  4145. * Normalizes in place the Vector4.
  4146. * Returns the updated Vector4.
  4147. */
  4148. Vector4.prototype.normalize = function () {
  4149. var len = this.length();
  4150. if (len === 0)
  4151. return this;
  4152. var num = 1.0 / len;
  4153. this.x *= num;
  4154. this.y *= num;
  4155. this.z *= num;
  4156. this.w *= num;
  4157. return this;
  4158. };
  4159. /**
  4160. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4161. */
  4162. Vector4.prototype.toVector3 = function () {
  4163. return new Vector3(this.x, this.y, this.z);
  4164. };
  4165. /**
  4166. * Returns a new Vector4 copied from the current one.
  4167. */
  4168. Vector4.prototype.clone = function () {
  4169. return new Vector4(this.x, this.y, this.z, this.w);
  4170. };
  4171. /**
  4172. * Updates the current Vector4 with the given one coordinates.
  4173. * Returns the updated Vector4.
  4174. */
  4175. Vector4.prototype.copyFrom = function (source) {
  4176. this.x = source.x;
  4177. this.y = source.y;
  4178. this.z = source.z;
  4179. this.w = source.w;
  4180. return this;
  4181. };
  4182. /**
  4183. * Updates the current Vector4 coordinates with the given floats.
  4184. * Returns the updated Vector4.
  4185. */
  4186. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4187. this.x = x;
  4188. this.y = y;
  4189. this.z = z;
  4190. this.w = w;
  4191. return this;
  4192. };
  4193. /**
  4194. * Updates the current Vector4 coordinates with the given floats.
  4195. * Returns the updated Vector4.
  4196. */
  4197. Vector4.prototype.set = function (x, y, z, w) {
  4198. return this.copyFromFloats(x, y, z, w);
  4199. };
  4200. // Statics
  4201. /**
  4202. * Returns a new Vector4 set from the starting index of the given array.
  4203. */
  4204. Vector4.FromArray = function (array, offset) {
  4205. if (!offset) {
  4206. offset = 0;
  4207. }
  4208. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4209. };
  4210. /**
  4211. * Updates the given vector "result" from the starting index of the given array.
  4212. */
  4213. Vector4.FromArrayToRef = function (array, offset, result) {
  4214. result.x = array[offset];
  4215. result.y = array[offset + 1];
  4216. result.z = array[offset + 2];
  4217. result.w = array[offset + 3];
  4218. };
  4219. /**
  4220. * Updates the given vector "result" from the starting index of the given Float32Array.
  4221. */
  4222. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4223. Vector4.FromArrayToRef(array, offset, result);
  4224. };
  4225. /**
  4226. * Updates the given vector "result" coordinates from the given floats.
  4227. */
  4228. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4229. result.x = x;
  4230. result.y = y;
  4231. result.z = z;
  4232. result.w = w;
  4233. };
  4234. /**
  4235. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4236. */
  4237. Vector4.Zero = function () {
  4238. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4239. };
  4240. /**
  4241. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4242. */
  4243. Vector4.One = function () {
  4244. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4245. };
  4246. /**
  4247. * Returns a new normalized Vector4 from the given one.
  4248. */
  4249. Vector4.Normalize = function (vector) {
  4250. var result = Vector4.Zero();
  4251. Vector4.NormalizeToRef(vector, result);
  4252. return result;
  4253. };
  4254. /**
  4255. * Updates the given vector "result" from the normalization of the given one.
  4256. */
  4257. Vector4.NormalizeToRef = function (vector, result) {
  4258. result.copyFrom(vector);
  4259. result.normalize();
  4260. };
  4261. Vector4.Minimize = function (left, right) {
  4262. var min = left.clone();
  4263. min.minimizeInPlace(right);
  4264. return min;
  4265. };
  4266. Vector4.Maximize = function (left, right) {
  4267. var max = left.clone();
  4268. max.maximizeInPlace(right);
  4269. return max;
  4270. };
  4271. /**
  4272. * Returns the distance (float) between the vectors "value1" and "value2".
  4273. */
  4274. Vector4.Distance = function (value1, value2) {
  4275. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4276. };
  4277. /**
  4278. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4279. */
  4280. Vector4.DistanceSquared = function (value1, value2) {
  4281. var x = value1.x - value2.x;
  4282. var y = value1.y - value2.y;
  4283. var z = value1.z - value2.z;
  4284. var w = value1.w - value2.w;
  4285. return (x * x) + (y * y) + (z * z) + (w * w);
  4286. };
  4287. /**
  4288. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4289. */
  4290. Vector4.Center = function (value1, value2) {
  4291. var center = value1.add(value2);
  4292. center.scaleInPlace(0.5);
  4293. return center;
  4294. };
  4295. /**
  4296. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4297. * This methods computes transformed normalized direction vectors only.
  4298. */
  4299. Vector4.TransformNormal = function (vector, transformation) {
  4300. var result = Vector4.Zero();
  4301. Vector4.TransformNormalToRef(vector, transformation, result);
  4302. return result;
  4303. };
  4304. /**
  4305. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4306. * This methods computes transformed normalized direction vectors only.
  4307. */
  4308. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4309. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4310. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4311. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4312. result.x = x;
  4313. result.y = y;
  4314. result.z = z;
  4315. result.w = vector.w;
  4316. };
  4317. /**
  4318. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4319. * This methods computes transformed normalized direction vectors only.
  4320. */
  4321. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4322. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4323. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4324. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4325. result.w = w;
  4326. };
  4327. return Vector4;
  4328. }());
  4329. BABYLON.Vector4 = Vector4;
  4330. var Size = /** @class */ (function () {
  4331. /**
  4332. * Creates a Size object from the given width and height (floats).
  4333. */
  4334. function Size(width, height) {
  4335. this.width = width;
  4336. this.height = height;
  4337. }
  4338. // Returns a string with the Size width and height.
  4339. Size.prototype.toString = function () {
  4340. return "{W: " + this.width + ", H: " + this.height + "}";
  4341. };
  4342. /**
  4343. * Returns the string "Size"
  4344. */
  4345. Size.prototype.getClassName = function () {
  4346. return "Size";
  4347. };
  4348. /**
  4349. * Returns the Size hash code.
  4350. */
  4351. Size.prototype.getHashCode = function () {
  4352. var hash = this.width || 0;
  4353. hash = (hash * 397) ^ (this.height || 0);
  4354. return hash;
  4355. };
  4356. /**
  4357. * Updates the current size from the given one.
  4358. * Returns the updated Size.
  4359. */
  4360. Size.prototype.copyFrom = function (src) {
  4361. this.width = src.width;
  4362. this.height = src.height;
  4363. };
  4364. /**
  4365. * Updates in place the current Size from the given floats.
  4366. * Returns the updated Size.
  4367. */
  4368. Size.prototype.copyFromFloats = function (width, height) {
  4369. this.width = width;
  4370. this.height = height;
  4371. return this;
  4372. };
  4373. /**
  4374. * Updates in place the current Size from the given floats.
  4375. * Returns the updated Size.
  4376. */
  4377. Size.prototype.set = function (width, height) {
  4378. return this.copyFromFloats(width, height);
  4379. };
  4380. /**
  4381. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4382. */
  4383. Size.prototype.multiplyByFloats = function (w, h) {
  4384. return new Size(this.width * w, this.height * h);
  4385. };
  4386. /**
  4387. * Returns a new Size copied from the given one.
  4388. */
  4389. Size.prototype.clone = function () {
  4390. return new Size(this.width, this.height);
  4391. };
  4392. /**
  4393. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4394. */
  4395. Size.prototype.equals = function (other) {
  4396. if (!other) {
  4397. return false;
  4398. }
  4399. return (this.width === other.width) && (this.height === other.height);
  4400. };
  4401. Object.defineProperty(Size.prototype, "surface", {
  4402. /**
  4403. * Returns the surface of the Size : width * height (float).
  4404. */
  4405. get: function () {
  4406. return this.width * this.height;
  4407. },
  4408. enumerable: true,
  4409. configurable: true
  4410. });
  4411. /**
  4412. * Returns a new Size set to (0.0, 0.0)
  4413. */
  4414. Size.Zero = function () {
  4415. return new Size(0.0, 0.0);
  4416. };
  4417. /**
  4418. * Returns a new Size set as the addition result of the current Size and the given one.
  4419. */
  4420. Size.prototype.add = function (otherSize) {
  4421. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4422. return r;
  4423. };
  4424. /**
  4425. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4426. */
  4427. Size.prototype.subtract = function (otherSize) {
  4428. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4429. return r;
  4430. };
  4431. /**
  4432. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4433. */
  4434. Size.Lerp = function (start, end, amount) {
  4435. var w = start.width + ((end.width - start.width) * amount);
  4436. var h = start.height + ((end.height - start.height) * amount);
  4437. return new Size(w, h);
  4438. };
  4439. return Size;
  4440. }());
  4441. BABYLON.Size = Size;
  4442. /**
  4443. * Class used to store quaternion data
  4444. * @see https://en.wikipedia.org/wiki/Quaternion
  4445. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4446. */
  4447. var Quaternion = /** @class */ (function () {
  4448. /**
  4449. * Creates a new Quaternion from the given floats
  4450. * @param x defines the first component (0 by default)
  4451. * @param y defines the second component (0 by default)
  4452. * @param z defines the third component (0 by default)
  4453. * @param w defines the fourth component (1.0 by default)
  4454. */
  4455. function Quaternion(
  4456. /** defines the first component (0 by default) */
  4457. x,
  4458. /** defines the second component (0 by default) */
  4459. y,
  4460. /** defines the third component (0 by default) */
  4461. z,
  4462. /** defines the fourth component (1.0 by default) */
  4463. w) {
  4464. if (x === void 0) { x = 0.0; }
  4465. if (y === void 0) { y = 0.0; }
  4466. if (z === void 0) { z = 0.0; }
  4467. if (w === void 0) { w = 1.0; }
  4468. this.x = x;
  4469. this.y = y;
  4470. this.z = z;
  4471. this.w = w;
  4472. }
  4473. /**
  4474. * Gets a string representation for the current quaternion
  4475. * @returns a string with the Quaternion coordinates
  4476. */
  4477. Quaternion.prototype.toString = function () {
  4478. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4479. };
  4480. /**
  4481. * Gets the class name of the quaternion
  4482. * @returns the string "Quaternion"
  4483. */
  4484. Quaternion.prototype.getClassName = function () {
  4485. return "Quaternion";
  4486. };
  4487. /**
  4488. * Gets a hash code for this quaternion
  4489. * @returns the quaternion hash code
  4490. */
  4491. Quaternion.prototype.getHashCode = function () {
  4492. var hash = this.x || 0;
  4493. hash = (hash * 397) ^ (this.y || 0);
  4494. hash = (hash * 397) ^ (this.z || 0);
  4495. hash = (hash * 397) ^ (this.w || 0);
  4496. return hash;
  4497. };
  4498. /**
  4499. * Copy the quaternion to an array
  4500. * @returns a new array populated with 4 elements from the quaternion coordinates
  4501. */
  4502. Quaternion.prototype.asArray = function () {
  4503. return [this.x, this.y, this.z, this.w];
  4504. };
  4505. /**
  4506. * Check if two quaternions are equals
  4507. * @param otherQuaternion defines the second operand
  4508. * @return true if the current quaternion and the given one coordinates are strictly equals
  4509. */
  4510. Quaternion.prototype.equals = function (otherQuaternion) {
  4511. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4512. };
  4513. /**
  4514. * Clone the current quaternion
  4515. * @returns a new quaternion copied from the current one
  4516. */
  4517. Quaternion.prototype.clone = function () {
  4518. return new Quaternion(this.x, this.y, this.z, this.w);
  4519. };
  4520. /**
  4521. * Copy a quaternion to the current one
  4522. * @param other defines the other quaternion
  4523. * @returns the updated current quaternion
  4524. */
  4525. Quaternion.prototype.copyFrom = function (other) {
  4526. this.x = other.x;
  4527. this.y = other.y;
  4528. this.z = other.z;
  4529. this.w = other.w;
  4530. return this;
  4531. };
  4532. /**
  4533. * Updates the current quaternion with the given float coordinates
  4534. * @param x defines the x coordinate
  4535. * @param y defines the y coordinate
  4536. * @param z defines the z coordinate
  4537. * @param w defines the w coordinate
  4538. * @returns the updated current quaternion
  4539. */
  4540. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4541. this.x = x;
  4542. this.y = y;
  4543. this.z = z;
  4544. this.w = w;
  4545. return this;
  4546. };
  4547. /**
  4548. * Updates the current quaternion from the given float coordinates
  4549. * @param x defines the x coordinate
  4550. * @param y defines the y coordinate
  4551. * @param z defines the z coordinate
  4552. * @param w defines the w coordinate
  4553. * @returns the updated current quaternion
  4554. */
  4555. Quaternion.prototype.set = function (x, y, z, w) {
  4556. return this.copyFromFloats(x, y, z, w);
  4557. };
  4558. /**
  4559. * Adds two quaternions
  4560. * @param other defines the second operand
  4561. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4562. */
  4563. Quaternion.prototype.add = function (other) {
  4564. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4565. };
  4566. /**
  4567. * Add a quaternion to the current one
  4568. * @param other defines the quaternion to add
  4569. * @returns the current quaternion
  4570. */
  4571. Quaternion.prototype.addInPlace = function (other) {
  4572. this.x += other.x;
  4573. this.y += other.y;
  4574. this.z += other.z;
  4575. this.w += other.w;
  4576. return this;
  4577. };
  4578. /**
  4579. * Subtract two quaternions
  4580. * @param other defines the second operand
  4581. * @returns a new quaternion as the subtraction result of the given one from the current one
  4582. */
  4583. Quaternion.prototype.subtract = function (other) {
  4584. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4585. };
  4586. /**
  4587. * Multiplies the current quaternion by a scale factor
  4588. * @param value defines the scale factor
  4589. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4590. */
  4591. Quaternion.prototype.scale = function (value) {
  4592. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4593. };
  4594. /**
  4595. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4596. * @param scale defines the scale factor
  4597. * @param result defines the Quaternion object where to store the result
  4598. * @returns the unmodified current quaternion
  4599. */
  4600. Quaternion.prototype.scaleToRef = function (scale, result) {
  4601. result.x = this.x * scale;
  4602. result.y = this.y * scale;
  4603. result.z = this.z * scale;
  4604. result.w = this.w * scale;
  4605. return this;
  4606. };
  4607. /**
  4608. * Multiplies in place the current quaternion by a scale factor
  4609. * @param value defines the scale factor
  4610. * @returns the current modified quaternion
  4611. */
  4612. Quaternion.prototype.scaleInPlace = function (value) {
  4613. this.x *= value;
  4614. this.y *= value;
  4615. this.z *= value;
  4616. this.w *= value;
  4617. return this;
  4618. };
  4619. /**
  4620. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4621. * @param scale defines the scale factor
  4622. * @param result defines the Quaternion object where to store the result
  4623. * @returns the unmodified current quaternion
  4624. */
  4625. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4626. result.x += this.x * scale;
  4627. result.y += this.y * scale;
  4628. result.z += this.z * scale;
  4629. result.w += this.w * scale;
  4630. return this;
  4631. };
  4632. /**
  4633. * Multiplies two quaternions
  4634. * @param q1 defines the second operand
  4635. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4636. */
  4637. Quaternion.prototype.multiply = function (q1) {
  4638. var result = new Quaternion(0, 0, 0, 1.0);
  4639. this.multiplyToRef(q1, result);
  4640. return result;
  4641. };
  4642. /**
  4643. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4644. * @param q1 defines the second operand
  4645. * @param result defines the target quaternion
  4646. * @returns the current quaternion
  4647. */
  4648. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4649. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4650. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4651. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4652. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4653. result.copyFromFloats(x, y, z, w);
  4654. return this;
  4655. };
  4656. /**
  4657. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4658. * @param q1 defines the second operand
  4659. * @returns the currentupdated quaternion
  4660. */
  4661. Quaternion.prototype.multiplyInPlace = function (q1) {
  4662. this.multiplyToRef(q1, this);
  4663. return this;
  4664. };
  4665. /**
  4666. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4667. * @param ref defines the target quaternion
  4668. * @returns the current quaternion
  4669. */
  4670. Quaternion.prototype.conjugateToRef = function (ref) {
  4671. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4672. return this;
  4673. };
  4674. /**
  4675. * Conjugates in place (1-q) the current quaternion
  4676. * @returns the current updated quaternion
  4677. */
  4678. Quaternion.prototype.conjugateInPlace = function () {
  4679. this.x *= -1;
  4680. this.y *= -1;
  4681. this.z *= -1;
  4682. return this;
  4683. };
  4684. /**
  4685. * Conjugates in place (1-q) the current quaternion
  4686. * @returns a new quaternion
  4687. */
  4688. Quaternion.prototype.conjugate = function () {
  4689. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4690. return result;
  4691. };
  4692. /**
  4693. * Gets length of current quaternion
  4694. * @returns the quaternion length (float)
  4695. */
  4696. Quaternion.prototype.length = function () {
  4697. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4698. };
  4699. /**
  4700. * Normalize in place the current quaternion
  4701. * @returns the current updated quaternion
  4702. */
  4703. Quaternion.prototype.normalize = function () {
  4704. var length = 1.0 / this.length();
  4705. this.x *= length;
  4706. this.y *= length;
  4707. this.z *= length;
  4708. this.w *= length;
  4709. return this;
  4710. };
  4711. /**
  4712. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4713. * @param order is a reserved parameter and is ignore for now
  4714. * @returns a new Vector3 containing the Euler angles
  4715. */
  4716. Quaternion.prototype.toEulerAngles = function (order) {
  4717. if (order === void 0) { order = "YZX"; }
  4718. var result = Vector3.Zero();
  4719. this.toEulerAnglesToRef(result, order);
  4720. return result;
  4721. };
  4722. /**
  4723. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4724. * @param result defines the vector which will be filled with the Euler angles
  4725. * @param order is a reserved parameter and is ignore for now
  4726. * @returns the current unchanged quaternion
  4727. */
  4728. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4729. if (order === void 0) { order = "YZX"; }
  4730. var qz = this.z;
  4731. var qx = this.x;
  4732. var qy = this.y;
  4733. var qw = this.w;
  4734. var sqw = qw * qw;
  4735. var sqz = qz * qz;
  4736. var sqx = qx * qx;
  4737. var sqy = qy * qy;
  4738. var zAxisY = qy * qz - qx * qw;
  4739. var limit = .4999999;
  4740. if (zAxisY < -limit) {
  4741. result.y = 2 * Math.atan2(qy, qw);
  4742. result.x = Math.PI / 2;
  4743. result.z = 0;
  4744. }
  4745. else if (zAxisY > limit) {
  4746. result.y = 2 * Math.atan2(qy, qw);
  4747. result.x = -Math.PI / 2;
  4748. result.z = 0;
  4749. }
  4750. else {
  4751. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4752. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4753. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4754. }
  4755. return this;
  4756. };
  4757. /**
  4758. * Updates the given rotation matrix with the current quaternion values
  4759. * @param result defines the target matrix
  4760. * @returns the current unchanged quaternion
  4761. */
  4762. Quaternion.prototype.toRotationMatrix = function (result) {
  4763. var xx = this.x * this.x;
  4764. var yy = this.y * this.y;
  4765. var zz = this.z * this.z;
  4766. var xy = this.x * this.y;
  4767. var zw = this.z * this.w;
  4768. var zx = this.z * this.x;
  4769. var yw = this.y * this.w;
  4770. var yz = this.y * this.z;
  4771. var xw = this.x * this.w;
  4772. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4773. result.m[1] = 2.0 * (xy + zw);
  4774. result.m[2] = 2.0 * (zx - yw);
  4775. result.m[3] = 0;
  4776. result.m[4] = 2.0 * (xy - zw);
  4777. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4778. result.m[6] = 2.0 * (yz + xw);
  4779. result.m[7] = 0;
  4780. result.m[8] = 2.0 * (zx + yw);
  4781. result.m[9] = 2.0 * (yz - xw);
  4782. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4783. result.m[11] = 0;
  4784. result.m[12] = 0;
  4785. result.m[13] = 0;
  4786. result.m[14] = 0;
  4787. result.m[15] = 1.0;
  4788. result._markAsUpdated();
  4789. return this;
  4790. };
  4791. /**
  4792. * Updates the current quaternion from the given rotation matrix values
  4793. * @param matrix defines the source matrix
  4794. * @returns the current updated quaternion
  4795. */
  4796. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4797. Quaternion.FromRotationMatrixToRef(matrix, this);
  4798. return this;
  4799. };
  4800. // Statics
  4801. /**
  4802. * Creates a new quaternion from a rotation matrix
  4803. * @param matrix defines the source matrix
  4804. * @returns a new quaternion created from the given rotation matrix values
  4805. */
  4806. Quaternion.FromRotationMatrix = function (matrix) {
  4807. var result = new Quaternion();
  4808. Quaternion.FromRotationMatrixToRef(matrix, result);
  4809. return result;
  4810. };
  4811. /**
  4812. * Updates the given quaternion with the given rotation matrix values
  4813. * @param matrix defines the source matrix
  4814. * @param result defines the target quaternion
  4815. */
  4816. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4817. var data = matrix.m;
  4818. var m11 = data[0], m12 = data[4], m13 = data[8];
  4819. var m21 = data[1], m22 = data[5], m23 = data[9];
  4820. var m31 = data[2], m32 = data[6], m33 = data[10];
  4821. var trace = m11 + m22 + m33;
  4822. var s;
  4823. if (trace > 0) {
  4824. s = 0.5 / Math.sqrt(trace + 1.0);
  4825. result.w = 0.25 / s;
  4826. result.x = (m32 - m23) * s;
  4827. result.y = (m13 - m31) * s;
  4828. result.z = (m21 - m12) * s;
  4829. }
  4830. else if (m11 > m22 && m11 > m33) {
  4831. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4832. result.w = (m32 - m23) / s;
  4833. result.x = 0.25 * s;
  4834. result.y = (m12 + m21) / s;
  4835. result.z = (m13 + m31) / s;
  4836. }
  4837. else if (m22 > m33) {
  4838. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4839. result.w = (m13 - m31) / s;
  4840. result.x = (m12 + m21) / s;
  4841. result.y = 0.25 * s;
  4842. result.z = (m23 + m32) / s;
  4843. }
  4844. else {
  4845. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4846. result.w = (m21 - m12) / s;
  4847. result.x = (m13 + m31) / s;
  4848. result.y = (m23 + m32) / s;
  4849. result.z = 0.25 * s;
  4850. }
  4851. };
  4852. /**
  4853. * Returns the dot product (float) between the quaternions "left" and "right"
  4854. * @param left defines the left operand
  4855. * @param right defines the right operand
  4856. * @returns the dot product
  4857. */
  4858. Quaternion.Dot = function (left, right) {
  4859. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4860. };
  4861. /**
  4862. * Checks if the two quaternions are close to each other
  4863. * @param quat0 defines the first quaternion to check
  4864. * @param quat1 defines the second quaternion to check
  4865. * @returns true if the two quaternions are close to each other
  4866. */
  4867. Quaternion.AreClose = function (quat0, quat1) {
  4868. var dot = Quaternion.Dot(quat0, quat1);
  4869. return dot >= 0;
  4870. };
  4871. /**
  4872. * Creates an empty quaternion
  4873. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4874. */
  4875. Quaternion.Zero = function () {
  4876. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4877. };
  4878. /**
  4879. * Inverse a given quaternion
  4880. * @param q defines the source quaternion
  4881. * @returns a new quaternion as the inverted current quaternion
  4882. */
  4883. Quaternion.Inverse = function (q) {
  4884. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4885. };
  4886. /**
  4887. * Creates an identity quaternion
  4888. * @returns the identity quaternion
  4889. */
  4890. Quaternion.Identity = function () {
  4891. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4892. };
  4893. /**
  4894. * Gets a boolean indicating if the given quaternion is identity
  4895. * @param quaternion defines the quaternion to check
  4896. * @returns true if the quaternion is identity
  4897. */
  4898. Quaternion.IsIdentity = function (quaternion) {
  4899. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4900. };
  4901. /**
  4902. * Creates a quaternion from a rotation around an axis
  4903. * @param axis defines the axis to use
  4904. * @param angle defines the angle to use
  4905. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4906. */
  4907. Quaternion.RotationAxis = function (axis, angle) {
  4908. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4909. };
  4910. /**
  4911. * Creates a rotation around an axis and stores it into the given quaternion
  4912. * @param axis defines the axis to use
  4913. * @param angle defines the angle to use
  4914. * @param result defines the target quaternion
  4915. * @returns the target quaternion
  4916. */
  4917. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4918. var sin = Math.sin(angle / 2);
  4919. axis.normalize();
  4920. result.w = Math.cos(angle / 2);
  4921. result.x = axis.x * sin;
  4922. result.y = axis.y * sin;
  4923. result.z = axis.z * sin;
  4924. return result;
  4925. };
  4926. /**
  4927. * Creates a new quaternion from data stored into an array
  4928. * @param array defines the data source
  4929. * @param offset defines the offset in the source array where the data starts
  4930. * @returns a new quaternion
  4931. */
  4932. Quaternion.FromArray = function (array, offset) {
  4933. if (!offset) {
  4934. offset = 0;
  4935. }
  4936. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4937. };
  4938. /**
  4939. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4940. * @param yaw defines the rotation around Y axis
  4941. * @param pitch defines the rotation around X axis
  4942. * @param roll defines the rotation around Z axis
  4943. * @returns the new quaternion
  4944. */
  4945. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4946. var q = new Quaternion();
  4947. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4948. return q;
  4949. };
  4950. /**
  4951. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4952. * @param yaw defines the rotation around Y axis
  4953. * @param pitch defines the rotation around X axis
  4954. * @param roll defines the rotation around Z axis
  4955. * @param result defines the target quaternion
  4956. */
  4957. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4958. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4959. var halfRoll = roll * 0.5;
  4960. var halfPitch = pitch * 0.5;
  4961. var halfYaw = yaw * 0.5;
  4962. var sinRoll = Math.sin(halfRoll);
  4963. var cosRoll = Math.cos(halfRoll);
  4964. var sinPitch = Math.sin(halfPitch);
  4965. var cosPitch = Math.cos(halfPitch);
  4966. var sinYaw = Math.sin(halfYaw);
  4967. var cosYaw = Math.cos(halfYaw);
  4968. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4969. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4970. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4971. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4972. };
  4973. /**
  4974. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4975. * @param alpha defines the rotation around first axis
  4976. * @param beta defines the rotation around second axis
  4977. * @param gamma defines the rotation around third axis
  4978. * @returns the new quaternion
  4979. */
  4980. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4981. var result = new Quaternion();
  4982. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4983. return result;
  4984. };
  4985. /**
  4986. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4987. * @param alpha defines the rotation around first axis
  4988. * @param beta defines the rotation around second axis
  4989. * @param gamma defines the rotation around third axis
  4990. * @param result defines the target quaternion
  4991. */
  4992. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4993. // Produces a quaternion from Euler angles in the z-x-z orientation
  4994. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4995. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4996. var halfBeta = beta * 0.5;
  4997. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4998. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4999. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5000. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5001. };
  5002. /**
  5003. * 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)
  5004. * @param axis1 defines the first axis
  5005. * @param axis2 defines the second axis
  5006. * @param axis3 defines the third axis
  5007. * @returns the new quaternion
  5008. */
  5009. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5010. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5011. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5012. return quat;
  5013. };
  5014. /**
  5015. * 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
  5016. * @param axis1 defines the first axis
  5017. * @param axis2 defines the second axis
  5018. * @param axis3 defines the third axis
  5019. * @param ref defines the target quaternion
  5020. */
  5021. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5022. var rotMat = MathTmp.Matrix[0];
  5023. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5024. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5025. };
  5026. /**
  5027. * Interpolates between two quaternions
  5028. * @param left defines first quaternion
  5029. * @param right defines second quaternion
  5030. * @param amount defines the gradient to use
  5031. * @returns the new interpolated quaternion
  5032. */
  5033. Quaternion.Slerp = function (left, right, amount) {
  5034. var result = Quaternion.Identity();
  5035. Quaternion.SlerpToRef(left, right, amount, result);
  5036. return result;
  5037. };
  5038. /**
  5039. * Interpolates between two quaternions and stores it into a target quaternion
  5040. * @param left defines first quaternion
  5041. * @param right defines second quaternion
  5042. * @param amount defines the gradient to use
  5043. * @param result defines the target quaternion
  5044. */
  5045. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5046. var num2;
  5047. var num3;
  5048. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5049. var flag = false;
  5050. if (num4 < 0) {
  5051. flag = true;
  5052. num4 = -num4;
  5053. }
  5054. if (num4 > 0.999999) {
  5055. num3 = 1 - amount;
  5056. num2 = flag ? -amount : amount;
  5057. }
  5058. else {
  5059. var num5 = Math.acos(num4);
  5060. var num6 = (1.0 / Math.sin(num5));
  5061. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5062. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5063. }
  5064. result.x = (num3 * left.x) + (num2 * right.x);
  5065. result.y = (num3 * left.y) + (num2 * right.y);
  5066. result.z = (num3 * left.z) + (num2 * right.z);
  5067. result.w = (num3 * left.w) + (num2 * right.w);
  5068. };
  5069. /**
  5070. * Interpolate between two quaternions using Hermite interpolation
  5071. * @param value1 defines first quaternion
  5072. * @param tangent1 defines the incoming tangent
  5073. * @param value2 defines second quaternion
  5074. * @param tangent2 defines the outgoing tangent
  5075. * @param amount defines the target quaternion
  5076. * @returns the new interpolated quaternion
  5077. */
  5078. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5079. var squared = amount * amount;
  5080. var cubed = amount * squared;
  5081. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5082. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5083. var part3 = (cubed - (2.0 * squared)) + amount;
  5084. var part4 = cubed - squared;
  5085. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5086. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5087. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5088. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5089. return new Quaternion(x, y, z, w);
  5090. };
  5091. return Quaternion;
  5092. }());
  5093. BABYLON.Quaternion = Quaternion;
  5094. /**
  5095. * Class used to store matrix data (4x4)
  5096. */
  5097. var Matrix = /** @class */ (function () {
  5098. /**
  5099. * Creates an empty matrix (filled with zeros)
  5100. */
  5101. function Matrix() {
  5102. this._isIdentity = false;
  5103. this._isIdentityDirty = true;
  5104. /**
  5105. * Gets or sets the internal data of the matrix
  5106. */
  5107. this.m = new Float32Array(16);
  5108. this._markAsUpdated();
  5109. }
  5110. /** @hidden */
  5111. Matrix.prototype._markAsUpdated = function () {
  5112. this.updateFlag = Matrix._updateFlagSeed++;
  5113. this._isIdentityDirty = true;
  5114. };
  5115. // Properties
  5116. /**
  5117. * Check if the current matrix is indentity
  5118. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5119. * @returns true is the matrix is the identity matrix
  5120. */
  5121. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5122. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5123. if (this._isIdentityDirty) {
  5124. this._isIdentityDirty = false;
  5125. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5126. this._isIdentity = false;
  5127. }
  5128. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5129. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5130. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5131. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5132. this._isIdentity = false;
  5133. }
  5134. else {
  5135. this._isIdentity = true;
  5136. }
  5137. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5138. this._isIdentity = false;
  5139. }
  5140. }
  5141. return this._isIdentity;
  5142. };
  5143. /**
  5144. * Gets the determinant of the matrix
  5145. * @returns the matrix determinant
  5146. */
  5147. Matrix.prototype.determinant = function () {
  5148. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5149. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5150. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5151. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5152. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5153. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5154. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5155. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5156. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5157. };
  5158. // Methods
  5159. /**
  5160. * Returns the matrix as a Float32Array
  5161. * @returns the matrix underlying array
  5162. */
  5163. Matrix.prototype.toArray = function () {
  5164. return this.m;
  5165. };
  5166. /**
  5167. * Returns the matrix as a Float32Array
  5168. * @returns the matrix underlying array.
  5169. */
  5170. Matrix.prototype.asArray = function () {
  5171. return this.toArray();
  5172. };
  5173. /**
  5174. * Inverts the current matrix in place
  5175. * @returns the current inverted matrix
  5176. */
  5177. Matrix.prototype.invert = function () {
  5178. this.invertToRef(this);
  5179. return this;
  5180. };
  5181. /**
  5182. * Sets all the matrix elements to zero
  5183. * @returns the current matrix
  5184. */
  5185. Matrix.prototype.reset = function () {
  5186. for (var index = 0; index < 16; index++) {
  5187. this.m[index] = 0.0;
  5188. }
  5189. this._markAsUpdated();
  5190. return this;
  5191. };
  5192. /**
  5193. * Adds the current matrix with a second one
  5194. * @param other defines the matrix to add
  5195. * @returns a new matrix as the addition of the current matrix and the given one
  5196. */
  5197. Matrix.prototype.add = function (other) {
  5198. var result = new Matrix();
  5199. this.addToRef(other, result);
  5200. return result;
  5201. };
  5202. /**
  5203. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5204. * @param other defines the matrix to add
  5205. * @param result defines the target matrix
  5206. * @returns the current matrix
  5207. */
  5208. Matrix.prototype.addToRef = function (other, result) {
  5209. for (var index = 0; index < 16; index++) {
  5210. result.m[index] = this.m[index] + other.m[index];
  5211. }
  5212. result._markAsUpdated();
  5213. return this;
  5214. };
  5215. /**
  5216. * Adds in place the given matrix to the current matrix
  5217. * @param other defines the second operand
  5218. * @returns the current updated matrix
  5219. */
  5220. Matrix.prototype.addToSelf = function (other) {
  5221. for (var index = 0; index < 16; index++) {
  5222. this.m[index] += other.m[index];
  5223. }
  5224. this._markAsUpdated();
  5225. return this;
  5226. };
  5227. /**
  5228. * Sets the given matrix to the current inverted Matrix
  5229. * @param other defines the target matrix
  5230. * @returns the unmodified current matrix
  5231. */
  5232. Matrix.prototype.invertToRef = function (other) {
  5233. var l1 = this.m[0];
  5234. var l2 = this.m[1];
  5235. var l3 = this.m[2];
  5236. var l4 = this.m[3];
  5237. var l5 = this.m[4];
  5238. var l6 = this.m[5];
  5239. var l7 = this.m[6];
  5240. var l8 = this.m[7];
  5241. var l9 = this.m[8];
  5242. var l10 = this.m[9];
  5243. var l11 = this.m[10];
  5244. var l12 = this.m[11];
  5245. var l13 = this.m[12];
  5246. var l14 = this.m[13];
  5247. var l15 = this.m[14];
  5248. var l16 = this.m[15];
  5249. var l17 = (l11 * l16) - (l12 * l15);
  5250. var l18 = (l10 * l16) - (l12 * l14);
  5251. var l19 = (l10 * l15) - (l11 * l14);
  5252. var l20 = (l9 * l16) - (l12 * l13);
  5253. var l21 = (l9 * l15) - (l11 * l13);
  5254. var l22 = (l9 * l14) - (l10 * l13);
  5255. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5256. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5257. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5258. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5259. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5260. var l28 = (l7 * l16) - (l8 * l15);
  5261. var l29 = (l6 * l16) - (l8 * l14);
  5262. var l30 = (l6 * l15) - (l7 * l14);
  5263. var l31 = (l5 * l16) - (l8 * l13);
  5264. var l32 = (l5 * l15) - (l7 * l13);
  5265. var l33 = (l5 * l14) - (l6 * l13);
  5266. var l34 = (l7 * l12) - (l8 * l11);
  5267. var l35 = (l6 * l12) - (l8 * l10);
  5268. var l36 = (l6 * l11) - (l7 * l10);
  5269. var l37 = (l5 * l12) - (l8 * l9);
  5270. var l38 = (l5 * l11) - (l7 * l9);
  5271. var l39 = (l5 * l10) - (l6 * l9);
  5272. other.m[0] = l23 * l27;
  5273. other.m[4] = l24 * l27;
  5274. other.m[8] = l25 * l27;
  5275. other.m[12] = l26 * l27;
  5276. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5277. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5278. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5279. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5280. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5281. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5282. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5283. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5284. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5285. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5286. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5287. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5288. other._markAsUpdated();
  5289. return this;
  5290. };
  5291. /**
  5292. * Inserts the translation vector (using 3 floats) in the current matrix
  5293. * @param x defines the 1st component of the translation
  5294. * @param y defines the 2nd component of the translation
  5295. * @param z defines the 3rd component of the translation
  5296. * @returns the current updated matrix
  5297. */
  5298. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5299. this.m[12] = x;
  5300. this.m[13] = y;
  5301. this.m[14] = z;
  5302. this._markAsUpdated();
  5303. return this;
  5304. };
  5305. /**
  5306. * Inserts the translation vector in the current matrix
  5307. * @param vector3 defines the translation to insert
  5308. * @returns the current updated matrix
  5309. */
  5310. Matrix.prototype.setTranslation = function (vector3) {
  5311. this.m[12] = vector3.x;
  5312. this.m[13] = vector3.y;
  5313. this.m[14] = vector3.z;
  5314. this._markAsUpdated();
  5315. return this;
  5316. };
  5317. /**
  5318. * Gets the translation value of the current matrix
  5319. * @returns a new Vector3 as the extracted translation from the matrix
  5320. */
  5321. Matrix.prototype.getTranslation = function () {
  5322. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5323. };
  5324. /**
  5325. * Fill a Vector3 with the extracted translation from the matrix
  5326. * @param result defines the Vector3 where to store the translation
  5327. * @returns the current matrix
  5328. */
  5329. Matrix.prototype.getTranslationToRef = function (result) {
  5330. result.x = this.m[12];
  5331. result.y = this.m[13];
  5332. result.z = this.m[14];
  5333. return this;
  5334. };
  5335. /**
  5336. * Remove rotation and scaling part from the matrix
  5337. * @returns the updated matrix
  5338. */
  5339. Matrix.prototype.removeRotationAndScaling = function () {
  5340. this.setRowFromFloats(0, 1, 0, 0, 0);
  5341. this.setRowFromFloats(1, 0, 1, 0, 0);
  5342. this.setRowFromFloats(2, 0, 0, 1, 0);
  5343. return this;
  5344. };
  5345. /**
  5346. * Multiply two matrices
  5347. * @param other defines the second operand
  5348. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5349. */
  5350. Matrix.prototype.multiply = function (other) {
  5351. var result = new Matrix();
  5352. this.multiplyToRef(other, result);
  5353. return result;
  5354. };
  5355. /**
  5356. * Copy the current matrix from the given one
  5357. * @param other defines the source matrix
  5358. * @returns the current updated matrix
  5359. */
  5360. Matrix.prototype.copyFrom = function (other) {
  5361. for (var index = 0; index < 16; index++) {
  5362. this.m[index] = other.m[index];
  5363. }
  5364. this._markAsUpdated();
  5365. return this;
  5366. };
  5367. /**
  5368. * Populates the given array from the starting index with the current matrix values
  5369. * @param array defines the target array
  5370. * @param offset defines the offset in the target array where to start storing values
  5371. * @returns the current matrix
  5372. */
  5373. Matrix.prototype.copyToArray = function (array, offset) {
  5374. if (offset === void 0) { offset = 0; }
  5375. for (var index = 0; index < 16; index++) {
  5376. array[offset + index] = this.m[index];
  5377. }
  5378. return this;
  5379. };
  5380. /**
  5381. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5382. * @param other defines the second operand
  5383. * @param result defines the matrix where to store the multiplication
  5384. * @returns the current matrix
  5385. */
  5386. Matrix.prototype.multiplyToRef = function (other, result) {
  5387. this.multiplyToArray(other, result.m, 0);
  5388. result._markAsUpdated();
  5389. return this;
  5390. };
  5391. /**
  5392. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5393. * @param other defines the second operand
  5394. * @param result defines the array where to store the multiplication
  5395. * @param offset defines the offset in the target array where to start storing values
  5396. * @returns the current matrix
  5397. */
  5398. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5399. var tm0 = this.m[0];
  5400. var tm1 = this.m[1];
  5401. var tm2 = this.m[2];
  5402. var tm3 = this.m[3];
  5403. var tm4 = this.m[4];
  5404. var tm5 = this.m[5];
  5405. var tm6 = this.m[6];
  5406. var tm7 = this.m[7];
  5407. var tm8 = this.m[8];
  5408. var tm9 = this.m[9];
  5409. var tm10 = this.m[10];
  5410. var tm11 = this.m[11];
  5411. var tm12 = this.m[12];
  5412. var tm13 = this.m[13];
  5413. var tm14 = this.m[14];
  5414. var tm15 = this.m[15];
  5415. var om0 = other.m[0];
  5416. var om1 = other.m[1];
  5417. var om2 = other.m[2];
  5418. var om3 = other.m[3];
  5419. var om4 = other.m[4];
  5420. var om5 = other.m[5];
  5421. var om6 = other.m[6];
  5422. var om7 = other.m[7];
  5423. var om8 = other.m[8];
  5424. var om9 = other.m[9];
  5425. var om10 = other.m[10];
  5426. var om11 = other.m[11];
  5427. var om12 = other.m[12];
  5428. var om13 = other.m[13];
  5429. var om14 = other.m[14];
  5430. var om15 = other.m[15];
  5431. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5432. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5433. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5434. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5435. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5436. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5437. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5438. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5439. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5440. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5441. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5442. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5443. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5444. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5445. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5446. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5447. return this;
  5448. };
  5449. /**
  5450. * Check equality between this matrix and a second one
  5451. * @param value defines the second matrix to compare
  5452. * @returns true is the current matrix and the given one values are strictly equal
  5453. */
  5454. Matrix.prototype.equals = function (value) {
  5455. return value &&
  5456. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5457. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5458. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5459. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5460. };
  5461. /**
  5462. * Clone the current matrix
  5463. * @returns a new matrix from the current matrix
  5464. */
  5465. Matrix.prototype.clone = function () {
  5466. 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]);
  5467. };
  5468. /**
  5469. * Returns the name of the current matrix class
  5470. * @returns the string "Matrix"
  5471. */
  5472. Matrix.prototype.getClassName = function () {
  5473. return "Matrix";
  5474. };
  5475. /**
  5476. * Gets the hash code of the current matrix
  5477. * @returns the hash code
  5478. */
  5479. Matrix.prototype.getHashCode = function () {
  5480. var hash = this.m[0] || 0;
  5481. for (var i = 1; i < 16; i++) {
  5482. hash = (hash * 397) ^ (this.m[i] || 0);
  5483. }
  5484. return hash;
  5485. };
  5486. /**
  5487. * Decomposes the current Matrix into a translation, rotation and scaling components
  5488. * @param scale defines the scale vector3 given as a reference to update
  5489. * @param rotation defines the rotation quaternion given as a reference to update
  5490. * @param translation defines the translation vector3 given as a reference to update
  5491. * @returns true if operation was successful
  5492. */
  5493. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5494. if (translation) {
  5495. translation.x = this.m[12];
  5496. translation.y = this.m[13];
  5497. translation.z = this.m[14];
  5498. }
  5499. scale = scale || MathTmp.Vector3[0];
  5500. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5501. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5502. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5503. if (this.determinant() <= 0) {
  5504. scale.y *= -1;
  5505. }
  5506. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5507. if (rotation) {
  5508. rotation.x = 0;
  5509. rotation.y = 0;
  5510. rotation.z = 0;
  5511. rotation.w = 1;
  5512. }
  5513. return false;
  5514. }
  5515. if (rotation) {
  5516. 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]);
  5517. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5518. }
  5519. return true;
  5520. };
  5521. /**
  5522. * Gets specific row of the matrix
  5523. * @param index defines the number of the row to get
  5524. * @returns the index-th row of the current matrix as a new Vector4
  5525. */
  5526. Matrix.prototype.getRow = function (index) {
  5527. if (index < 0 || index > 3) {
  5528. return null;
  5529. }
  5530. var i = index * 4;
  5531. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5532. };
  5533. /**
  5534. * Sets the index-th row of the current matrix to the vector4 values
  5535. * @param index defines the number of the row to set
  5536. * @param row defines the target vector4
  5537. * @returns the updated current matrix
  5538. */
  5539. Matrix.prototype.setRow = function (index, row) {
  5540. if (index < 0 || index > 3) {
  5541. return this;
  5542. }
  5543. var i = index * 4;
  5544. this.m[i + 0] = row.x;
  5545. this.m[i + 1] = row.y;
  5546. this.m[i + 2] = row.z;
  5547. this.m[i + 3] = row.w;
  5548. this._markAsUpdated();
  5549. return this;
  5550. };
  5551. /**
  5552. * Compute the transpose of the matrix
  5553. * @returns the new transposed matrix
  5554. */
  5555. Matrix.prototype.transpose = function () {
  5556. return Matrix.Transpose(this);
  5557. };
  5558. /**
  5559. * Compute the transpose of the matrix and store it in a given matrix
  5560. * @param result defines the target matrix
  5561. * @returns the current matrix
  5562. */
  5563. Matrix.prototype.transposeToRef = function (result) {
  5564. Matrix.TransposeToRef(this, result);
  5565. return this;
  5566. };
  5567. /**
  5568. * Sets the index-th row of the current matrix with the given 4 x float values
  5569. * @param index defines the row index
  5570. * @param x defines the x component to set
  5571. * @param y defines the y component to set
  5572. * @param z defines the z component to set
  5573. * @param w defines the w component to set
  5574. * @returns the updated current matrix
  5575. */
  5576. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5577. if (index < 0 || index > 3) {
  5578. return this;
  5579. }
  5580. var i = index * 4;
  5581. this.m[i + 0] = x;
  5582. this.m[i + 1] = y;
  5583. this.m[i + 2] = z;
  5584. this.m[i + 3] = w;
  5585. this._markAsUpdated();
  5586. return this;
  5587. };
  5588. /**
  5589. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5590. * @param scale defines the scale factor
  5591. * @returns a new matrix
  5592. */
  5593. Matrix.prototype.scale = function (scale) {
  5594. var result = new Matrix();
  5595. this.scaleToRef(scale, result);
  5596. return result;
  5597. };
  5598. /**
  5599. * Scale the current matrix values by a factor to a given result matrix
  5600. * @param scale defines the scale factor
  5601. * @param result defines the matrix to store the result
  5602. * @returns the current matrix
  5603. */
  5604. Matrix.prototype.scaleToRef = function (scale, result) {
  5605. for (var index = 0; index < 16; index++) {
  5606. result.m[index] = this.m[index] * scale;
  5607. }
  5608. result._markAsUpdated();
  5609. return this;
  5610. };
  5611. /**
  5612. * Scale the current matrix values by a factor and add the result to a given matrix
  5613. * @param scale defines the scale factor
  5614. * @param result defines the Matrix to store the result
  5615. * @returns the current matrix
  5616. */
  5617. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5618. for (var index = 0; index < 16; index++) {
  5619. result.m[index] += this.m[index] * scale;
  5620. }
  5621. result._markAsUpdated();
  5622. return this;
  5623. };
  5624. /**
  5625. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5626. * @param ref matrix to store the result
  5627. */
  5628. Matrix.prototype.toNormalMatrix = function (ref) {
  5629. this.invertToRef(ref);
  5630. ref.transpose();
  5631. var m = ref.m;
  5632. 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);
  5633. };
  5634. /**
  5635. * Gets only rotation part of the current matrix
  5636. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5637. */
  5638. Matrix.prototype.getRotationMatrix = function () {
  5639. var result = Matrix.Identity();
  5640. this.getRotationMatrixToRef(result);
  5641. return result;
  5642. };
  5643. /**
  5644. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5645. * @param result defines the target matrix to store data to
  5646. * @returns the current matrix
  5647. */
  5648. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5649. var m = this.m;
  5650. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5651. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5652. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5653. if (this.determinant() <= 0) {
  5654. sy *= -1;
  5655. }
  5656. if (sx === 0 || sy === 0 || sz === 0) {
  5657. Matrix.IdentityToRef(result);
  5658. }
  5659. else {
  5660. 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);
  5661. }
  5662. return this;
  5663. };
  5664. // Statics
  5665. /**
  5666. * Creates a matrix from an array
  5667. * @param array defines the source array
  5668. * @param offset defines an offset in the source array
  5669. * @returns a new Matrix set from the starting index of the given array
  5670. */
  5671. Matrix.FromArray = function (array, offset) {
  5672. var result = new Matrix();
  5673. if (!offset) {
  5674. offset = 0;
  5675. }
  5676. Matrix.FromArrayToRef(array, offset, result);
  5677. return result;
  5678. };
  5679. /**
  5680. * Copy the content of an array into a given matrix
  5681. * @param array defines the source array
  5682. * @param offset defines an offset in the source array
  5683. * @param result defines the target matrix
  5684. */
  5685. Matrix.FromArrayToRef = function (array, offset, result) {
  5686. for (var index = 0; index < 16; index++) {
  5687. result.m[index] = array[index + offset];
  5688. }
  5689. result._markAsUpdated();
  5690. };
  5691. /**
  5692. * Stores an array into a matrix after having multiplied each component by a given factor
  5693. * @param array defines the source array
  5694. * @param offset defines the offset in the source array
  5695. * @param scale defines the scaling factor
  5696. * @param result defines the target matrix
  5697. */
  5698. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5699. for (var index = 0; index < 16; index++) {
  5700. result.m[index] = array[index + offset] * scale;
  5701. }
  5702. result._markAsUpdated();
  5703. };
  5704. /**
  5705. * Stores a list of values (16) inside a given matrix
  5706. * @param initialM11 defines 1st value of 1st row
  5707. * @param initialM12 defines 2nd value of 1st row
  5708. * @param initialM13 defines 3rd value of 1st row
  5709. * @param initialM14 defines 4th value of 1st row
  5710. * @param initialM21 defines 1st value of 2nd row
  5711. * @param initialM22 defines 2nd value of 2nd row
  5712. * @param initialM23 defines 3rd value of 2nd row
  5713. * @param initialM24 defines 4th value of 2nd row
  5714. * @param initialM31 defines 1st value of 3rd row
  5715. * @param initialM32 defines 2nd value of 3rd row
  5716. * @param initialM33 defines 3rd value of 3rd row
  5717. * @param initialM34 defines 4th value of 3rd row
  5718. * @param initialM41 defines 1st value of 4th row
  5719. * @param initialM42 defines 2nd value of 4th row
  5720. * @param initialM43 defines 3rd value of 4th row
  5721. * @param initialM44 defines 4th value of 4th row
  5722. * @param result defines the target matrix
  5723. */
  5724. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5725. result.m[0] = initialM11;
  5726. result.m[1] = initialM12;
  5727. result.m[2] = initialM13;
  5728. result.m[3] = initialM14;
  5729. result.m[4] = initialM21;
  5730. result.m[5] = initialM22;
  5731. result.m[6] = initialM23;
  5732. result.m[7] = initialM24;
  5733. result.m[8] = initialM31;
  5734. result.m[9] = initialM32;
  5735. result.m[10] = initialM33;
  5736. result.m[11] = initialM34;
  5737. result.m[12] = initialM41;
  5738. result.m[13] = initialM42;
  5739. result.m[14] = initialM43;
  5740. result.m[15] = initialM44;
  5741. result._markAsUpdated();
  5742. };
  5743. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5744. /**
  5745. * Gets an identity matrix that must not be updated
  5746. */
  5747. get: function () {
  5748. return Matrix._identityReadOnly;
  5749. },
  5750. enumerable: true,
  5751. configurable: true
  5752. });
  5753. /**
  5754. * Creates new matrix from a list of values (16)
  5755. * @param initialM11 defines 1st value of 1st row
  5756. * @param initialM12 defines 2nd value of 1st row
  5757. * @param initialM13 defines 3rd value of 1st row
  5758. * @param initialM14 defines 4th value of 1st row
  5759. * @param initialM21 defines 1st value of 2nd row
  5760. * @param initialM22 defines 2nd value of 2nd row
  5761. * @param initialM23 defines 3rd value of 2nd row
  5762. * @param initialM24 defines 4th value of 2nd row
  5763. * @param initialM31 defines 1st value of 3rd row
  5764. * @param initialM32 defines 2nd value of 3rd row
  5765. * @param initialM33 defines 3rd value of 3rd row
  5766. * @param initialM34 defines 4th value of 3rd row
  5767. * @param initialM41 defines 1st value of 4th row
  5768. * @param initialM42 defines 2nd value of 4th row
  5769. * @param initialM43 defines 3rd value of 4th row
  5770. * @param initialM44 defines 4th value of 4th row
  5771. * @returns the new matrix
  5772. */
  5773. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5774. var result = new Matrix();
  5775. result.m[0] = initialM11;
  5776. result.m[1] = initialM12;
  5777. result.m[2] = initialM13;
  5778. result.m[3] = initialM14;
  5779. result.m[4] = initialM21;
  5780. result.m[5] = initialM22;
  5781. result.m[6] = initialM23;
  5782. result.m[7] = initialM24;
  5783. result.m[8] = initialM31;
  5784. result.m[9] = initialM32;
  5785. result.m[10] = initialM33;
  5786. result.m[11] = initialM34;
  5787. result.m[12] = initialM41;
  5788. result.m[13] = initialM42;
  5789. result.m[14] = initialM43;
  5790. result.m[15] = initialM44;
  5791. return result;
  5792. };
  5793. /**
  5794. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5795. * @param scale defines the scale vector3
  5796. * @param rotation defines the rotation quaternion
  5797. * @param translation defines the translation vector3
  5798. * @returns a new matrix
  5799. */
  5800. Matrix.Compose = function (scale, rotation, translation) {
  5801. var result = Matrix.Identity();
  5802. Matrix.ComposeToRef(scale, rotation, translation, result);
  5803. return result;
  5804. };
  5805. /**
  5806. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5807. * @param scale defines the scale vector3
  5808. * @param rotation defines the rotation quaternion
  5809. * @param translation defines the translation vector3
  5810. * @param result defines the target matrix
  5811. */
  5812. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5813. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5814. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5815. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5816. result.setTranslation(translation);
  5817. };
  5818. /**
  5819. * Creates a new identity matrix
  5820. * @returns a new identity matrix
  5821. */
  5822. Matrix.Identity = function () {
  5823. 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);
  5824. };
  5825. /**
  5826. * Creates a new identity matrix and stores the result in a given matrix
  5827. * @param result defines the target matrix
  5828. */
  5829. Matrix.IdentityToRef = function (result) {
  5830. 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);
  5831. };
  5832. /**
  5833. * Creates a new zero matrix
  5834. * @returns a new zero matrix
  5835. */
  5836. Matrix.Zero = function () {
  5837. 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);
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the X axis
  5841. * @param angle defines the angle (in radians) to use
  5842. * @return the new matrix
  5843. */
  5844. Matrix.RotationX = function (angle) {
  5845. var result = new Matrix();
  5846. Matrix.RotationXToRef(angle, result);
  5847. return result;
  5848. };
  5849. /**
  5850. * Creates a new matrix as the invert of a given matrix
  5851. * @param source defines the source matrix
  5852. * @returns the new matrix
  5853. */
  5854. Matrix.Invert = function (source) {
  5855. var result = new Matrix();
  5856. source.invertToRef(result);
  5857. return result;
  5858. };
  5859. /**
  5860. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5861. * @param angle defines the angle (in radians) to use
  5862. * @param result defines the target matrix
  5863. */
  5864. Matrix.RotationXToRef = function (angle, result) {
  5865. var s = Math.sin(angle);
  5866. var c = Math.cos(angle);
  5867. result.m[0] = 1.0;
  5868. result.m[15] = 1.0;
  5869. result.m[5] = c;
  5870. result.m[10] = c;
  5871. result.m[9] = -s;
  5872. result.m[6] = s;
  5873. result.m[1] = 0.0;
  5874. result.m[2] = 0.0;
  5875. result.m[3] = 0.0;
  5876. result.m[4] = 0.0;
  5877. result.m[7] = 0.0;
  5878. result.m[8] = 0.0;
  5879. result.m[11] = 0.0;
  5880. result.m[12] = 0.0;
  5881. result.m[13] = 0.0;
  5882. result.m[14] = 0.0;
  5883. result._markAsUpdated();
  5884. };
  5885. /**
  5886. * Creates a new rotation matrix for "angle" radians around the Y axis
  5887. * @param angle defines the angle (in radians) to use
  5888. * @return the new matrix
  5889. */
  5890. Matrix.RotationY = function (angle) {
  5891. var result = new Matrix();
  5892. Matrix.RotationYToRef(angle, result);
  5893. return result;
  5894. };
  5895. /**
  5896. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5897. * @param angle defines the angle (in radians) to use
  5898. * @param result defines the target matrix
  5899. */
  5900. Matrix.RotationYToRef = function (angle, result) {
  5901. var s = Math.sin(angle);
  5902. var c = Math.cos(angle);
  5903. result.m[5] = 1.0;
  5904. result.m[15] = 1.0;
  5905. result.m[0] = c;
  5906. result.m[2] = -s;
  5907. result.m[8] = s;
  5908. result.m[10] = c;
  5909. result.m[1] = 0.0;
  5910. result.m[3] = 0.0;
  5911. result.m[4] = 0.0;
  5912. result.m[6] = 0.0;
  5913. result.m[7] = 0.0;
  5914. result.m[9] = 0.0;
  5915. result.m[11] = 0.0;
  5916. result.m[12] = 0.0;
  5917. result.m[13] = 0.0;
  5918. result.m[14] = 0.0;
  5919. result._markAsUpdated();
  5920. };
  5921. /**
  5922. * Creates a new rotation matrix for "angle" radians around the Z axis
  5923. * @param angle defines the angle (in radians) to use
  5924. * @return the new matrix
  5925. */
  5926. Matrix.RotationZ = function (angle) {
  5927. var result = new Matrix();
  5928. Matrix.RotationZToRef(angle, result);
  5929. return result;
  5930. };
  5931. /**
  5932. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5933. * @param angle defines the angle (in radians) to use
  5934. * @param result defines the target matrix
  5935. */
  5936. Matrix.RotationZToRef = function (angle, result) {
  5937. var s = Math.sin(angle);
  5938. var c = Math.cos(angle);
  5939. result.m[10] = 1.0;
  5940. result.m[15] = 1.0;
  5941. result.m[0] = c;
  5942. result.m[1] = s;
  5943. result.m[4] = -s;
  5944. result.m[5] = c;
  5945. result.m[2] = 0.0;
  5946. result.m[3] = 0.0;
  5947. result.m[6] = 0.0;
  5948. result.m[7] = 0.0;
  5949. result.m[8] = 0.0;
  5950. result.m[9] = 0.0;
  5951. result.m[11] = 0.0;
  5952. result.m[12] = 0.0;
  5953. result.m[13] = 0.0;
  5954. result.m[14] = 0.0;
  5955. result._markAsUpdated();
  5956. };
  5957. /**
  5958. * Creates a new rotation matrix for "angle" radians around the given axis
  5959. * @param axis defines the axis to use
  5960. * @param angle defines the angle (in radians) to use
  5961. * @return the new matrix
  5962. */
  5963. Matrix.RotationAxis = function (axis, angle) {
  5964. var result = Matrix.Zero();
  5965. Matrix.RotationAxisToRef(axis, angle, result);
  5966. return result;
  5967. };
  5968. /**
  5969. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5970. * @param axis defines the axis to use
  5971. * @param angle defines the angle (in radians) to use
  5972. * @param result defines the target matrix
  5973. */
  5974. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5975. var s = Math.sin(-angle);
  5976. var c = Math.cos(-angle);
  5977. var c1 = 1 - c;
  5978. axis.normalize();
  5979. result.m[0] = (axis.x * axis.x) * c1 + c;
  5980. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5981. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5982. result.m[3] = 0.0;
  5983. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5984. result.m[5] = (axis.y * axis.y) * c1 + c;
  5985. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5986. result.m[7] = 0.0;
  5987. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5988. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5989. result.m[10] = (axis.z * axis.z) * c1 + c;
  5990. result.m[11] = 0.0;
  5991. result.m[15] = 1.0;
  5992. result._markAsUpdated();
  5993. };
  5994. /**
  5995. * Creates a rotation matrix
  5996. * @param yaw defines the yaw angle in radians (Y axis)
  5997. * @param pitch defines the pitch angle in radians (X axis)
  5998. * @param roll defines the roll angle in radians (X axis)
  5999. * @returns the new rotation matrix
  6000. */
  6001. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6002. var result = new Matrix();
  6003. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6004. return result;
  6005. };
  6006. /**
  6007. * Creates a rotation matrix and stores it in a given matrix
  6008. * @param yaw defines the yaw angle in radians (Y axis)
  6009. * @param pitch defines the pitch angle in radians (X axis)
  6010. * @param roll defines the roll angle in radians (X axis)
  6011. * @param result defines the target matrix
  6012. */
  6013. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6014. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6015. this._tempQuaternion.toRotationMatrix(result);
  6016. };
  6017. /**
  6018. * Creates a scaling matrix
  6019. * @param x defines the scale factor on X axis
  6020. * @param y defines the scale factor on Y axis
  6021. * @param z defines the scale factor on Z axis
  6022. * @returns the new matrix
  6023. */
  6024. Matrix.Scaling = function (x, y, z) {
  6025. var result = Matrix.Zero();
  6026. Matrix.ScalingToRef(x, y, z, result);
  6027. return result;
  6028. };
  6029. /**
  6030. * Creates a scaling matrix and stores it in a given matrix
  6031. * @param x defines the scale factor on X axis
  6032. * @param y defines the scale factor on Y axis
  6033. * @param z defines the scale factor on Z axis
  6034. * @param result defines the target matrix
  6035. */
  6036. Matrix.ScalingToRef = function (x, y, z, result) {
  6037. result.m[0] = x;
  6038. result.m[1] = 0.0;
  6039. result.m[2] = 0.0;
  6040. result.m[3] = 0.0;
  6041. result.m[4] = 0.0;
  6042. result.m[5] = y;
  6043. result.m[6] = 0.0;
  6044. result.m[7] = 0.0;
  6045. result.m[8] = 0.0;
  6046. result.m[9] = 0.0;
  6047. result.m[10] = z;
  6048. result.m[11] = 0.0;
  6049. result.m[12] = 0.0;
  6050. result.m[13] = 0.0;
  6051. result.m[14] = 0.0;
  6052. result.m[15] = 1.0;
  6053. result._markAsUpdated();
  6054. };
  6055. /**
  6056. * Creates a translation matrix
  6057. * @param x defines the translation on X axis
  6058. * @param y defines the translation on Y axis
  6059. * @param z defines the translationon Z axis
  6060. * @returns the new matrix
  6061. */
  6062. Matrix.Translation = function (x, y, z) {
  6063. var result = Matrix.Identity();
  6064. Matrix.TranslationToRef(x, y, z, result);
  6065. return result;
  6066. };
  6067. /**
  6068. * Creates a translation matrix and stores it in a given matrix
  6069. * @param x defines the translation on X axis
  6070. * @param y defines the translation on Y axis
  6071. * @param z defines the translationon Z axis
  6072. * @param result defines the target matrix
  6073. */
  6074. Matrix.TranslationToRef = function (x, y, z, result) {
  6075. 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);
  6076. };
  6077. /**
  6078. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6079. * @param startValue defines the start value
  6080. * @param endValue defines the end value
  6081. * @param gradient defines the gradient factor
  6082. * @returns the new matrix
  6083. */
  6084. Matrix.Lerp = function (startValue, endValue, gradient) {
  6085. var result = Matrix.Zero();
  6086. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6087. return result;
  6088. };
  6089. /**
  6090. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6091. * @param startValue defines the start value
  6092. * @param endValue defines the end value
  6093. * @param gradient defines the gradient factor
  6094. * @param result defines the Matrix object where to store data
  6095. */
  6096. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6097. for (var index = 0; index < 16; index++) {
  6098. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6099. }
  6100. result._markAsUpdated();
  6101. };
  6102. /**
  6103. * Builds a new matrix whose values are computed by:
  6104. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6105. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6106. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6107. * @param startValue defines the first matrix
  6108. * @param endValue defines the second matrix
  6109. * @param gradient defines the gradient between the two matrices
  6110. * @returns the new matrix
  6111. */
  6112. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6113. var result = Matrix.Zero();
  6114. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6115. return result;
  6116. };
  6117. /**
  6118. * Update a matrix to values which are computed by:
  6119. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6120. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6121. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6122. * @param startValue defines the first matrix
  6123. * @param endValue defines the second matrix
  6124. * @param gradient defines the gradient between the two matrices
  6125. * @param result defines the target matrix
  6126. */
  6127. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6128. var startScale = MathTmp.Vector3[0];
  6129. var startRotation = MathTmp.Quaternion[0];
  6130. var startTranslation = MathTmp.Vector3[1];
  6131. startValue.decompose(startScale, startRotation, startTranslation);
  6132. var endScale = MathTmp.Vector3[2];
  6133. var endRotation = MathTmp.Quaternion[1];
  6134. var endTranslation = MathTmp.Vector3[3];
  6135. endValue.decompose(endScale, endRotation, endTranslation);
  6136. var resultScale = MathTmp.Vector3[4];
  6137. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6138. var resultRotation = MathTmp.Quaternion[2];
  6139. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6140. var resultTranslation = MathTmp.Vector3[5];
  6141. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6142. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6143. };
  6144. /**
  6145. * 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"
  6146. * This function works in left handed mode
  6147. * @param eye defines the final position of the entity
  6148. * @param target defines where the entity should look at
  6149. * @param up defines the up vector for the entity
  6150. * @returns the new matrix
  6151. */
  6152. Matrix.LookAtLH = function (eye, target, up) {
  6153. var result = Matrix.Zero();
  6154. Matrix.LookAtLHToRef(eye, target, up, result);
  6155. return result;
  6156. };
  6157. /**
  6158. * 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".
  6159. * This function works in left handed mode
  6160. * @param eye defines the final position of the entity
  6161. * @param target defines where the entity should look at
  6162. * @param up defines the up vector for the entity
  6163. * @param result defines the target matrix
  6164. */
  6165. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6166. // Z axis
  6167. target.subtractToRef(eye, this._zAxis);
  6168. this._zAxis.normalize();
  6169. // X axis
  6170. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6171. if (this._xAxis.lengthSquared() === 0) {
  6172. this._xAxis.x = 1.0;
  6173. }
  6174. else {
  6175. this._xAxis.normalize();
  6176. }
  6177. // Y axis
  6178. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6179. this._yAxis.normalize();
  6180. // Eye angles
  6181. var ex = -Vector3.Dot(this._xAxis, eye);
  6182. var ey = -Vector3.Dot(this._yAxis, eye);
  6183. var ez = -Vector3.Dot(this._zAxis, eye);
  6184. 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);
  6185. };
  6186. /**
  6187. * 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"
  6188. * This function works in right handed mode
  6189. * @param eye defines the final position of the entity
  6190. * @param target defines where the entity should look at
  6191. * @param up defines the up vector for the entity
  6192. * @returns the new matrix
  6193. */
  6194. Matrix.LookAtRH = function (eye, target, up) {
  6195. var result = Matrix.Zero();
  6196. Matrix.LookAtRHToRef(eye, target, up, result);
  6197. return result;
  6198. };
  6199. /**
  6200. * 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".
  6201. * This function works in right handed mode
  6202. * @param eye defines the final position of the entity
  6203. * @param target defines where the entity should look at
  6204. * @param up defines the up vector for the entity
  6205. * @param result defines the target matrix
  6206. */
  6207. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6208. // Z axis
  6209. eye.subtractToRef(target, this._zAxis);
  6210. this._zAxis.normalize();
  6211. // X axis
  6212. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6213. if (this._xAxis.lengthSquared() === 0) {
  6214. this._xAxis.x = 1.0;
  6215. }
  6216. else {
  6217. this._xAxis.normalize();
  6218. }
  6219. // Y axis
  6220. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6221. this._yAxis.normalize();
  6222. // Eye angles
  6223. var ex = -Vector3.Dot(this._xAxis, eye);
  6224. var ey = -Vector3.Dot(this._yAxis, eye);
  6225. var ez = -Vector3.Dot(this._zAxis, eye);
  6226. 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);
  6227. };
  6228. /**
  6229. * Create a left-handed orthographic projection matrix
  6230. * @param width defines the viewport width
  6231. * @param height defines the viewport height
  6232. * @param znear defines the near clip plane
  6233. * @param zfar defines the far clip plane
  6234. * @returns a new matrix as a left-handed orthographic projection matrix
  6235. */
  6236. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6237. var matrix = Matrix.Zero();
  6238. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6239. return matrix;
  6240. };
  6241. /**
  6242. * Store a left-handed orthographic projection to a given matrix
  6243. * @param width defines the viewport width
  6244. * @param height defines the viewport height
  6245. * @param znear defines the near clip plane
  6246. * @param zfar defines the far clip plane
  6247. * @param result defines the target matrix
  6248. */
  6249. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6250. var n = znear;
  6251. var f = zfar;
  6252. var a = 2.0 / width;
  6253. var b = 2.0 / height;
  6254. var c = 2.0 / (f - n);
  6255. var d = -(f + n) / (f - n);
  6256. 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);
  6257. };
  6258. /**
  6259. * Create a left-handed orthographic projection matrix
  6260. * @param left defines the viewport left coordinate
  6261. * @param right defines the viewport right coordinate
  6262. * @param bottom defines the viewport bottom coordinate
  6263. * @param top defines the viewport top coordinate
  6264. * @param znear defines the near clip plane
  6265. * @param zfar defines the far clip plane
  6266. * @returns a new matrix as a left-handed orthographic projection matrix
  6267. */
  6268. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6269. var matrix = Matrix.Zero();
  6270. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6271. return matrix;
  6272. };
  6273. /**
  6274. * Stores a left-handed orthographic projection into a given matrix
  6275. * @param left defines the viewport left coordinate
  6276. * @param right defines the viewport right coordinate
  6277. * @param bottom defines the viewport bottom coordinate
  6278. * @param top defines the viewport top coordinate
  6279. * @param znear defines the near clip plane
  6280. * @param zfar defines the far clip plane
  6281. * @param result defines the target matrix
  6282. */
  6283. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6284. var n = znear;
  6285. var f = zfar;
  6286. var a = 2.0 / (right - left);
  6287. var b = 2.0 / (top - bottom);
  6288. var c = 2.0 / (f - n);
  6289. var d = -(f + n) / (f - n);
  6290. var i0 = (left + right) / (left - right);
  6291. var i1 = (top + bottom) / (bottom - top);
  6292. 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);
  6293. };
  6294. /**
  6295. * Creates a right-handed orthographic projection matrix
  6296. * @param left defines the viewport left coordinate
  6297. * @param right defines the viewport right coordinate
  6298. * @param bottom defines the viewport bottom coordinate
  6299. * @param top defines the viewport top coordinate
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @returns a new matrix as a right-handed orthographic projection matrix
  6303. */
  6304. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6305. var matrix = Matrix.Zero();
  6306. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6307. return matrix;
  6308. };
  6309. /**
  6310. * Stores a right-handed orthographic projection into a given matrix
  6311. * @param left defines the viewport left coordinate
  6312. * @param right defines the viewport right coordinate
  6313. * @param bottom defines the viewport bottom coordinate
  6314. * @param top defines the viewport top coordinate
  6315. * @param znear defines the near clip plane
  6316. * @param zfar defines the far clip plane
  6317. * @param result defines the target matrix
  6318. */
  6319. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6320. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6321. result.m[10] *= -1.0;
  6322. };
  6323. /**
  6324. * Creates a left-handed perspective projection matrix
  6325. * @param width defines the viewport width
  6326. * @param height defines the viewport height
  6327. * @param znear defines the near clip plane
  6328. * @param zfar defines the far clip plane
  6329. * @returns a new matrix as a left-handed perspective projection matrix
  6330. */
  6331. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6332. var matrix = Matrix.Zero();
  6333. var n = znear;
  6334. var f = zfar;
  6335. var a = 2.0 * n / width;
  6336. var b = 2.0 * n / height;
  6337. var c = (f + n) / (f - n);
  6338. var d = -2.0 * f * n / (f - n);
  6339. 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);
  6340. return matrix;
  6341. };
  6342. /**
  6343. * Creates a left-handed perspective projection matrix
  6344. * @param fov defines the horizontal field of view
  6345. * @param aspect defines the aspect ratio
  6346. * @param znear defines the near clip plane
  6347. * @param zfar defines the far clip plane
  6348. * @returns a new matrix as a left-handed perspective projection matrix
  6349. */
  6350. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6351. var matrix = Matrix.Zero();
  6352. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6353. return matrix;
  6354. };
  6355. /**
  6356. * Stores a left-handed perspective projection into a given matrix
  6357. * @param fov defines the horizontal field of view
  6358. * @param aspect defines the aspect ratio
  6359. * @param znear defines the near clip plane
  6360. * @param zfar defines the far clip plane
  6361. * @param result defines the target matrix
  6362. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6363. */
  6364. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6365. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6366. var n = znear;
  6367. var f = zfar;
  6368. var t = 1.0 / (Math.tan(fov * 0.5));
  6369. var a = isVerticalFovFixed ? (t / aspect) : t;
  6370. var b = isVerticalFovFixed ? t : (t * aspect);
  6371. var c = (f + n) / (f - n);
  6372. var d = -2.0 * f * n / (f - n);
  6373. 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);
  6374. };
  6375. /**
  6376. * Creates a right-handed perspective projection matrix
  6377. * @param fov defines the horizontal field of view
  6378. * @param aspect defines the aspect ratio
  6379. * @param znear defines the near clip plane
  6380. * @param zfar defines the far clip plane
  6381. * @returns a new matrix as a right-handed perspective projection matrix
  6382. */
  6383. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6384. var matrix = Matrix.Zero();
  6385. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6386. return matrix;
  6387. };
  6388. /**
  6389. * Stores a right-handed perspective projection into a given matrix
  6390. * @param fov defines the horizontal field of view
  6391. * @param aspect defines the aspect ratio
  6392. * @param znear defines the near clip plane
  6393. * @param zfar defines the far clip plane
  6394. * @param result defines the target matrix
  6395. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6396. */
  6397. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6398. //alternatively this could be expressed as:
  6399. // m = PerspectiveFovLHToRef
  6400. // m[10] *= -1.0;
  6401. // m[11] *= -1.0;
  6402. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6403. var n = znear;
  6404. var f = zfar;
  6405. var t = 1.0 / (Math.tan(fov * 0.5));
  6406. var a = isVerticalFovFixed ? (t / aspect) : t;
  6407. var b = isVerticalFovFixed ? t : (t * aspect);
  6408. var c = -(f + n) / (f - n);
  6409. var d = -2 * f * n / (f - n);
  6410. 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);
  6411. };
  6412. /**
  6413. * Stores a perspective projection for WebVR info a given matrix
  6414. * @param fov defines the field of view
  6415. * @param znear defines the near clip plane
  6416. * @param zfar defines the far clip plane
  6417. * @param result defines the target matrix
  6418. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6419. */
  6420. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6421. if (rightHanded === void 0) { rightHanded = false; }
  6422. var rightHandedFactor = rightHanded ? -1 : 1;
  6423. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6424. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6425. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6426. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6427. var xScale = 2.0 / (leftTan + rightTan);
  6428. var yScale = 2.0 / (upTan + downTan);
  6429. result.m[0] = xScale;
  6430. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6431. result.m[5] = yScale;
  6432. result.m[6] = result.m[7] = 0.0;
  6433. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6434. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6435. result.m[10] = -zfar / (znear - zfar);
  6436. result.m[11] = 1.0 * rightHandedFactor;
  6437. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6438. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6439. result._markAsUpdated();
  6440. };
  6441. /**
  6442. * Computes a complete transformation matrix
  6443. * @param viewport defines the viewport to use
  6444. * @param world defines the world matrix
  6445. * @param view defines the view matrix
  6446. * @param projection defines the projection matrix
  6447. * @param zmin defines the near clip plane
  6448. * @param zmax defines the far clip plane
  6449. * @returns the transformation matrix
  6450. */
  6451. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6452. var cw = viewport.width;
  6453. var ch = viewport.height;
  6454. var cx = viewport.x;
  6455. var cy = viewport.y;
  6456. 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);
  6457. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6458. };
  6459. /**
  6460. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6461. * @param matrix defines the matrix to use
  6462. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6463. */
  6464. Matrix.GetAsMatrix2x2 = function (matrix) {
  6465. return new Float32Array([
  6466. matrix.m[0], matrix.m[1],
  6467. matrix.m[4], matrix.m[5]
  6468. ]);
  6469. };
  6470. /**
  6471. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6472. * @param matrix defines the matrix to use
  6473. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6474. */
  6475. Matrix.GetAsMatrix3x3 = function (matrix) {
  6476. return new Float32Array([
  6477. matrix.m[0], matrix.m[1], matrix.m[2],
  6478. matrix.m[4], matrix.m[5], matrix.m[6],
  6479. matrix.m[8], matrix.m[9], matrix.m[10]
  6480. ]);
  6481. };
  6482. /**
  6483. * Compute the transpose of a given matrix
  6484. * @param matrix defines the matrix to transpose
  6485. * @returns the new matrix
  6486. */
  6487. Matrix.Transpose = function (matrix) {
  6488. var result = new Matrix();
  6489. Matrix.TransposeToRef(matrix, result);
  6490. return result;
  6491. };
  6492. /**
  6493. * Compute the transpose of a matrix and store it in a target matrix
  6494. * @param matrix defines the matrix to transpose
  6495. * @param result defines the target matrix
  6496. */
  6497. Matrix.TransposeToRef = function (matrix, result) {
  6498. result.m[0] = matrix.m[0];
  6499. result.m[1] = matrix.m[4];
  6500. result.m[2] = matrix.m[8];
  6501. result.m[3] = matrix.m[12];
  6502. result.m[4] = matrix.m[1];
  6503. result.m[5] = matrix.m[5];
  6504. result.m[6] = matrix.m[9];
  6505. result.m[7] = matrix.m[13];
  6506. result.m[8] = matrix.m[2];
  6507. result.m[9] = matrix.m[6];
  6508. result.m[10] = matrix.m[10];
  6509. result.m[11] = matrix.m[14];
  6510. result.m[12] = matrix.m[3];
  6511. result.m[13] = matrix.m[7];
  6512. result.m[14] = matrix.m[11];
  6513. result.m[15] = matrix.m[15];
  6514. };
  6515. /**
  6516. * Computes a reflection matrix from a plane
  6517. * @param plane defines the reflection plane
  6518. * @returns a new matrix
  6519. */
  6520. Matrix.Reflection = function (plane) {
  6521. var matrix = new Matrix();
  6522. Matrix.ReflectionToRef(plane, matrix);
  6523. return matrix;
  6524. };
  6525. /**
  6526. * Computes a reflection matrix from a plane
  6527. * @param plane defines the reflection plane
  6528. * @param result defines the target matrix
  6529. */
  6530. Matrix.ReflectionToRef = function (plane, result) {
  6531. plane.normalize();
  6532. var x = plane.normal.x;
  6533. var y = plane.normal.y;
  6534. var z = plane.normal.z;
  6535. var temp = -2 * x;
  6536. var temp2 = -2 * y;
  6537. var temp3 = -2 * z;
  6538. result.m[0] = (temp * x) + 1;
  6539. result.m[1] = temp2 * x;
  6540. result.m[2] = temp3 * x;
  6541. result.m[3] = 0.0;
  6542. result.m[4] = temp * y;
  6543. result.m[5] = (temp2 * y) + 1;
  6544. result.m[6] = temp3 * y;
  6545. result.m[7] = 0.0;
  6546. result.m[8] = temp * z;
  6547. result.m[9] = temp2 * z;
  6548. result.m[10] = (temp3 * z) + 1;
  6549. result.m[11] = 0.0;
  6550. result.m[12] = temp * plane.d;
  6551. result.m[13] = temp2 * plane.d;
  6552. result.m[14] = temp3 * plane.d;
  6553. result.m[15] = 1.0;
  6554. result._markAsUpdated();
  6555. };
  6556. /**
  6557. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6558. * @param xaxis defines the value of the 1st axis
  6559. * @param yaxis defines the value of the 2nd axis
  6560. * @param zaxis defines the value of the 3rd axis
  6561. * @param result defines the target matrix
  6562. */
  6563. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6564. result.m[0] = xaxis.x;
  6565. result.m[1] = xaxis.y;
  6566. result.m[2] = xaxis.z;
  6567. result.m[3] = 0.0;
  6568. result.m[4] = yaxis.x;
  6569. result.m[5] = yaxis.y;
  6570. result.m[6] = yaxis.z;
  6571. result.m[7] = 0.0;
  6572. result.m[8] = zaxis.x;
  6573. result.m[9] = zaxis.y;
  6574. result.m[10] = zaxis.z;
  6575. result.m[11] = 0.0;
  6576. result.m[12] = 0.0;
  6577. result.m[13] = 0.0;
  6578. result.m[14] = 0.0;
  6579. result.m[15] = 1.0;
  6580. result._markAsUpdated();
  6581. };
  6582. /**
  6583. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6584. * @param quat defines the quaternion to use
  6585. * @param result defines the target matrix
  6586. */
  6587. Matrix.FromQuaternionToRef = function (quat, result) {
  6588. var xx = quat.x * quat.x;
  6589. var yy = quat.y * quat.y;
  6590. var zz = quat.z * quat.z;
  6591. var xy = quat.x * quat.y;
  6592. var zw = quat.z * quat.w;
  6593. var zx = quat.z * quat.x;
  6594. var yw = quat.y * quat.w;
  6595. var yz = quat.y * quat.z;
  6596. var xw = quat.x * quat.w;
  6597. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6598. result.m[1] = 2.0 * (xy + zw);
  6599. result.m[2] = 2.0 * (zx - yw);
  6600. result.m[3] = 0.0;
  6601. result.m[4] = 2.0 * (xy - zw);
  6602. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6603. result.m[6] = 2.0 * (yz + xw);
  6604. result.m[7] = 0.0;
  6605. result.m[8] = 2.0 * (zx + yw);
  6606. result.m[9] = 2.0 * (yz - xw);
  6607. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6608. result.m[11] = 0.0;
  6609. result.m[12] = 0.0;
  6610. result.m[13] = 0.0;
  6611. result.m[14] = 0.0;
  6612. result.m[15] = 1.0;
  6613. result._markAsUpdated();
  6614. };
  6615. Matrix._tempQuaternion = new Quaternion();
  6616. Matrix._xAxis = Vector3.Zero();
  6617. Matrix._yAxis = Vector3.Zero();
  6618. Matrix._zAxis = Vector3.Zero();
  6619. Matrix._updateFlagSeed = 0;
  6620. Matrix._identityReadOnly = Matrix.Identity();
  6621. return Matrix;
  6622. }());
  6623. BABYLON.Matrix = Matrix;
  6624. var Plane = /** @class */ (function () {
  6625. /**
  6626. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6627. */
  6628. function Plane(a, b, c, d) {
  6629. this.normal = new Vector3(a, b, c);
  6630. this.d = d;
  6631. }
  6632. /**
  6633. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6634. */
  6635. Plane.prototype.asArray = function () {
  6636. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6637. };
  6638. // Methods
  6639. /**
  6640. * Returns a new plane copied from the current Plane.
  6641. */
  6642. Plane.prototype.clone = function () {
  6643. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6644. };
  6645. /**
  6646. * Returns the string "Plane".
  6647. */
  6648. Plane.prototype.getClassName = function () {
  6649. return "Plane";
  6650. };
  6651. /**
  6652. * Returns the Plane hash code.
  6653. */
  6654. Plane.prototype.getHashCode = function () {
  6655. var hash = this.normal.getHashCode();
  6656. hash = (hash * 397) ^ (this.d || 0);
  6657. return hash;
  6658. };
  6659. /**
  6660. * Normalize the current Plane in place.
  6661. * Returns the updated Plane.
  6662. */
  6663. Plane.prototype.normalize = function () {
  6664. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6665. var magnitude = 0.0;
  6666. if (norm !== 0) {
  6667. magnitude = 1.0 / norm;
  6668. }
  6669. this.normal.x *= magnitude;
  6670. this.normal.y *= magnitude;
  6671. this.normal.z *= magnitude;
  6672. this.d *= magnitude;
  6673. return this;
  6674. };
  6675. /**
  6676. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6677. */
  6678. Plane.prototype.transform = function (transformation) {
  6679. var transposedMatrix = Matrix.Transpose(transformation);
  6680. var x = this.normal.x;
  6681. var y = this.normal.y;
  6682. var z = this.normal.z;
  6683. var d = this.d;
  6684. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6685. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6686. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6687. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6688. return new Plane(normalX, normalY, normalZ, finalD);
  6689. };
  6690. /**
  6691. * Returns the dot product (float) of the point coordinates and the plane normal.
  6692. */
  6693. Plane.prototype.dotCoordinate = function (point) {
  6694. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6695. };
  6696. /**
  6697. * Updates the current Plane from the plane defined by the three given points.
  6698. * Returns the updated Plane.
  6699. */
  6700. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6701. var x1 = point2.x - point1.x;
  6702. var y1 = point2.y - point1.y;
  6703. var z1 = point2.z - point1.z;
  6704. var x2 = point3.x - point1.x;
  6705. var y2 = point3.y - point1.y;
  6706. var z2 = point3.z - point1.z;
  6707. var yz = (y1 * z2) - (z1 * y2);
  6708. var xz = (z1 * x2) - (x1 * z2);
  6709. var xy = (x1 * y2) - (y1 * x2);
  6710. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6711. var invPyth;
  6712. if (pyth !== 0) {
  6713. invPyth = 1.0 / pyth;
  6714. }
  6715. else {
  6716. invPyth = 0.0;
  6717. }
  6718. this.normal.x = yz * invPyth;
  6719. this.normal.y = xz * invPyth;
  6720. this.normal.z = xy * invPyth;
  6721. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6722. return this;
  6723. };
  6724. /**
  6725. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6726. */
  6727. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6728. var dot = Vector3.Dot(this.normal, direction);
  6729. return (dot <= epsilon);
  6730. };
  6731. /**
  6732. * Returns the signed distance (float) from the given point to the Plane.
  6733. */
  6734. Plane.prototype.signedDistanceTo = function (point) {
  6735. return Vector3.Dot(point, this.normal) + this.d;
  6736. };
  6737. // Statics
  6738. /**
  6739. * Returns a new Plane from the given array.
  6740. */
  6741. Plane.FromArray = function (array) {
  6742. return new Plane(array[0], array[1], array[2], array[3]);
  6743. };
  6744. /**
  6745. * Returns a new Plane defined by the three given points.
  6746. */
  6747. Plane.FromPoints = function (point1, point2, point3) {
  6748. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6749. result.copyFromPoints(point1, point2, point3);
  6750. return result;
  6751. };
  6752. /**
  6753. * Returns a new Plane the normal vector to this plane at the given origin point.
  6754. * Note : the vector "normal" is updated because normalized.
  6755. */
  6756. Plane.FromPositionAndNormal = function (origin, normal) {
  6757. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6758. normal.normalize();
  6759. result.normal = normal;
  6760. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6761. return result;
  6762. };
  6763. /**
  6764. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6765. */
  6766. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6767. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6768. return Vector3.Dot(point, normal) + d;
  6769. };
  6770. return Plane;
  6771. }());
  6772. BABYLON.Plane = Plane;
  6773. var Viewport = /** @class */ (function () {
  6774. /**
  6775. * Creates a Viewport object located at (x, y) and sized (width, height).
  6776. */
  6777. function Viewport(x, y, width, height) {
  6778. this.x = x;
  6779. this.y = y;
  6780. this.width = width;
  6781. this.height = height;
  6782. }
  6783. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6784. if (renderWidthOrEngine.getRenderWidth) {
  6785. var engine = renderWidthOrEngine;
  6786. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6787. }
  6788. var renderWidth = renderWidthOrEngine;
  6789. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6790. };
  6791. /**
  6792. * Returns a new Viewport copied from the current one.
  6793. */
  6794. Viewport.prototype.clone = function () {
  6795. return new Viewport(this.x, this.y, this.width, this.height);
  6796. };
  6797. return Viewport;
  6798. }());
  6799. BABYLON.Viewport = Viewport;
  6800. var Frustum = /** @class */ (function () {
  6801. function Frustum() {
  6802. }
  6803. /**
  6804. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6805. */
  6806. Frustum.GetPlanes = function (transform) {
  6807. var frustumPlanes = [];
  6808. for (var index = 0; index < 6; index++) {
  6809. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6810. }
  6811. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6812. return frustumPlanes;
  6813. };
  6814. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6815. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6816. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6817. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6818. frustumPlane.d = transform.m[15] + transform.m[14];
  6819. frustumPlane.normalize();
  6820. };
  6821. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6822. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6823. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6824. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6825. frustumPlane.d = transform.m[15] - transform.m[14];
  6826. frustumPlane.normalize();
  6827. };
  6828. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6829. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6830. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6831. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6832. frustumPlane.d = transform.m[15] + transform.m[12];
  6833. frustumPlane.normalize();
  6834. };
  6835. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6836. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6837. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6838. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6839. frustumPlane.d = transform.m[15] - transform.m[12];
  6840. frustumPlane.normalize();
  6841. };
  6842. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6843. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6844. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6845. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6846. frustumPlane.d = transform.m[15] - transform.m[13];
  6847. frustumPlane.normalize();
  6848. };
  6849. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6850. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6851. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6852. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6853. frustumPlane.d = transform.m[15] + transform.m[13];
  6854. frustumPlane.normalize();
  6855. };
  6856. /**
  6857. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6858. */
  6859. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6860. // Near
  6861. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6862. // Far
  6863. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6864. // Left
  6865. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6866. // Right
  6867. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6868. // Top
  6869. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6870. // Bottom
  6871. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6872. };
  6873. return Frustum;
  6874. }());
  6875. BABYLON.Frustum = Frustum;
  6876. /** Defines supported spaces */
  6877. var Space;
  6878. (function (Space) {
  6879. /** Local (object) space */
  6880. Space[Space["LOCAL"] = 0] = "LOCAL";
  6881. /** World space */
  6882. Space[Space["WORLD"] = 1] = "WORLD";
  6883. /** Bone space */
  6884. Space[Space["BONE"] = 2] = "BONE";
  6885. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6886. /** Defines the 3 main axes */
  6887. var Axis = /** @class */ (function () {
  6888. function Axis() {
  6889. }
  6890. /** X axis */
  6891. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6892. /** Y axis */
  6893. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6894. /** Z axis */
  6895. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6896. return Axis;
  6897. }());
  6898. BABYLON.Axis = Axis;
  6899. ;
  6900. var BezierCurve = /** @class */ (function () {
  6901. function BezierCurve() {
  6902. }
  6903. /**
  6904. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6905. */
  6906. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6907. // Extract X (which is equal to time here)
  6908. var f0 = 1 - 3 * x2 + 3 * x1;
  6909. var f1 = 3 * x2 - 6 * x1;
  6910. var f2 = 3 * x1;
  6911. var refinedT = t;
  6912. for (var i = 0; i < 5; i++) {
  6913. var refinedT2 = refinedT * refinedT;
  6914. var refinedT3 = refinedT2 * refinedT;
  6915. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6916. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6917. refinedT -= (x - t) * slope;
  6918. refinedT = Math.min(1, Math.max(0, refinedT));
  6919. }
  6920. // Resolve cubic bezier for the given x
  6921. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6922. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6923. Math.pow(refinedT, 3);
  6924. };
  6925. return BezierCurve;
  6926. }());
  6927. BABYLON.BezierCurve = BezierCurve;
  6928. /**
  6929. * Defines potential orientation for back face culling
  6930. */
  6931. var Orientation;
  6932. (function (Orientation) {
  6933. /**
  6934. * Clockwise
  6935. */
  6936. Orientation[Orientation["CW"] = 0] = "CW";
  6937. /** Counter clockwise */
  6938. Orientation[Orientation["CCW"] = 1] = "CCW";
  6939. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6940. /**
  6941. * Defines angle representation
  6942. */
  6943. var Angle = /** @class */ (function () {
  6944. /**
  6945. * Creates an Angle object of "radians" radians (float).
  6946. */
  6947. function Angle(radians) {
  6948. this._radians = radians;
  6949. if (this._radians < 0.0)
  6950. this._radians += (2.0 * Math.PI);
  6951. }
  6952. /**
  6953. * Get value in degrees
  6954. * @returns the Angle value in degrees (float)
  6955. */
  6956. Angle.prototype.degrees = function () {
  6957. return this._radians * 180.0 / Math.PI;
  6958. };
  6959. /**
  6960. * Get value in radians
  6961. * @returns the Angle value in radians (float)
  6962. */
  6963. Angle.prototype.radians = function () {
  6964. return this._radians;
  6965. };
  6966. /**
  6967. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6968. * @param a defines first vector
  6969. * @param b defines second vector
  6970. * @returns a new Angle
  6971. */
  6972. Angle.BetweenTwoPoints = function (a, b) {
  6973. var delta = b.subtract(a);
  6974. var theta = Math.atan2(delta.y, delta.x);
  6975. return new Angle(theta);
  6976. };
  6977. /**
  6978. * Gets a new Angle object from the given float in radians
  6979. * @param radians defines the angle value in radians
  6980. * @returns a new Angle
  6981. */
  6982. Angle.FromRadians = function (radians) {
  6983. return new Angle(radians);
  6984. };
  6985. /**
  6986. * Gets a new Angle object from the given float in degrees
  6987. * @param degrees defines the angle value in degrees
  6988. * @returns a new Angle
  6989. */
  6990. Angle.FromDegrees = function (degrees) {
  6991. return new Angle(degrees * Math.PI / 180.0);
  6992. };
  6993. return Angle;
  6994. }());
  6995. BABYLON.Angle = Angle;
  6996. var Arc2 = /** @class */ (function () {
  6997. /**
  6998. * Creates an Arc object from the three given points : start, middle and end.
  6999. */
  7000. function Arc2(startPoint, midPoint, endPoint) {
  7001. this.startPoint = startPoint;
  7002. this.midPoint = midPoint;
  7003. this.endPoint = endPoint;
  7004. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7005. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7006. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7007. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7008. 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);
  7009. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7010. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7011. var a1 = this.startAngle.degrees();
  7012. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7013. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7014. // angles correction
  7015. if (a2 - a1 > +180.0)
  7016. a2 -= 360.0;
  7017. if (a2 - a1 < -180.0)
  7018. a2 += 360.0;
  7019. if (a3 - a2 > +180.0)
  7020. a3 -= 360.0;
  7021. if (a3 - a2 < -180.0)
  7022. a3 += 360.0;
  7023. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7024. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7025. }
  7026. return Arc2;
  7027. }());
  7028. BABYLON.Arc2 = Arc2;
  7029. var Path2 = /** @class */ (function () {
  7030. /**
  7031. * Creates a Path2 object from the starting 2D coordinates x and y.
  7032. */
  7033. function Path2(x, y) {
  7034. this._points = new Array();
  7035. this._length = 0.0;
  7036. this.closed = false;
  7037. this._points.push(new Vector2(x, y));
  7038. }
  7039. /**
  7040. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7041. * Returns the updated Path2.
  7042. */
  7043. Path2.prototype.addLineTo = function (x, y) {
  7044. if (this.closed) {
  7045. return this;
  7046. }
  7047. var newPoint = new Vector2(x, y);
  7048. var previousPoint = this._points[this._points.length - 1];
  7049. this._points.push(newPoint);
  7050. this._length += newPoint.subtract(previousPoint).length();
  7051. return this;
  7052. };
  7053. /**
  7054. * 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.
  7055. * Returns the updated Path2.
  7056. */
  7057. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7058. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7059. if (this.closed) {
  7060. return this;
  7061. }
  7062. var startPoint = this._points[this._points.length - 1];
  7063. var midPoint = new Vector2(midX, midY);
  7064. var endPoint = new Vector2(endX, endY);
  7065. var arc = new Arc2(startPoint, midPoint, endPoint);
  7066. var increment = arc.angle.radians() / numberOfSegments;
  7067. if (arc.orientation === Orientation.CW)
  7068. increment *= -1;
  7069. var currentAngle = arc.startAngle.radians() + increment;
  7070. for (var i = 0; i < numberOfSegments; i++) {
  7071. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7072. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7073. this.addLineTo(x, y);
  7074. currentAngle += increment;
  7075. }
  7076. return this;
  7077. };
  7078. /**
  7079. * Closes the Path2.
  7080. * Returns the Path2.
  7081. */
  7082. Path2.prototype.close = function () {
  7083. this.closed = true;
  7084. return this;
  7085. };
  7086. /**
  7087. * Returns the Path2 total length (float).
  7088. */
  7089. Path2.prototype.length = function () {
  7090. var result = this._length;
  7091. if (!this.closed) {
  7092. var lastPoint = this._points[this._points.length - 1];
  7093. var firstPoint = this._points[0];
  7094. result += (firstPoint.subtract(lastPoint).length());
  7095. }
  7096. return result;
  7097. };
  7098. /**
  7099. * Returns the Path2 internal array of points.
  7100. */
  7101. Path2.prototype.getPoints = function () {
  7102. return this._points;
  7103. };
  7104. /**
  7105. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7106. */
  7107. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7108. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7109. return Vector2.Zero();
  7110. }
  7111. var lengthPosition = normalizedLengthPosition * this.length();
  7112. var previousOffset = 0;
  7113. for (var i = 0; i < this._points.length; i++) {
  7114. var j = (i + 1) % this._points.length;
  7115. var a = this._points[i];
  7116. var b = this._points[j];
  7117. var bToA = b.subtract(a);
  7118. var nextOffset = (bToA.length() + previousOffset);
  7119. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7120. var dir = bToA.normalize();
  7121. var localOffset = lengthPosition - previousOffset;
  7122. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7123. }
  7124. previousOffset = nextOffset;
  7125. }
  7126. return Vector2.Zero();
  7127. };
  7128. /**
  7129. * Returns a new Path2 starting at the coordinates (x, y).
  7130. */
  7131. Path2.StartingAt = function (x, y) {
  7132. return new Path2(x, y);
  7133. };
  7134. return Path2;
  7135. }());
  7136. BABYLON.Path2 = Path2;
  7137. var Path3D = /** @class */ (function () {
  7138. /**
  7139. * new Path3D(path, normal, raw)
  7140. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7141. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7142. * path : an array of Vector3, the curve axis of the Path3D
  7143. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7144. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7145. */
  7146. function Path3D(path, firstNormal, raw) {
  7147. if (firstNormal === void 0) { firstNormal = null; }
  7148. this.path = path;
  7149. this._curve = new Array();
  7150. this._distances = new Array();
  7151. this._tangents = new Array();
  7152. this._normals = new Array();
  7153. this._binormals = new Array();
  7154. for (var p = 0; p < path.length; p++) {
  7155. this._curve[p] = path[p].clone(); // hard copy
  7156. }
  7157. this._raw = raw || false;
  7158. this._compute(firstNormal);
  7159. }
  7160. /**
  7161. * Returns the Path3D array of successive Vector3 designing its curve.
  7162. */
  7163. Path3D.prototype.getCurve = function () {
  7164. return this._curve;
  7165. };
  7166. /**
  7167. * Returns an array populated with tangent vectors on each Path3D curve point.
  7168. */
  7169. Path3D.prototype.getTangents = function () {
  7170. return this._tangents;
  7171. };
  7172. /**
  7173. * Returns an array populated with normal vectors on each Path3D curve point.
  7174. */
  7175. Path3D.prototype.getNormals = function () {
  7176. return this._normals;
  7177. };
  7178. /**
  7179. * Returns an array populated with binormal vectors on each Path3D curve point.
  7180. */
  7181. Path3D.prototype.getBinormals = function () {
  7182. return this._binormals;
  7183. };
  7184. /**
  7185. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7186. */
  7187. Path3D.prototype.getDistances = function () {
  7188. return this._distances;
  7189. };
  7190. /**
  7191. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7192. * Returns the same object updated.
  7193. */
  7194. Path3D.prototype.update = function (path, firstNormal) {
  7195. if (firstNormal === void 0) { firstNormal = null; }
  7196. for (var p = 0; p < path.length; p++) {
  7197. this._curve[p].x = path[p].x;
  7198. this._curve[p].y = path[p].y;
  7199. this._curve[p].z = path[p].z;
  7200. }
  7201. this._compute(firstNormal);
  7202. return this;
  7203. };
  7204. // private function compute() : computes tangents, normals and binormals
  7205. Path3D.prototype._compute = function (firstNormal) {
  7206. var l = this._curve.length;
  7207. // first and last tangents
  7208. this._tangents[0] = this._getFirstNonNullVector(0);
  7209. if (!this._raw) {
  7210. this._tangents[0].normalize();
  7211. }
  7212. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7213. if (!this._raw) {
  7214. this._tangents[l - 1].normalize();
  7215. }
  7216. // normals and binormals at first point : arbitrary vector with _normalVector()
  7217. var tg0 = this._tangents[0];
  7218. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7219. this._normals[0] = pp0;
  7220. if (!this._raw) {
  7221. this._normals[0].normalize();
  7222. }
  7223. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7224. if (!this._raw) {
  7225. this._binormals[0].normalize();
  7226. }
  7227. this._distances[0] = 0.0;
  7228. // normals and binormals : next points
  7229. var prev; // previous vector (segment)
  7230. var cur; // current vector (segment)
  7231. var curTang; // current tangent
  7232. // previous normal
  7233. var prevBinor; // previous binormal
  7234. for (var i = 1; i < l; i++) {
  7235. // tangents
  7236. prev = this._getLastNonNullVector(i);
  7237. if (i < l - 1) {
  7238. cur = this._getFirstNonNullVector(i);
  7239. this._tangents[i] = prev.add(cur);
  7240. this._tangents[i].normalize();
  7241. }
  7242. this._distances[i] = this._distances[i - 1] + prev.length();
  7243. // normals and binormals
  7244. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7245. curTang = this._tangents[i];
  7246. prevBinor = this._binormals[i - 1];
  7247. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7248. if (!this._raw) {
  7249. this._normals[i].normalize();
  7250. }
  7251. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7252. if (!this._raw) {
  7253. this._binormals[i].normalize();
  7254. }
  7255. }
  7256. };
  7257. // private function getFirstNonNullVector(index)
  7258. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7259. Path3D.prototype._getFirstNonNullVector = function (index) {
  7260. var i = 1;
  7261. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7262. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7263. i++;
  7264. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7265. }
  7266. return nNVector;
  7267. };
  7268. // private function getLastNonNullVector(index)
  7269. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7270. Path3D.prototype._getLastNonNullVector = function (index) {
  7271. var i = 1;
  7272. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7273. while (nLVector.length() === 0 && index > i + 1) {
  7274. i++;
  7275. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7276. }
  7277. return nLVector;
  7278. };
  7279. // private function normalVector(v0, vt, va) :
  7280. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7281. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7282. Path3D.prototype._normalVector = function (v0, vt, va) {
  7283. var normal0;
  7284. var tgl = vt.length();
  7285. if (tgl === 0.0) {
  7286. tgl = 1.0;
  7287. }
  7288. if (va === undefined || va === null) {
  7289. var point;
  7290. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7291. point = new Vector3(0.0, -1.0, 0.0);
  7292. }
  7293. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7294. point = new Vector3(1.0, 0.0, 0.0);
  7295. }
  7296. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7297. point = new Vector3(0.0, 0.0, 1.0);
  7298. }
  7299. else {
  7300. point = Vector3.Zero();
  7301. }
  7302. normal0 = Vector3.Cross(vt, point);
  7303. }
  7304. else {
  7305. normal0 = Vector3.Cross(vt, va);
  7306. Vector3.CrossToRef(normal0, vt, normal0);
  7307. }
  7308. normal0.normalize();
  7309. return normal0;
  7310. };
  7311. return Path3D;
  7312. }());
  7313. BABYLON.Path3D = Path3D;
  7314. var Curve3 = /** @class */ (function () {
  7315. /**
  7316. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7317. * A Curve3 is designed from a series of successive Vector3.
  7318. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7319. */
  7320. function Curve3(points) {
  7321. this._length = 0.0;
  7322. this._points = points;
  7323. this._length = this._computeLength(points);
  7324. }
  7325. /**
  7326. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7327. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7328. * @param v1 (Vector3) the control point
  7329. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7330. * @param nbPoints (integer) the wanted number of points in the curve
  7331. */
  7332. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7333. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7334. var bez = new Array();
  7335. var equation = function (t, val0, val1, val2) {
  7336. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7337. return res;
  7338. };
  7339. for (var i = 0; i <= nbPoints; i++) {
  7340. 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)));
  7341. }
  7342. return new Curve3(bez);
  7343. };
  7344. /**
  7345. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7346. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7347. * @param v1 (Vector3) the first control point
  7348. * @param v2 (Vector3) the second control point
  7349. * @param v3 (Vector3) the end point of the Cubic Bezier
  7350. * @param nbPoints (integer) the wanted number of points in the curve
  7351. */
  7352. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7353. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7354. var bez = new Array();
  7355. var equation = function (t, val0, val1, val2, val3) {
  7356. 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;
  7357. return res;
  7358. };
  7359. for (var i = 0; i <= nbPoints; i++) {
  7360. 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)));
  7361. }
  7362. return new Curve3(bez);
  7363. };
  7364. /**
  7365. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7366. * @param p1 (Vector3) the origin point of the Hermite Spline
  7367. * @param t1 (Vector3) the tangent vector at the origin point
  7368. * @param p2 (Vector3) the end point of the Hermite Spline
  7369. * @param t2 (Vector3) the tangent vector at the end point
  7370. * @param nbPoints (integer) the wanted number of points in the curve
  7371. */
  7372. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7373. var hermite = new Array();
  7374. var step = 1.0 / nbPoints;
  7375. for (var i = 0; i <= nbPoints; i++) {
  7376. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7377. }
  7378. return new Curve3(hermite);
  7379. };
  7380. /**
  7381. * Returns a Curve3 object along a CatmullRom Spline curve :
  7382. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7383. * @param nbPoints (integer) the wanted number of points between each curve control points
  7384. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7385. */
  7386. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7387. var catmullRom = new Array();
  7388. var step = 1.0 / nbPoints;
  7389. var amount = 0.0;
  7390. if (closed) {
  7391. var pointsCount = points.length;
  7392. for (var i = 0; i < pointsCount; i++) {
  7393. amount = 0;
  7394. for (var c = 0; c < nbPoints; c++) {
  7395. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7396. amount += step;
  7397. }
  7398. }
  7399. catmullRom.push(catmullRom[0]);
  7400. }
  7401. else {
  7402. var totalPoints = new Array();
  7403. totalPoints.push(points[0].clone());
  7404. Array.prototype.push.apply(totalPoints, points);
  7405. totalPoints.push(points[points.length - 1].clone());
  7406. for (var i = 0; i < totalPoints.length - 3; i++) {
  7407. amount = 0;
  7408. for (var c = 0; c < nbPoints; c++) {
  7409. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7410. amount += step;
  7411. }
  7412. }
  7413. i--;
  7414. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7415. }
  7416. return new Curve3(catmullRom);
  7417. };
  7418. /**
  7419. * Returns the Curve3 stored array of successive Vector3
  7420. */
  7421. Curve3.prototype.getPoints = function () {
  7422. return this._points;
  7423. };
  7424. /**
  7425. * Returns the computed length (float) of the curve.
  7426. */
  7427. Curve3.prototype.length = function () {
  7428. return this._length;
  7429. };
  7430. /**
  7431. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7432. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7433. * curveA and curveB keep unchanged.
  7434. */
  7435. Curve3.prototype.continue = function (curve) {
  7436. var lastPoint = this._points[this._points.length - 1];
  7437. var continuedPoints = this._points.slice();
  7438. var curvePoints = curve.getPoints();
  7439. for (var i = 1; i < curvePoints.length; i++) {
  7440. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7441. }
  7442. var continuedCurve = new Curve3(continuedPoints);
  7443. return continuedCurve;
  7444. };
  7445. Curve3.prototype._computeLength = function (path) {
  7446. var l = 0;
  7447. for (var i = 1; i < path.length; i++) {
  7448. l += (path[i].subtract(path[i - 1])).length();
  7449. }
  7450. return l;
  7451. };
  7452. return Curve3;
  7453. }());
  7454. BABYLON.Curve3 = Curve3;
  7455. // Vertex formats
  7456. var PositionNormalVertex = /** @class */ (function () {
  7457. function PositionNormalVertex(position, normal) {
  7458. if (position === void 0) { position = Vector3.Zero(); }
  7459. if (normal === void 0) { normal = Vector3.Up(); }
  7460. this.position = position;
  7461. this.normal = normal;
  7462. }
  7463. PositionNormalVertex.prototype.clone = function () {
  7464. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7465. };
  7466. return PositionNormalVertex;
  7467. }());
  7468. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7469. var PositionNormalTextureVertex = /** @class */ (function () {
  7470. function PositionNormalTextureVertex(position, normal, uv) {
  7471. if (position === void 0) { position = Vector3.Zero(); }
  7472. if (normal === void 0) { normal = Vector3.Up(); }
  7473. if (uv === void 0) { uv = Vector2.Zero(); }
  7474. this.position = position;
  7475. this.normal = normal;
  7476. this.uv = uv;
  7477. }
  7478. PositionNormalTextureVertex.prototype.clone = function () {
  7479. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7480. };
  7481. return PositionNormalTextureVertex;
  7482. }());
  7483. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7484. // Temporary pre-allocated objects for engine internal use
  7485. // usage in any internal function :
  7486. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7487. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7488. var Tmp = /** @class */ (function () {
  7489. function Tmp() {
  7490. }
  7491. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7492. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7493. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7494. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7495. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7496. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7497. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7498. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7499. Matrix.Zero(), Matrix.Zero(),
  7500. Matrix.Zero(), Matrix.Zero(),
  7501. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7502. return Tmp;
  7503. }());
  7504. BABYLON.Tmp = Tmp;
  7505. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7506. var MathTmp = /** @class */ (function () {
  7507. function MathTmp() {
  7508. }
  7509. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7510. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7511. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7512. return MathTmp;
  7513. }());
  7514. })(BABYLON || (BABYLON = {}));
  7515. //# sourceMappingURL=babylon.math.js.map
  7516. var BABYLON;
  7517. (function (BABYLON) {
  7518. var Scalar = /** @class */ (function () {
  7519. function Scalar() {
  7520. }
  7521. /**
  7522. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7523. */
  7524. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7525. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7526. var num = a - b;
  7527. return -epsilon <= num && num <= epsilon;
  7528. };
  7529. /**
  7530. * Returns a string : the upper case translation of the number i to hexadecimal.
  7531. */
  7532. Scalar.ToHex = function (i) {
  7533. var str = i.toString(16);
  7534. if (i <= 15) {
  7535. return ("0" + str).toUpperCase();
  7536. }
  7537. return str.toUpperCase();
  7538. };
  7539. /**
  7540. * Returns -1 if value is negative and +1 is value is positive.
  7541. * Returns the value itself if it's equal to zero.
  7542. */
  7543. Scalar.Sign = function (value) {
  7544. value = +value; // convert to a number
  7545. if (value === 0 || isNaN(value))
  7546. return value;
  7547. return value > 0 ? 1 : -1;
  7548. };
  7549. /**
  7550. * Returns the value itself if it's between min and max.
  7551. * Returns min if the value is lower than min.
  7552. * Returns max if the value is greater than max.
  7553. */
  7554. Scalar.Clamp = function (value, min, max) {
  7555. if (min === void 0) { min = 0; }
  7556. if (max === void 0) { max = 1; }
  7557. return Math.min(max, Math.max(min, value));
  7558. };
  7559. /**
  7560. * Returns the log2 of value.
  7561. */
  7562. Scalar.Log2 = function (value) {
  7563. return Math.log(value) * Math.LOG2E;
  7564. };
  7565. /**
  7566. * Loops the value, so that it is never larger than length and never smaller than 0.
  7567. *
  7568. * This is similar to the modulo operator but it works with floating point numbers.
  7569. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7570. * With t = 5 and length = 2.5, the result would be 0.0.
  7571. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7572. */
  7573. Scalar.Repeat = function (value, length) {
  7574. return value - Math.floor(value / length) * length;
  7575. };
  7576. /**
  7577. * Normalize the value between 0.0 and 1.0 using min and max values
  7578. */
  7579. Scalar.Normalize = function (value, min, max) {
  7580. return (value - min) / (max - min);
  7581. };
  7582. /**
  7583. * Denormalize the value from 0.0 and 1.0 using min and max values
  7584. */
  7585. Scalar.Denormalize = function (normalized, min, max) {
  7586. return (normalized * (max - min) + min);
  7587. };
  7588. /**
  7589. * Calculates the shortest difference between two given angles given in degrees.
  7590. */
  7591. Scalar.DeltaAngle = function (current, target) {
  7592. var num = Scalar.Repeat(target - current, 360.0);
  7593. if (num > 180.0) {
  7594. num -= 360.0;
  7595. }
  7596. return num;
  7597. };
  7598. /**
  7599. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7600. *
  7601. * The returned value will move back and forth between 0 and length
  7602. */
  7603. Scalar.PingPong = function (tx, length) {
  7604. var t = Scalar.Repeat(tx, length * 2.0);
  7605. return length - Math.abs(t - length);
  7606. };
  7607. /**
  7608. * Interpolates between min and max with smoothing at the limits.
  7609. *
  7610. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7611. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7612. */
  7613. Scalar.SmoothStep = function (from, to, tx) {
  7614. var t = Scalar.Clamp(tx);
  7615. t = -2.0 * t * t * t + 3.0 * t * t;
  7616. return to * t + from * (1.0 - t);
  7617. };
  7618. /**
  7619. * Moves a value current towards target.
  7620. *
  7621. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7622. * Negative values of maxDelta pushes the value away from target.
  7623. */
  7624. Scalar.MoveTowards = function (current, target, maxDelta) {
  7625. var result = 0;
  7626. if (Math.abs(target - current) <= maxDelta) {
  7627. result = target;
  7628. }
  7629. else {
  7630. result = current + Scalar.Sign(target - current) * maxDelta;
  7631. }
  7632. return result;
  7633. };
  7634. /**
  7635. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7636. *
  7637. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7638. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7639. */
  7640. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7641. var num = Scalar.DeltaAngle(current, target);
  7642. var result = 0;
  7643. if (-maxDelta < num && num < maxDelta) {
  7644. result = target;
  7645. }
  7646. else {
  7647. target = current + num;
  7648. result = Scalar.MoveTowards(current, target, maxDelta);
  7649. }
  7650. return result;
  7651. };
  7652. /**
  7653. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7654. */
  7655. Scalar.Lerp = function (start, end, amount) {
  7656. return start + ((end - start) * amount);
  7657. };
  7658. /**
  7659. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7660. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7661. */
  7662. Scalar.LerpAngle = function (start, end, amount) {
  7663. var num = Scalar.Repeat(end - start, 360.0);
  7664. if (num > 180.0) {
  7665. num -= 360.0;
  7666. }
  7667. return start + num * Scalar.Clamp(amount);
  7668. };
  7669. /**
  7670. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7671. */
  7672. Scalar.InverseLerp = function (a, b, value) {
  7673. var result = 0;
  7674. if (a != b) {
  7675. result = Scalar.Clamp((value - a) / (b - a));
  7676. }
  7677. else {
  7678. result = 0.0;
  7679. }
  7680. return result;
  7681. };
  7682. /**
  7683. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7684. */
  7685. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7686. var squared = amount * amount;
  7687. var cubed = amount * squared;
  7688. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7689. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7690. var part3 = (cubed - (2.0 * squared)) + amount;
  7691. var part4 = cubed - squared;
  7692. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7693. };
  7694. /**
  7695. * Returns a random float number between and min and max values
  7696. */
  7697. Scalar.RandomRange = function (min, max) {
  7698. if (min === max)
  7699. return min;
  7700. return ((Math.random() * (max - min)) + min);
  7701. };
  7702. /**
  7703. * This function returns percentage of a number in a given range.
  7704. *
  7705. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7706. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7707. */
  7708. Scalar.RangeToPercent = function (number, min, max) {
  7709. return ((number - min) / (max - min));
  7710. };
  7711. /**
  7712. * This function returns number that corresponds to the percentage in a given range.
  7713. *
  7714. * PercentToRange(0.34,0,100) will return 34.
  7715. */
  7716. Scalar.PercentToRange = function (percent, min, max) {
  7717. return ((max - min) * percent + min);
  7718. };
  7719. /**
  7720. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7721. * @param angle The angle to normalize in radian.
  7722. * @return The converted angle.
  7723. */
  7724. Scalar.NormalizeRadians = function (angle) {
  7725. // More precise but slower version kept for reference.
  7726. // angle = angle % Tools.TwoPi;
  7727. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7728. //if (angle > Math.PI) {
  7729. // angle -= Tools.TwoPi;
  7730. //}
  7731. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7732. return angle;
  7733. };
  7734. /**
  7735. * Two pi constants convenient for computation.
  7736. */
  7737. Scalar.TwoPi = Math.PI * 2;
  7738. return Scalar;
  7739. }());
  7740. BABYLON.Scalar = Scalar;
  7741. })(BABYLON || (BABYLON = {}));
  7742. //# sourceMappingURL=babylon.math.scalar.js.map
  7743. //# sourceMappingURL=babylon.mixins.js.map
  7744. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7745. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7746. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7747. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7748. //# sourceMappingURL=babylon.webgl2.js.map
  7749. var BABYLON;
  7750. (function (BABYLON) {
  7751. var __decoratorInitialStore = {};
  7752. var __mergedStore = {};
  7753. var _copySource = function (creationFunction, source, instanciate) {
  7754. var destination = creationFunction();
  7755. // Tags
  7756. if (BABYLON.Tags) {
  7757. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7758. }
  7759. var classStore = getMergedStore(destination);
  7760. // Properties
  7761. for (var property in classStore) {
  7762. var propertyDescriptor = classStore[property];
  7763. var sourceProperty = source[property];
  7764. var propertyType = propertyDescriptor.type;
  7765. if (sourceProperty !== undefined && sourceProperty !== null) {
  7766. switch (propertyType) {
  7767. case 0: // Value
  7768. case 6: // Mesh reference
  7769. case 11: // Camera reference
  7770. destination[property] = sourceProperty;
  7771. break;
  7772. case 1: // Texture
  7773. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7774. break;
  7775. case 2: // Color3
  7776. case 3: // FresnelParameters
  7777. case 4: // Vector2
  7778. case 5: // Vector3
  7779. case 7: // Color Curves
  7780. case 10: // Quaternion
  7781. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7782. break;
  7783. }
  7784. }
  7785. }
  7786. return destination;
  7787. };
  7788. function getDirectStore(target) {
  7789. var classKey = target.getClassName();
  7790. if (!__decoratorInitialStore[classKey]) {
  7791. __decoratorInitialStore[classKey] = {};
  7792. }
  7793. return __decoratorInitialStore[classKey];
  7794. }
  7795. /**
  7796. * Return the list of properties flagged as serializable
  7797. * @param target: host object
  7798. */
  7799. function getMergedStore(target) {
  7800. var classKey = target.getClassName();
  7801. if (__mergedStore[classKey]) {
  7802. return __mergedStore[classKey];
  7803. }
  7804. __mergedStore[classKey] = {};
  7805. var store = __mergedStore[classKey];
  7806. var currentTarget = target;
  7807. var currentKey = classKey;
  7808. while (currentKey) {
  7809. var initialStore = __decoratorInitialStore[currentKey];
  7810. for (var property in initialStore) {
  7811. store[property] = initialStore[property];
  7812. }
  7813. var parent_1 = void 0;
  7814. var done = false;
  7815. do {
  7816. parent_1 = Object.getPrototypeOf(currentTarget);
  7817. if (!parent_1.getClassName) {
  7818. done = true;
  7819. break;
  7820. }
  7821. if (parent_1.getClassName() !== currentKey) {
  7822. break;
  7823. }
  7824. currentTarget = parent_1;
  7825. } while (parent_1);
  7826. if (done) {
  7827. break;
  7828. }
  7829. currentKey = parent_1.getClassName();
  7830. currentTarget = parent_1;
  7831. }
  7832. return store;
  7833. }
  7834. function generateSerializableMember(type, sourceName) {
  7835. return function (target, propertyKey) {
  7836. var classStore = getDirectStore(target);
  7837. if (!classStore[propertyKey]) {
  7838. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7839. }
  7840. };
  7841. }
  7842. function generateExpandMember(setCallback, targetKey) {
  7843. if (targetKey === void 0) { targetKey = null; }
  7844. return function (target, propertyKey) {
  7845. var key = targetKey || ("_" + propertyKey);
  7846. Object.defineProperty(target, propertyKey, {
  7847. get: function () {
  7848. return this[key];
  7849. },
  7850. set: function (value) {
  7851. if (this[key] === value) {
  7852. return;
  7853. }
  7854. this[key] = value;
  7855. target[setCallback].apply(this);
  7856. },
  7857. enumerable: true,
  7858. configurable: true
  7859. });
  7860. };
  7861. }
  7862. function expandToProperty(callback, targetKey) {
  7863. if (targetKey === void 0) { targetKey = null; }
  7864. return generateExpandMember(callback, targetKey);
  7865. }
  7866. BABYLON.expandToProperty = expandToProperty;
  7867. function serialize(sourceName) {
  7868. return generateSerializableMember(0, sourceName); // value member
  7869. }
  7870. BABYLON.serialize = serialize;
  7871. function serializeAsTexture(sourceName) {
  7872. return generateSerializableMember(1, sourceName); // texture member
  7873. }
  7874. BABYLON.serializeAsTexture = serializeAsTexture;
  7875. function serializeAsColor3(sourceName) {
  7876. return generateSerializableMember(2, sourceName); // color3 member
  7877. }
  7878. BABYLON.serializeAsColor3 = serializeAsColor3;
  7879. function serializeAsFresnelParameters(sourceName) {
  7880. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7881. }
  7882. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7883. function serializeAsVector2(sourceName) {
  7884. return generateSerializableMember(4, sourceName); // vector2 member
  7885. }
  7886. BABYLON.serializeAsVector2 = serializeAsVector2;
  7887. function serializeAsVector3(sourceName) {
  7888. return generateSerializableMember(5, sourceName); // vector3 member
  7889. }
  7890. BABYLON.serializeAsVector3 = serializeAsVector3;
  7891. function serializeAsMeshReference(sourceName) {
  7892. return generateSerializableMember(6, sourceName); // mesh reference member
  7893. }
  7894. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7895. function serializeAsColorCurves(sourceName) {
  7896. return generateSerializableMember(7, sourceName); // color curves
  7897. }
  7898. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7899. function serializeAsColor4(sourceName) {
  7900. return generateSerializableMember(8, sourceName); // color 4
  7901. }
  7902. BABYLON.serializeAsColor4 = serializeAsColor4;
  7903. function serializeAsImageProcessingConfiguration(sourceName) {
  7904. return generateSerializableMember(9, sourceName); // image processing
  7905. }
  7906. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7907. function serializeAsQuaternion(sourceName) {
  7908. return generateSerializableMember(10, sourceName); // quaternion member
  7909. }
  7910. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7911. /**
  7912. * Decorator used to define property that can be serialized as reference to a camera
  7913. * @param sourceName defines the name of the property to decorate
  7914. */
  7915. function serializeAsCameraReference(sourceName) {
  7916. return generateSerializableMember(11, sourceName); // camera reference member
  7917. }
  7918. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7919. var SerializationHelper = /** @class */ (function () {
  7920. function SerializationHelper() {
  7921. }
  7922. SerializationHelper.Serialize = function (entity, serializationObject) {
  7923. if (!serializationObject) {
  7924. serializationObject = {};
  7925. }
  7926. // Tags
  7927. if (BABYLON.Tags) {
  7928. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7929. }
  7930. var serializedProperties = getMergedStore(entity);
  7931. // Properties
  7932. for (var property in serializedProperties) {
  7933. var propertyDescriptor = serializedProperties[property];
  7934. var targetPropertyName = propertyDescriptor.sourceName || property;
  7935. var propertyType = propertyDescriptor.type;
  7936. var sourceProperty = entity[property];
  7937. if (sourceProperty !== undefined && sourceProperty !== null) {
  7938. switch (propertyType) {
  7939. case 0: // Value
  7940. serializationObject[targetPropertyName] = sourceProperty;
  7941. break;
  7942. case 1: // Texture
  7943. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7944. break;
  7945. case 2: // Color3
  7946. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7947. break;
  7948. case 3: // FresnelParameters
  7949. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7950. break;
  7951. case 4: // Vector2
  7952. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7953. break;
  7954. case 5: // Vector3
  7955. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7956. break;
  7957. case 6: // Mesh reference
  7958. serializationObject[targetPropertyName] = sourceProperty.id;
  7959. break;
  7960. case 7: // Color Curves
  7961. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7962. break;
  7963. case 8: // Color 4
  7964. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7965. break;
  7966. case 9: // Image Processing
  7967. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7968. break;
  7969. case 10: // Quaternion
  7970. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7971. break;
  7972. case 11: // Camera reference
  7973. serializationObject[targetPropertyName] = sourceProperty.id;
  7974. break;
  7975. }
  7976. }
  7977. }
  7978. return serializationObject;
  7979. };
  7980. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7981. if (rootUrl === void 0) { rootUrl = null; }
  7982. var destination = creationFunction();
  7983. if (!rootUrl) {
  7984. rootUrl = "";
  7985. }
  7986. // Tags
  7987. if (BABYLON.Tags) {
  7988. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7989. }
  7990. var classStore = getMergedStore(destination);
  7991. // Properties
  7992. for (var property in classStore) {
  7993. var propertyDescriptor = classStore[property];
  7994. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7995. var propertyType = propertyDescriptor.type;
  7996. if (sourceProperty !== undefined && sourceProperty !== null) {
  7997. var dest = destination;
  7998. switch (propertyType) {
  7999. case 0: // Value
  8000. dest[property] = sourceProperty;
  8001. break;
  8002. case 1: // Texture
  8003. if (scene) {
  8004. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8005. }
  8006. break;
  8007. case 2: // Color3
  8008. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8009. break;
  8010. case 3: // FresnelParameters
  8011. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8012. break;
  8013. case 4: // Vector2
  8014. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8015. break;
  8016. case 5: // Vector3
  8017. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8018. break;
  8019. case 6: // Mesh reference
  8020. if (scene) {
  8021. dest[property] = scene.getLastMeshByID(sourceProperty);
  8022. }
  8023. break;
  8024. case 7: // Color Curves
  8025. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8026. break;
  8027. case 8: // Color 4
  8028. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8029. break;
  8030. case 9: // Image Processing
  8031. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8032. break;
  8033. case 10: // Quaternion
  8034. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8035. break;
  8036. case 11: // Camera reference
  8037. if (scene) {
  8038. dest[property] = scene.getCameraByID(sourceProperty);
  8039. }
  8040. break;
  8041. }
  8042. }
  8043. }
  8044. return destination;
  8045. };
  8046. SerializationHelper.Clone = function (creationFunction, source) {
  8047. return _copySource(creationFunction, source, false);
  8048. };
  8049. SerializationHelper.Instanciate = function (creationFunction, source) {
  8050. return _copySource(creationFunction, source, true);
  8051. };
  8052. return SerializationHelper;
  8053. }());
  8054. BABYLON.SerializationHelper = SerializationHelper;
  8055. })(BABYLON || (BABYLON = {}));
  8056. //# sourceMappingURL=babylon.decorators.js.map
  8057. var BABYLON;
  8058. (function (BABYLON) {
  8059. /**
  8060. * Wrapper class for promise with external resolve and reject.
  8061. */
  8062. var Deferred = /** @class */ (function () {
  8063. /**
  8064. * Constructor for this deferred object.
  8065. */
  8066. function Deferred() {
  8067. var _this = this;
  8068. this.promise = new Promise(function (resolve, reject) {
  8069. _this._resolve = resolve;
  8070. _this._reject = reject;
  8071. });
  8072. }
  8073. Object.defineProperty(Deferred.prototype, "resolve", {
  8074. /**
  8075. * The resolve method of the promise associated with this deferred object.
  8076. */
  8077. get: function () {
  8078. return this._resolve;
  8079. },
  8080. enumerable: true,
  8081. configurable: true
  8082. });
  8083. Object.defineProperty(Deferred.prototype, "reject", {
  8084. /**
  8085. * The reject method of the promise associated with this deferred object.
  8086. */
  8087. get: function () {
  8088. return this._reject;
  8089. },
  8090. enumerable: true,
  8091. configurable: true
  8092. });
  8093. return Deferred;
  8094. }());
  8095. BABYLON.Deferred = Deferred;
  8096. })(BABYLON || (BABYLON = {}));
  8097. //# sourceMappingURL=babylon.deferred.js.map
  8098. var BABYLON;
  8099. (function (BABYLON) {
  8100. /**
  8101. * A class serves as a medium between the observable and its observers
  8102. */
  8103. var EventState = /** @class */ (function () {
  8104. /**
  8105. * Create a new EventState
  8106. * @param mask defines the mask associated with this state
  8107. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8108. * @param target defines the original target of the state
  8109. * @param currentTarget defines the current target of the state
  8110. */
  8111. function EventState(mask, skipNextObservers, target, currentTarget) {
  8112. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8113. this.initalize(mask, skipNextObservers, target, currentTarget);
  8114. }
  8115. /**
  8116. * Initialize the current event state
  8117. * @param mask defines the mask associated with this state
  8118. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8119. * @param target defines the original target of the state
  8120. * @param currentTarget defines the current target of the state
  8121. * @returns the current event state
  8122. */
  8123. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8124. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8125. this.mask = mask;
  8126. this.skipNextObservers = skipNextObservers;
  8127. this.target = target;
  8128. this.currentTarget = currentTarget;
  8129. return this;
  8130. };
  8131. return EventState;
  8132. }());
  8133. BABYLON.EventState = EventState;
  8134. /**
  8135. * Represent an Observer registered to a given Observable object.
  8136. */
  8137. var Observer = /** @class */ (function () {
  8138. /**
  8139. * Creates a new observer
  8140. * @param callback defines the callback to call when the observer is notified
  8141. * @param mask defines the mask of the observer (used to filter notifications)
  8142. * @param scope defines the current scope used to restore the JS context
  8143. */
  8144. function Observer(
  8145. /**
  8146. * Defines the callback to call when the observer is notified
  8147. */
  8148. callback,
  8149. /**
  8150. * Defines the mask of the observer (used to filter notifications)
  8151. */
  8152. mask,
  8153. /**
  8154. * Defines the current scope used to restore the JS context
  8155. */
  8156. scope) {
  8157. if (scope === void 0) { scope = null; }
  8158. this.callback = callback;
  8159. this.mask = mask;
  8160. this.scope = scope;
  8161. /** @hidden */
  8162. this._willBeUnregistered = false;
  8163. /**
  8164. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8165. */
  8166. this.unregisterOnNextCall = false;
  8167. }
  8168. return Observer;
  8169. }());
  8170. BABYLON.Observer = Observer;
  8171. /**
  8172. * Represent a list of observers registered to multiple Observables object.
  8173. */
  8174. var MultiObserver = /** @class */ (function () {
  8175. function MultiObserver() {
  8176. }
  8177. /**
  8178. * Release associated resources
  8179. */
  8180. MultiObserver.prototype.dispose = function () {
  8181. if (this._observers && this._observables) {
  8182. for (var index = 0; index < this._observers.length; index++) {
  8183. this._observables[index].remove(this._observers[index]);
  8184. }
  8185. }
  8186. this._observers = null;
  8187. this._observables = null;
  8188. };
  8189. /**
  8190. * Raise a callback when one of the observable will notify
  8191. * @param observables defines a list of observables to watch
  8192. * @param callback defines the callback to call on notification
  8193. * @param mask defines the mask used to filter notifications
  8194. * @param scope defines the current scope used to restore the JS context
  8195. * @returns the new MultiObserver
  8196. */
  8197. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8198. if (mask === void 0) { mask = -1; }
  8199. if (scope === void 0) { scope = null; }
  8200. var result = new MultiObserver();
  8201. result._observers = new Array();
  8202. result._observables = observables;
  8203. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8204. var observable = observables_1[_i];
  8205. var observer = observable.add(callback, mask, false, scope);
  8206. if (observer) {
  8207. result._observers.push(observer);
  8208. }
  8209. }
  8210. return result;
  8211. };
  8212. return MultiObserver;
  8213. }());
  8214. BABYLON.MultiObserver = MultiObserver;
  8215. /**
  8216. * The Observable class is a simple implementation of the Observable pattern.
  8217. *
  8218. * 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.
  8219. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8220. * 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).
  8221. * 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.
  8222. */
  8223. var Observable = /** @class */ (function () {
  8224. /**
  8225. * Creates a new observable
  8226. * @param onObserverAdded defines a callback to call when a new observer is added
  8227. */
  8228. function Observable(onObserverAdded) {
  8229. this._observers = new Array();
  8230. this._eventState = new EventState(0);
  8231. if (onObserverAdded) {
  8232. this._onObserverAdded = onObserverAdded;
  8233. }
  8234. }
  8235. /**
  8236. * Create a new Observer with the specified callback
  8237. * @param callback the callback that will be executed for that Observer
  8238. * @param mask the mask used to filter observers
  8239. * @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.
  8240. * @param scope optional scope for the callback to be called from
  8241. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8242. * @returns the new observer created for the callback
  8243. */
  8244. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8245. if (mask === void 0) { mask = -1; }
  8246. if (insertFirst === void 0) { insertFirst = false; }
  8247. if (scope === void 0) { scope = null; }
  8248. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8249. if (!callback) {
  8250. return null;
  8251. }
  8252. var observer = new Observer(callback, mask, scope);
  8253. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8254. if (insertFirst) {
  8255. this._observers.unshift(observer);
  8256. }
  8257. else {
  8258. this._observers.push(observer);
  8259. }
  8260. if (this._onObserverAdded) {
  8261. this._onObserverAdded(observer);
  8262. }
  8263. return observer;
  8264. };
  8265. /**
  8266. * Create a new Observer with the specified callback and unregisters after the next notification
  8267. * @param callback the callback that will be executed for that Observer
  8268. * @returns the new observer created for the callback
  8269. */
  8270. Observable.prototype.addOnce = function (callback) {
  8271. return this.add(callback, undefined, undefined, undefined, true);
  8272. };
  8273. /**
  8274. * Remove an Observer from the Observable object
  8275. * @param observer the instance of the Observer to remove
  8276. * @returns false if it doesn't belong to this Observable
  8277. */
  8278. Observable.prototype.remove = function (observer) {
  8279. if (!observer) {
  8280. return false;
  8281. }
  8282. var index = this._observers.indexOf(observer);
  8283. if (index !== -1) {
  8284. this._deferUnregister(observer);
  8285. return true;
  8286. }
  8287. return false;
  8288. };
  8289. /**
  8290. * Remove a callback from the Observable object
  8291. * @param callback the callback to remove
  8292. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8293. * @returns false if it doesn't belong to this Observable
  8294. */
  8295. Observable.prototype.removeCallback = function (callback, scope) {
  8296. for (var index = 0; index < this._observers.length; index++) {
  8297. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8298. this._deferUnregister(this._observers[index]);
  8299. return true;
  8300. }
  8301. }
  8302. return false;
  8303. };
  8304. Observable.prototype._deferUnregister = function (observer) {
  8305. var _this = this;
  8306. observer.unregisterOnNextCall = false;
  8307. observer._willBeUnregistered = true;
  8308. BABYLON.Tools.SetImmediate(function () {
  8309. _this._remove(observer);
  8310. });
  8311. };
  8312. // This should only be called when not iterating over _observers to avoid callback skipping.
  8313. // Removes an observer from the _observer Array.
  8314. Observable.prototype._remove = function (observer) {
  8315. if (!observer) {
  8316. return false;
  8317. }
  8318. var index = this._observers.indexOf(observer);
  8319. if (index !== -1) {
  8320. this._observers.splice(index, 1);
  8321. return true;
  8322. }
  8323. return false;
  8324. };
  8325. /**
  8326. * Notify all Observers by calling their respective callback with the given data
  8327. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8328. * @param eventData defines the data to send to all observers
  8329. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8330. * @param target defines the original target of the state
  8331. * @param currentTarget defines the current target of the state
  8332. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8333. */
  8334. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8335. if (mask === void 0) { mask = -1; }
  8336. if (!this._observers.length) {
  8337. return true;
  8338. }
  8339. var state = this._eventState;
  8340. state.mask = mask;
  8341. state.target = target;
  8342. state.currentTarget = currentTarget;
  8343. state.skipNextObservers = false;
  8344. state.lastReturnValue = eventData;
  8345. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8346. var obs = _a[_i];
  8347. if (obs._willBeUnregistered) {
  8348. continue;
  8349. }
  8350. if (obs.mask & mask) {
  8351. if (obs.scope) {
  8352. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8353. }
  8354. else {
  8355. state.lastReturnValue = obs.callback(eventData, state);
  8356. }
  8357. if (obs.unregisterOnNextCall) {
  8358. this._deferUnregister(obs);
  8359. }
  8360. }
  8361. if (state.skipNextObservers) {
  8362. return false;
  8363. }
  8364. }
  8365. return true;
  8366. };
  8367. /**
  8368. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8369. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8370. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8371. * and it is crucial that all callbacks will be executed.
  8372. * The order of the callbacks is kept, callbacks are not executed parallel.
  8373. *
  8374. * @param eventData The data to be sent to each callback
  8375. * @param mask is used to filter observers defaults to -1
  8376. * @param target defines the callback target (see EventState)
  8377. * @param currentTarget defines he current object in the bubbling phase
  8378. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8379. */
  8380. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8381. var _this = this;
  8382. if (mask === void 0) { mask = -1; }
  8383. // create an empty promise
  8384. var p = Promise.resolve(eventData);
  8385. // no observers? return this promise.
  8386. if (!this._observers.length) {
  8387. return p;
  8388. }
  8389. var state = this._eventState;
  8390. state.mask = mask;
  8391. state.target = target;
  8392. state.currentTarget = currentTarget;
  8393. state.skipNextObservers = false;
  8394. // execute one callback after another (not using Promise.all, the order is important)
  8395. this._observers.forEach(function (obs) {
  8396. if (state.skipNextObservers) {
  8397. return;
  8398. }
  8399. if (obs._willBeUnregistered) {
  8400. return;
  8401. }
  8402. if (obs.mask & mask) {
  8403. if (obs.scope) {
  8404. p = p.then(function (lastReturnedValue) {
  8405. state.lastReturnValue = lastReturnedValue;
  8406. return obs.callback.apply(obs.scope, [eventData, state]);
  8407. });
  8408. }
  8409. else {
  8410. p = p.then(function (lastReturnedValue) {
  8411. state.lastReturnValue = lastReturnedValue;
  8412. return obs.callback(eventData, state);
  8413. });
  8414. }
  8415. if (obs.unregisterOnNextCall) {
  8416. _this._deferUnregister(obs);
  8417. }
  8418. }
  8419. });
  8420. // return the eventData
  8421. return p.then(function () { return eventData; });
  8422. };
  8423. /**
  8424. * Notify a specific observer
  8425. * @param observer defines the observer to notify
  8426. * @param eventData defines the data to be sent to each callback
  8427. * @param mask is used to filter observers defaults to -1
  8428. */
  8429. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8430. if (mask === void 0) { mask = -1; }
  8431. var state = this._eventState;
  8432. state.mask = mask;
  8433. state.skipNextObservers = false;
  8434. observer.callback(eventData, state);
  8435. };
  8436. /**
  8437. * Gets a boolean indicating if the observable has at least one observer
  8438. * @returns true is the Observable has at least one Observer registered
  8439. */
  8440. Observable.prototype.hasObservers = function () {
  8441. return this._observers.length > 0;
  8442. };
  8443. /**
  8444. * Clear the list of observers
  8445. */
  8446. Observable.prototype.clear = function () {
  8447. this._observers = new Array();
  8448. this._onObserverAdded = null;
  8449. };
  8450. /**
  8451. * Clone the current observable
  8452. * @returns a new observable
  8453. */
  8454. Observable.prototype.clone = function () {
  8455. var result = new Observable();
  8456. result._observers = this._observers.slice(0);
  8457. return result;
  8458. };
  8459. /**
  8460. * Does this observable handles observer registered with a given mask
  8461. * @param mask defines the mask to be tested
  8462. * @return whether or not one observer registered with the given mask is handeled
  8463. **/
  8464. Observable.prototype.hasSpecificMask = function (mask) {
  8465. if (mask === void 0) { mask = -1; }
  8466. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8467. var obs = _a[_i];
  8468. if (obs.mask & mask || obs.mask === mask) {
  8469. return true;
  8470. }
  8471. }
  8472. return false;
  8473. };
  8474. return Observable;
  8475. }());
  8476. BABYLON.Observable = Observable;
  8477. })(BABYLON || (BABYLON = {}));
  8478. //# sourceMappingURL=babylon.observable.js.map
  8479. var BABYLON;
  8480. (function (BABYLON) {
  8481. var SmartArray = /** @class */ (function () {
  8482. function SmartArray(capacity) {
  8483. this.length = 0;
  8484. this.data = new Array(capacity);
  8485. this._id = SmartArray._GlobalId++;
  8486. }
  8487. SmartArray.prototype.push = function (value) {
  8488. this.data[this.length++] = value;
  8489. if (this.length > this.data.length) {
  8490. this.data.length *= 2;
  8491. }
  8492. };
  8493. SmartArray.prototype.forEach = function (func) {
  8494. for (var index = 0; index < this.length; index++) {
  8495. func(this.data[index]);
  8496. }
  8497. };
  8498. SmartArray.prototype.sort = function (compareFn) {
  8499. this.data.sort(compareFn);
  8500. };
  8501. SmartArray.prototype.reset = function () {
  8502. this.length = 0;
  8503. };
  8504. SmartArray.prototype.dispose = function () {
  8505. this.reset();
  8506. if (this.data) {
  8507. this.data.length = 0;
  8508. this.data = [];
  8509. }
  8510. };
  8511. SmartArray.prototype.concat = function (array) {
  8512. if (array.length === 0) {
  8513. return;
  8514. }
  8515. if (this.length + array.length > this.data.length) {
  8516. this.data.length = (this.length + array.length) * 2;
  8517. }
  8518. for (var index = 0; index < array.length; index++) {
  8519. this.data[this.length++] = (array.data || array)[index];
  8520. }
  8521. };
  8522. SmartArray.prototype.indexOf = function (value) {
  8523. var position = this.data.indexOf(value);
  8524. if (position >= this.length) {
  8525. return -1;
  8526. }
  8527. return position;
  8528. };
  8529. SmartArray.prototype.contains = function (value) {
  8530. return this.data.indexOf(value) !== -1;
  8531. };
  8532. // Statics
  8533. SmartArray._GlobalId = 0;
  8534. return SmartArray;
  8535. }());
  8536. BABYLON.SmartArray = SmartArray;
  8537. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8538. __extends(SmartArrayNoDuplicate, _super);
  8539. function SmartArrayNoDuplicate() {
  8540. var _this = _super !== null && _super.apply(this, arguments) || this;
  8541. _this._duplicateId = 0;
  8542. return _this;
  8543. }
  8544. SmartArrayNoDuplicate.prototype.push = function (value) {
  8545. _super.prototype.push.call(this, value);
  8546. if (!value.__smartArrayFlags) {
  8547. value.__smartArrayFlags = {};
  8548. }
  8549. value.__smartArrayFlags[this._id] = this._duplicateId;
  8550. };
  8551. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8552. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8553. return false;
  8554. }
  8555. this.push(value);
  8556. return true;
  8557. };
  8558. SmartArrayNoDuplicate.prototype.reset = function () {
  8559. _super.prototype.reset.call(this);
  8560. this._duplicateId++;
  8561. };
  8562. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8563. if (array.length === 0) {
  8564. return;
  8565. }
  8566. if (this.length + array.length > this.data.length) {
  8567. this.data.length = (this.length + array.length) * 2;
  8568. }
  8569. for (var index = 0; index < array.length; index++) {
  8570. var item = (array.data || array)[index];
  8571. this.pushNoDuplicate(item);
  8572. }
  8573. };
  8574. return SmartArrayNoDuplicate;
  8575. }(SmartArray));
  8576. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8577. })(BABYLON || (BABYLON = {}));
  8578. //# sourceMappingURL=babylon.smartArray.js.map
  8579. var BABYLON;
  8580. (function (BABYLON) {
  8581. /** Class used to store color gradient */
  8582. var ColorGradient = /** @class */ (function () {
  8583. function ColorGradient() {
  8584. }
  8585. /**
  8586. * Will get a color picked randomly between color1 and color2.
  8587. * If color2 is undefined then color1 will be used
  8588. * @param result defines the target Color4 to store the result in
  8589. */
  8590. ColorGradient.prototype.getColorToRef = function (result) {
  8591. if (!this.color2) {
  8592. result.copyFrom(this.color1);
  8593. return;
  8594. }
  8595. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8596. };
  8597. return ColorGradient;
  8598. }());
  8599. BABYLON.ColorGradient = ColorGradient;
  8600. /** Class used to store factor gradient */
  8601. var FactorGradient = /** @class */ (function () {
  8602. function FactorGradient() {
  8603. }
  8604. /**
  8605. * Will get a number picked randomly between factor1 and factor2.
  8606. * If factor2 is undefined then factor1 will be used
  8607. * @returns the picked number
  8608. */
  8609. FactorGradient.prototype.getFactor = function () {
  8610. if (this.factor2 === undefined) {
  8611. return this.factor1;
  8612. }
  8613. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8614. };
  8615. return FactorGradient;
  8616. }());
  8617. BABYLON.FactorGradient = FactorGradient;
  8618. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8619. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8620. var LoadFileError = /** @class */ (function (_super) {
  8621. __extends(LoadFileError, _super);
  8622. function LoadFileError(message, request) {
  8623. var _this = _super.call(this, message) || this;
  8624. _this.request = request;
  8625. _this.name = "LoadFileError";
  8626. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8627. return _this;
  8628. }
  8629. // Polyfill for Object.setPrototypeOf if necessary.
  8630. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8631. return LoadFileError;
  8632. }(Error));
  8633. BABYLON.LoadFileError = LoadFileError;
  8634. var RetryStrategy = /** @class */ (function () {
  8635. function RetryStrategy() {
  8636. }
  8637. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8638. if (maxRetries === void 0) { maxRetries = 3; }
  8639. if (baseInterval === void 0) { baseInterval = 500; }
  8640. return function (url, request, retryIndex) {
  8641. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8642. return -1;
  8643. }
  8644. return Math.pow(2, retryIndex) * baseInterval;
  8645. };
  8646. };
  8647. return RetryStrategy;
  8648. }());
  8649. BABYLON.RetryStrategy = RetryStrategy;
  8650. // Screenshots
  8651. var screenshotCanvas;
  8652. var cloneValue = function (source, destinationObject) {
  8653. if (!source)
  8654. return null;
  8655. if (source instanceof BABYLON.Mesh) {
  8656. return null;
  8657. }
  8658. if (source instanceof BABYLON.SubMesh) {
  8659. return source.clone(destinationObject);
  8660. }
  8661. else if (source.clone) {
  8662. return source.clone();
  8663. }
  8664. return null;
  8665. };
  8666. var Tools = /** @class */ (function () {
  8667. function Tools() {
  8668. }
  8669. /**
  8670. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8671. * @param u defines the coordinate on X axis
  8672. * @param v defines the coordinate on Y axis
  8673. * @param width defines the width of the source data
  8674. * @param height defines the height of the source data
  8675. * @param pixels defines the source byte array
  8676. * @param color defines the output color
  8677. */
  8678. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8679. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8680. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8681. var position = (wrappedU + wrappedV * width) * 4;
  8682. color.r = pixels[position] / 255;
  8683. color.g = pixels[position + 1] / 255;
  8684. color.b = pixels[position + 2] / 255;
  8685. color.a = pixels[position + 3] / 255;
  8686. };
  8687. /**
  8688. * Interpolates between a and b via alpha
  8689. * @param a The lower value (returned when alpha = 0)
  8690. * @param b The upper value (returned when alpha = 1)
  8691. * @param alpha The interpolation-factor
  8692. * @return The mixed value
  8693. */
  8694. Tools.Mix = function (a, b, alpha) {
  8695. return a * (1 - alpha) + b * alpha;
  8696. };
  8697. Tools.Instantiate = function (className) {
  8698. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8699. return Tools.RegisteredExternalClasses[className];
  8700. }
  8701. var arr = className.split(".");
  8702. var fn = (window || this);
  8703. for (var i = 0, len = arr.length; i < len; i++) {
  8704. fn = fn[arr[i]];
  8705. }
  8706. if (typeof fn !== "function") {
  8707. return null;
  8708. }
  8709. return fn;
  8710. };
  8711. /**
  8712. * Provides a slice function that will work even on IE
  8713. * @param data defines the array to slice
  8714. * @param start defines the start of the data (optional)
  8715. * @param end defines the end of the data (optional)
  8716. * @returns the new sliced array
  8717. */
  8718. Tools.Slice = function (data, start, end) {
  8719. if (data.slice) {
  8720. return data.slice(start, end);
  8721. }
  8722. return Array.prototype.slice.call(data, start, end);
  8723. };
  8724. Tools.SetImmediate = function (action) {
  8725. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8726. window.setImmediate(action);
  8727. }
  8728. else {
  8729. setTimeout(action, 1);
  8730. }
  8731. };
  8732. Tools.IsExponentOfTwo = function (value) {
  8733. var count = 1;
  8734. do {
  8735. count *= 2;
  8736. } while (count < value);
  8737. return count === value;
  8738. };
  8739. /**
  8740. * Returns the nearest 32-bit single precision float representation of a Number
  8741. * @param value A Number. If the parameter is of a different type, it will get converted
  8742. * to a number or to NaN if it cannot be converted
  8743. * @returns number
  8744. */
  8745. Tools.FloatRound = function (value) {
  8746. if (Math.fround) {
  8747. return Math.fround(value);
  8748. }
  8749. return (Tools._tmpFloatArray[0] = value);
  8750. };
  8751. /**
  8752. * Find the next highest power of two.
  8753. * @param x Number to start search from.
  8754. * @return Next highest power of two.
  8755. */
  8756. Tools.CeilingPOT = function (x) {
  8757. x--;
  8758. x |= x >> 1;
  8759. x |= x >> 2;
  8760. x |= x >> 4;
  8761. x |= x >> 8;
  8762. x |= x >> 16;
  8763. x++;
  8764. return x;
  8765. };
  8766. /**
  8767. * Find the next lowest power of two.
  8768. * @param x Number to start search from.
  8769. * @return Next lowest power of two.
  8770. */
  8771. Tools.FloorPOT = function (x) {
  8772. x = x | (x >> 1);
  8773. x = x | (x >> 2);
  8774. x = x | (x >> 4);
  8775. x = x | (x >> 8);
  8776. x = x | (x >> 16);
  8777. return x - (x >> 1);
  8778. };
  8779. /**
  8780. * Find the nearest power of two.
  8781. * @param x Number to start search from.
  8782. * @return Next nearest power of two.
  8783. */
  8784. Tools.NearestPOT = function (x) {
  8785. var c = Tools.CeilingPOT(x);
  8786. var f = Tools.FloorPOT(x);
  8787. return (c - x) > (x - f) ? f : c;
  8788. };
  8789. Tools.GetExponentOfTwo = function (value, max, mode) {
  8790. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8791. var pot;
  8792. switch (mode) {
  8793. case BABYLON.Engine.SCALEMODE_FLOOR:
  8794. pot = Tools.FloorPOT(value);
  8795. break;
  8796. case BABYLON.Engine.SCALEMODE_NEAREST:
  8797. pot = Tools.NearestPOT(value);
  8798. break;
  8799. case BABYLON.Engine.SCALEMODE_CEILING:
  8800. default:
  8801. pot = Tools.CeilingPOT(value);
  8802. break;
  8803. }
  8804. return Math.min(pot, max);
  8805. };
  8806. Tools.GetFilename = function (path) {
  8807. var index = path.lastIndexOf("/");
  8808. if (index < 0)
  8809. return path;
  8810. return path.substring(index + 1);
  8811. };
  8812. /**
  8813. * Extracts the "folder" part of a path (everything before the filename).
  8814. * @param uri The URI to extract the info from
  8815. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8816. * @returns The "folder" part of the path
  8817. */
  8818. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8819. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8820. var index = uri.lastIndexOf("/");
  8821. if (index < 0) {
  8822. if (returnUnchangedIfNoSlash) {
  8823. return uri;
  8824. }
  8825. return "";
  8826. }
  8827. return uri.substring(0, index + 1);
  8828. };
  8829. Tools.GetDOMTextContent = function (element) {
  8830. var result = "";
  8831. var child = element.firstChild;
  8832. while (child) {
  8833. if (child.nodeType === 3) {
  8834. result += child.textContent;
  8835. }
  8836. child = child.nextSibling;
  8837. }
  8838. return result;
  8839. };
  8840. Tools.ToDegrees = function (angle) {
  8841. return angle * 180 / Math.PI;
  8842. };
  8843. Tools.ToRadians = function (angle) {
  8844. return angle * Math.PI / 180;
  8845. };
  8846. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8847. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8848. var output = "";
  8849. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8850. var i = 0;
  8851. var bytes = new Uint8Array(buffer);
  8852. while (i < bytes.length) {
  8853. chr1 = bytes[i++];
  8854. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8855. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8856. enc1 = chr1 >> 2;
  8857. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8858. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8859. enc4 = chr3 & 63;
  8860. if (isNaN(chr2)) {
  8861. enc3 = enc4 = 64;
  8862. }
  8863. else if (isNaN(chr3)) {
  8864. enc4 = 64;
  8865. }
  8866. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8867. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8868. }
  8869. return "data:image/png;base64," + output;
  8870. };
  8871. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8872. if (bias === void 0) { bias = null; }
  8873. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8874. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8875. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8876. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8877. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8878. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8879. }
  8880. if (bias) {
  8881. minimum.x -= minimum.x * bias.x + bias.y;
  8882. minimum.y -= minimum.y * bias.x + bias.y;
  8883. minimum.z -= minimum.z * bias.x + bias.y;
  8884. maximum.x += maximum.x * bias.x + bias.y;
  8885. maximum.y += maximum.y * bias.x + bias.y;
  8886. maximum.z += maximum.z * bias.x + bias.y;
  8887. }
  8888. return {
  8889. minimum: minimum,
  8890. maximum: maximum
  8891. };
  8892. };
  8893. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8894. if (bias === void 0) { bias = null; }
  8895. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8896. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8897. if (!stride) {
  8898. stride = 3;
  8899. }
  8900. for (var index = start; index < start + count; index++) {
  8901. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8902. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8903. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8904. }
  8905. if (bias) {
  8906. minimum.x -= minimum.x * bias.x + bias.y;
  8907. minimum.y -= minimum.y * bias.x + bias.y;
  8908. minimum.z -= minimum.z * bias.x + bias.y;
  8909. maximum.x += maximum.x * bias.x + bias.y;
  8910. maximum.y += maximum.y * bias.x + bias.y;
  8911. maximum.z += maximum.z * bias.x + bias.y;
  8912. }
  8913. return {
  8914. minimum: minimum,
  8915. maximum: maximum
  8916. };
  8917. };
  8918. Tools.Vector2ArrayFeeder = function (array) {
  8919. return function (index) {
  8920. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8921. var length = isFloatArray ? array.length / 2 : array.length;
  8922. if (index >= length) {
  8923. return null;
  8924. }
  8925. if (isFloatArray) {
  8926. var fa = array;
  8927. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8928. }
  8929. var a = array;
  8930. return a[index];
  8931. };
  8932. };
  8933. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8934. if (bias === void 0) { bias = null; }
  8935. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8936. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8937. var i = 0;
  8938. var cur = feeder(i++);
  8939. while (cur) {
  8940. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8941. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8942. cur = feeder(i++);
  8943. }
  8944. if (bias) {
  8945. minimum.x -= minimum.x * bias.x + bias.y;
  8946. minimum.y -= minimum.y * bias.x + bias.y;
  8947. maximum.x += maximum.x * bias.x + bias.y;
  8948. maximum.y += maximum.y * bias.x + bias.y;
  8949. }
  8950. return {
  8951. minimum: minimum,
  8952. maximum: maximum
  8953. };
  8954. };
  8955. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8956. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8957. return null;
  8958. return Array.isArray(obj) ? obj : [obj];
  8959. };
  8960. // Misc.
  8961. Tools.GetPointerPrefix = function () {
  8962. var eventPrefix = "pointer";
  8963. // Check if pointer events are supported
  8964. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8965. eventPrefix = "mouse";
  8966. }
  8967. return eventPrefix;
  8968. };
  8969. /**
  8970. * @param func - the function to be called
  8971. * @param requester - the object that will request the next frame. Falls back to window.
  8972. */
  8973. Tools.QueueNewFrame = function (func, requester) {
  8974. if (!Tools.IsWindowObjectExist()) {
  8975. return setTimeout(func, 16);
  8976. }
  8977. if (!requester) {
  8978. requester = window;
  8979. }
  8980. if (requester.requestAnimationFrame) {
  8981. return requester.requestAnimationFrame(func);
  8982. }
  8983. else if (requester.msRequestAnimationFrame) {
  8984. return requester.msRequestAnimationFrame(func);
  8985. }
  8986. else if (requester.webkitRequestAnimationFrame) {
  8987. return requester.webkitRequestAnimationFrame(func);
  8988. }
  8989. else if (requester.mozRequestAnimationFrame) {
  8990. return requester.mozRequestAnimationFrame(func);
  8991. }
  8992. else if (requester.oRequestAnimationFrame) {
  8993. return requester.oRequestAnimationFrame(func);
  8994. }
  8995. else {
  8996. return window.setTimeout(func, 16);
  8997. }
  8998. };
  8999. Tools.RequestFullscreen = function (element) {
  9000. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9001. if (!requestFunction)
  9002. return;
  9003. requestFunction.call(element);
  9004. };
  9005. Tools.ExitFullscreen = function () {
  9006. if (document.exitFullscreen) {
  9007. document.exitFullscreen();
  9008. }
  9009. else if (document.mozCancelFullScreen) {
  9010. document.mozCancelFullScreen();
  9011. }
  9012. else if (document.webkitCancelFullScreen) {
  9013. document.webkitCancelFullScreen();
  9014. }
  9015. else if (document.msCancelFullScreen) {
  9016. document.msCancelFullScreen();
  9017. }
  9018. };
  9019. Tools.SetCorsBehavior = function (url, element) {
  9020. if (url && url.indexOf("data:") === 0) {
  9021. return;
  9022. }
  9023. if (Tools.CorsBehavior) {
  9024. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9025. element.crossOrigin = Tools.CorsBehavior;
  9026. }
  9027. else {
  9028. var result = Tools.CorsBehavior(url);
  9029. if (result) {
  9030. element.crossOrigin = result;
  9031. }
  9032. }
  9033. }
  9034. };
  9035. // External files
  9036. Tools.CleanUrl = function (url) {
  9037. url = url.replace(/#/mg, "%23");
  9038. return url;
  9039. };
  9040. /**
  9041. * Loads an image as an HTMLImageElement.
  9042. * @param input url string, ArrayBuffer, or Blob to load
  9043. * @param onLoad callback called when the image successfully loads
  9044. * @param onError callback called when the image fails to load
  9045. * @param database database for caching
  9046. * @returns the HTMLImageElement of the loaded image
  9047. */
  9048. Tools.LoadImage = function (input, onLoad, onError, database) {
  9049. var url;
  9050. var usingObjectURL = false;
  9051. if (input instanceof ArrayBuffer) {
  9052. url = URL.createObjectURL(new Blob([input]));
  9053. usingObjectURL = true;
  9054. }
  9055. else if (input instanceof Blob) {
  9056. url = URL.createObjectURL(input);
  9057. usingObjectURL = true;
  9058. }
  9059. else {
  9060. url = Tools.CleanUrl(input);
  9061. url = Tools.PreprocessUrl(input);
  9062. }
  9063. var img = new Image();
  9064. Tools.SetCorsBehavior(url, img);
  9065. var loadHandler = function () {
  9066. if (usingObjectURL && img.src) {
  9067. URL.revokeObjectURL(img.src);
  9068. }
  9069. img.removeEventListener("load", loadHandler);
  9070. img.removeEventListener("error", errorHandler);
  9071. onLoad(img);
  9072. };
  9073. var errorHandler = function (err) {
  9074. if (usingObjectURL && img.src) {
  9075. URL.revokeObjectURL(img.src);
  9076. }
  9077. img.removeEventListener("load", loadHandler);
  9078. img.removeEventListener("error", errorHandler);
  9079. Tools.Error("Error while trying to load image: " + input);
  9080. if (onError) {
  9081. onError("Error while trying to load image: " + input, err);
  9082. }
  9083. };
  9084. img.addEventListener("load", loadHandler);
  9085. img.addEventListener("error", errorHandler);
  9086. var noIndexedDB = function () {
  9087. img.src = url;
  9088. };
  9089. var loadFromIndexedDB = function () {
  9090. if (database) {
  9091. database.loadImageFromDB(url, img);
  9092. }
  9093. };
  9094. //ANY database to do!
  9095. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9096. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9097. }
  9098. else {
  9099. if (url.indexOf("file:") !== -1) {
  9100. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9101. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9102. try {
  9103. var blobURL;
  9104. try {
  9105. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9106. }
  9107. catch (ex) {
  9108. // Chrome doesn't support oneTimeOnly parameter
  9109. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9110. }
  9111. img.src = blobURL;
  9112. usingObjectURL = true;
  9113. }
  9114. catch (e) {
  9115. img.src = "";
  9116. }
  9117. return img;
  9118. }
  9119. }
  9120. noIndexedDB();
  9121. }
  9122. return img;
  9123. };
  9124. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9125. url = Tools.CleanUrl(url);
  9126. url = Tools.PreprocessUrl(url);
  9127. // If file and file input are set
  9128. if (url.indexOf("file:") !== -1) {
  9129. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9130. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9131. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9132. }
  9133. }
  9134. var loadUrl = Tools.BaseUrl + url;
  9135. var aborted = false;
  9136. var fileRequest = {
  9137. onCompleteObservable: new BABYLON.Observable(),
  9138. abort: function () { return aborted = true; },
  9139. };
  9140. var requestFile = function () {
  9141. var request = new XMLHttpRequest();
  9142. var retryHandle = null;
  9143. fileRequest.abort = function () {
  9144. aborted = true;
  9145. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9146. request.abort();
  9147. }
  9148. if (retryHandle !== null) {
  9149. clearTimeout(retryHandle);
  9150. retryHandle = null;
  9151. }
  9152. };
  9153. var retryLoop = function (retryIndex) {
  9154. request.open('GET', loadUrl, true);
  9155. if (useArrayBuffer) {
  9156. request.responseType = "arraybuffer";
  9157. }
  9158. if (onProgress) {
  9159. request.addEventListener("progress", onProgress);
  9160. }
  9161. var onLoadEnd = function () {
  9162. request.removeEventListener("loadend", onLoadEnd);
  9163. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9164. fileRequest.onCompleteObservable.clear();
  9165. };
  9166. request.addEventListener("loadend", onLoadEnd);
  9167. var onReadyStateChange = function () {
  9168. if (aborted) {
  9169. return;
  9170. }
  9171. // In case of undefined state in some browsers.
  9172. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9173. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9174. request.removeEventListener("readystatechange", onReadyStateChange);
  9175. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9176. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9177. return;
  9178. }
  9179. var retryStrategy = Tools.DefaultRetryStrategy;
  9180. if (retryStrategy) {
  9181. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9182. if (waitTime !== -1) {
  9183. // Prevent the request from completing for retry.
  9184. request.removeEventListener("loadend", onLoadEnd);
  9185. request = new XMLHttpRequest();
  9186. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9187. return;
  9188. }
  9189. }
  9190. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9191. if (onError) {
  9192. onError(request, e);
  9193. }
  9194. else {
  9195. throw e;
  9196. }
  9197. }
  9198. };
  9199. request.addEventListener("readystatechange", onReadyStateChange);
  9200. request.send();
  9201. };
  9202. retryLoop(0);
  9203. };
  9204. // Caching all files
  9205. if (database && database.enableSceneOffline) {
  9206. var noIndexedDB_1 = function (request) {
  9207. if (request && request.status > 400) {
  9208. if (onError) {
  9209. onError(request);
  9210. }
  9211. }
  9212. else {
  9213. if (!aborted) {
  9214. requestFile();
  9215. }
  9216. }
  9217. };
  9218. var loadFromIndexedDB = function () {
  9219. // TODO: database needs to support aborting and should return a IFileRequest
  9220. if (aborted) {
  9221. return;
  9222. }
  9223. if (database) {
  9224. database.loadFileFromDB(url, function (data) {
  9225. if (!aborted) {
  9226. onSuccess(data);
  9227. }
  9228. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9229. }, onProgress ? function (event) {
  9230. if (!aborted) {
  9231. onProgress(event);
  9232. }
  9233. } : undefined, noIndexedDB_1, useArrayBuffer);
  9234. }
  9235. };
  9236. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9237. }
  9238. else {
  9239. requestFile();
  9240. }
  9241. return fileRequest;
  9242. };
  9243. /**
  9244. * Load a script (identified by an url). When the url returns, the
  9245. * content of this file is added into a new script element, attached to the DOM (body element)
  9246. */
  9247. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9248. var head = document.getElementsByTagName('head')[0];
  9249. var script = document.createElement('script');
  9250. script.type = 'text/javascript';
  9251. script.src = scriptUrl;
  9252. script.onload = function () {
  9253. if (onSuccess) {
  9254. onSuccess();
  9255. }
  9256. };
  9257. script.onerror = function (e) {
  9258. if (onError) {
  9259. onError("Unable to load script '" + scriptUrl + "'", e);
  9260. }
  9261. };
  9262. head.appendChild(script);
  9263. };
  9264. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9265. var reader = new FileReader();
  9266. var request = {
  9267. onCompleteObservable: new BABYLON.Observable(),
  9268. abort: function () { return reader.abort(); },
  9269. };
  9270. reader.onloadend = function (e) {
  9271. request.onCompleteObservable.notifyObservers(request);
  9272. };
  9273. reader.onload = function (e) {
  9274. //target doesn't have result from ts 1.3
  9275. callback(e.target['result']);
  9276. };
  9277. reader.onprogress = progressCallback;
  9278. reader.readAsDataURL(fileToLoad);
  9279. return request;
  9280. };
  9281. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9282. var reader = new FileReader();
  9283. var request = {
  9284. onCompleteObservable: new BABYLON.Observable(),
  9285. abort: function () { return reader.abort(); },
  9286. };
  9287. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9288. reader.onerror = function (e) {
  9289. Tools.Log("Error while reading file: " + fileToLoad.name);
  9290. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9291. };
  9292. reader.onload = function (e) {
  9293. //target doesn't have result from ts 1.3
  9294. callback(e.target['result']);
  9295. };
  9296. if (progressCallBack) {
  9297. reader.onprogress = progressCallBack;
  9298. }
  9299. if (!useArrayBuffer) {
  9300. // Asynchronous read
  9301. reader.readAsText(fileToLoad);
  9302. }
  9303. else {
  9304. reader.readAsArrayBuffer(fileToLoad);
  9305. }
  9306. return request;
  9307. };
  9308. //returns a downloadable url to a file content.
  9309. Tools.FileAsURL = function (content) {
  9310. var fileBlob = new Blob([content]);
  9311. var url = window.URL || window.webkitURL;
  9312. var link = url.createObjectURL(fileBlob);
  9313. return link;
  9314. };
  9315. // Misc.
  9316. Tools.Format = function (value, decimals) {
  9317. if (decimals === void 0) { decimals = 2; }
  9318. return value.toFixed(decimals);
  9319. };
  9320. Tools.CheckExtends = function (v, min, max) {
  9321. if (v.x < min.x)
  9322. min.x = v.x;
  9323. if (v.y < min.y)
  9324. min.y = v.y;
  9325. if (v.z < min.z)
  9326. min.z = v.z;
  9327. if (v.x > max.x)
  9328. max.x = v.x;
  9329. if (v.y > max.y)
  9330. max.y = v.y;
  9331. if (v.z > max.z)
  9332. max.z = v.z;
  9333. };
  9334. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9335. for (var prop in source) {
  9336. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9337. continue;
  9338. }
  9339. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9340. continue;
  9341. }
  9342. var sourceValue = source[prop];
  9343. var typeOfSourceValue = typeof sourceValue;
  9344. if (typeOfSourceValue === "function") {
  9345. continue;
  9346. }
  9347. try {
  9348. if (typeOfSourceValue === "object") {
  9349. if (sourceValue instanceof Array) {
  9350. destination[prop] = [];
  9351. if (sourceValue.length > 0) {
  9352. if (typeof sourceValue[0] == "object") {
  9353. for (var index = 0; index < sourceValue.length; index++) {
  9354. var clonedValue = cloneValue(sourceValue[index], destination);
  9355. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9356. destination[prop].push(clonedValue);
  9357. }
  9358. }
  9359. }
  9360. else {
  9361. destination[prop] = sourceValue.slice(0);
  9362. }
  9363. }
  9364. }
  9365. else {
  9366. destination[prop] = cloneValue(sourceValue, destination);
  9367. }
  9368. }
  9369. else {
  9370. destination[prop] = sourceValue;
  9371. }
  9372. }
  9373. catch (e) {
  9374. // Just ignore error (it could be because of a read-only property)
  9375. }
  9376. }
  9377. };
  9378. Tools.IsEmpty = function (obj) {
  9379. for (var i in obj) {
  9380. if (obj.hasOwnProperty(i)) {
  9381. return false;
  9382. }
  9383. }
  9384. return true;
  9385. };
  9386. Tools.RegisterTopRootEvents = function (events) {
  9387. for (var index = 0; index < events.length; index++) {
  9388. var event = events[index];
  9389. window.addEventListener(event.name, event.handler, false);
  9390. try {
  9391. if (window.parent) {
  9392. window.parent.addEventListener(event.name, event.handler, false);
  9393. }
  9394. }
  9395. catch (e) {
  9396. // Silently fails...
  9397. }
  9398. }
  9399. };
  9400. Tools.UnregisterTopRootEvents = function (events) {
  9401. for (var index = 0; index < events.length; index++) {
  9402. var event = events[index];
  9403. window.removeEventListener(event.name, event.handler);
  9404. try {
  9405. if (window.parent) {
  9406. window.parent.removeEventListener(event.name, event.handler);
  9407. }
  9408. }
  9409. catch (e) {
  9410. // Silently fails...
  9411. }
  9412. }
  9413. };
  9414. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9415. if (mimeType === void 0) { mimeType = "image/png"; }
  9416. // Read the contents of the framebuffer
  9417. var numberOfChannelsByLine = width * 4;
  9418. var halfHeight = height / 2;
  9419. //Reading datas from WebGL
  9420. var data = engine.readPixels(0, 0, width, height);
  9421. //To flip image on Y axis.
  9422. for (var i = 0; i < halfHeight; i++) {
  9423. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9424. var currentCell = j + i * numberOfChannelsByLine;
  9425. var targetLine = height - i - 1;
  9426. var targetCell = j + targetLine * numberOfChannelsByLine;
  9427. var temp = data[currentCell];
  9428. data[currentCell] = data[targetCell];
  9429. data[targetCell] = temp;
  9430. }
  9431. }
  9432. // Create a 2D canvas to store the result
  9433. if (!screenshotCanvas) {
  9434. screenshotCanvas = document.createElement('canvas');
  9435. }
  9436. screenshotCanvas.width = width;
  9437. screenshotCanvas.height = height;
  9438. var context = screenshotCanvas.getContext('2d');
  9439. if (context) {
  9440. // Copy the pixels to a 2D canvas
  9441. var imageData = context.createImageData(width, height);
  9442. var castData = (imageData.data);
  9443. castData.set(data);
  9444. context.putImageData(imageData, 0, 0);
  9445. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9446. }
  9447. };
  9448. /**
  9449. * Converts the canvas data to blob.
  9450. * This acts as a polyfill for browsers not supporting the to blob function.
  9451. * @param canvas Defines the canvas to extract the data from
  9452. * @param successCallback Defines the callback triggered once the data are available
  9453. * @param mimeType Defines the mime type of the result
  9454. */
  9455. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9456. if (mimeType === void 0) { mimeType = "image/png"; }
  9457. // We need HTMLCanvasElement.toBlob for HD screenshots
  9458. if (!canvas.toBlob) {
  9459. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9460. canvas.toBlob = function (callback, type, quality) {
  9461. var _this = this;
  9462. setTimeout(function () {
  9463. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9464. for (var i = 0; i < len; i++) {
  9465. arr[i] = binStr.charCodeAt(i);
  9466. }
  9467. callback(new Blob([arr]));
  9468. });
  9469. };
  9470. }
  9471. canvas.toBlob(function (blob) {
  9472. successCallback(blob);
  9473. }, mimeType);
  9474. };
  9475. /**
  9476. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9477. * @param successCallback Defines the callback triggered once the data are available
  9478. * @param mimeType Defines the mime type of the result
  9479. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9480. */
  9481. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9482. if (mimeType === void 0) { mimeType = "image/png"; }
  9483. if (successCallback) {
  9484. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9485. successCallback(base64Image);
  9486. }
  9487. else {
  9488. this.ToBlob(screenshotCanvas, function (blob) {
  9489. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9490. if (("download" in document.createElement("a"))) {
  9491. if (!fileName) {
  9492. var date = new Date();
  9493. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9494. fileName = "screenshot_" + stringDate + ".png";
  9495. }
  9496. Tools.Download(blob, fileName);
  9497. }
  9498. else {
  9499. var url = URL.createObjectURL(blob);
  9500. var newWindow = window.open("");
  9501. if (!newWindow)
  9502. return;
  9503. var img = newWindow.document.createElement("img");
  9504. img.onload = function () {
  9505. // no longer need to read the blob so it's revoked
  9506. URL.revokeObjectURL(url);
  9507. };
  9508. img.src = url;
  9509. newWindow.document.body.appendChild(img);
  9510. }
  9511. }, mimeType);
  9512. }
  9513. };
  9514. /**
  9515. * Downloads a blob in the browser
  9516. * @param blob defines the blob to download
  9517. * @param fileName defines the name of the downloaded file
  9518. */
  9519. Tools.Download = function (blob, fileName) {
  9520. if (navigator && navigator.msSaveBlob) {
  9521. navigator.msSaveBlob(blob, fileName);
  9522. return;
  9523. }
  9524. var url = window.URL.createObjectURL(blob);
  9525. var a = document.createElement("a");
  9526. document.body.appendChild(a);
  9527. a.style.display = "none";
  9528. a.href = url;
  9529. a.download = fileName;
  9530. a.addEventListener("click", function () {
  9531. if (a.parentElement) {
  9532. a.parentElement.removeChild(a);
  9533. }
  9534. });
  9535. a.click();
  9536. window.URL.revokeObjectURL(url);
  9537. };
  9538. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9539. if (mimeType === void 0) { mimeType = "image/png"; }
  9540. var width;
  9541. var height;
  9542. // If a precision value is specified
  9543. if (size.precision) {
  9544. width = Math.round(engine.getRenderWidth() * size.precision);
  9545. height = Math.round(width / engine.getAspectRatio(camera));
  9546. }
  9547. else if (size.width && size.height) {
  9548. width = size.width;
  9549. height = size.height;
  9550. }
  9551. //If passing only width, computing height to keep display canvas ratio.
  9552. else if (size.width && !size.height) {
  9553. width = size.width;
  9554. height = Math.round(width / engine.getAspectRatio(camera));
  9555. }
  9556. //If passing only height, computing width to keep display canvas ratio.
  9557. else if (size.height && !size.width) {
  9558. height = size.height;
  9559. width = Math.round(height * engine.getAspectRatio(camera));
  9560. }
  9561. //Assuming here that "size" parameter is a number
  9562. else if (!isNaN(size)) {
  9563. height = size;
  9564. width = size;
  9565. }
  9566. else {
  9567. Tools.Error("Invalid 'size' parameter !");
  9568. return;
  9569. }
  9570. if (!screenshotCanvas) {
  9571. screenshotCanvas = document.createElement('canvas');
  9572. }
  9573. screenshotCanvas.width = width;
  9574. screenshotCanvas.height = height;
  9575. var renderContext = screenshotCanvas.getContext("2d");
  9576. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9577. var newWidth = width;
  9578. var newHeight = newWidth / ratio;
  9579. if (newHeight > height) {
  9580. newHeight = height;
  9581. newWidth = newHeight * ratio;
  9582. }
  9583. var offsetX = Math.max(0, width - newWidth) / 2;
  9584. var offsetY = Math.max(0, height - newHeight) / 2;
  9585. var renderingCanvas = engine.getRenderingCanvas();
  9586. if (renderContext && renderingCanvas) {
  9587. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9588. }
  9589. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9590. };
  9591. /**
  9592. * Generates an image screenshot from the specified camera.
  9593. *
  9594. * @param engine The engine to use for rendering
  9595. * @param camera The camera to use for rendering
  9596. * @param size This parameter can be set to a single number or to an object with the
  9597. * following (optional) properties: precision, width, height. If a single number is passed,
  9598. * it will be used for both width and height. If an object is passed, the screenshot size
  9599. * will be derived from the parameters. The precision property is a multiplier allowing
  9600. * rendering at a higher or lower resolution.
  9601. * @param successCallback The callback receives a single parameter which contains the
  9602. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9603. * src parameter of an <img> to display it.
  9604. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9605. * Check your browser for supported MIME types.
  9606. * @param samples Texture samples (default: 1)
  9607. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9608. * @param fileName A name for for the downloaded file.
  9609. * @constructor
  9610. */
  9611. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9612. if (mimeType === void 0) { mimeType = "image/png"; }
  9613. if (samples === void 0) { samples = 1; }
  9614. if (antialiasing === void 0) { antialiasing = false; }
  9615. var width;
  9616. var height;
  9617. //If a precision value is specified
  9618. if (size.precision) {
  9619. width = Math.round(engine.getRenderWidth() * size.precision);
  9620. height = Math.round(width / engine.getAspectRatio(camera));
  9621. size = { width: width, height: height };
  9622. }
  9623. else if (size.width && size.height) {
  9624. width = size.width;
  9625. height = size.height;
  9626. }
  9627. //If passing only width, computing height to keep display canvas ratio.
  9628. else if (size.width && !size.height) {
  9629. width = size.width;
  9630. height = Math.round(width / engine.getAspectRatio(camera));
  9631. size = { width: width, height: height };
  9632. }
  9633. //If passing only height, computing width to keep display canvas ratio.
  9634. else if (size.height && !size.width) {
  9635. height = size.height;
  9636. width = Math.round(height * engine.getAspectRatio(camera));
  9637. size = { width: width, height: height };
  9638. }
  9639. //Assuming here that "size" parameter is a number
  9640. else if (!isNaN(size)) {
  9641. height = size;
  9642. width = size;
  9643. }
  9644. else {
  9645. Tools.Error("Invalid 'size' parameter !");
  9646. return;
  9647. }
  9648. var scene = camera.getScene();
  9649. var previousCamera = null;
  9650. if (scene.activeCamera !== camera) {
  9651. previousCamera = scene.activeCamera;
  9652. scene.activeCamera = camera;
  9653. }
  9654. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9655. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9656. texture.renderList = null;
  9657. texture.samples = samples;
  9658. if (antialiasing) {
  9659. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9660. }
  9661. texture.onAfterRenderObservable.add(function () {
  9662. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9663. });
  9664. scene.incrementRenderId();
  9665. scene.resetCachedMaterial();
  9666. texture.render(true);
  9667. texture.dispose();
  9668. if (previousCamera) {
  9669. scene.activeCamera = previousCamera;
  9670. }
  9671. camera.getProjectionMatrix(true); // Force cache refresh;
  9672. };
  9673. // XHR response validator for local file scenario
  9674. Tools.ValidateXHRData = function (xhr, dataType) {
  9675. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9676. if (dataType === void 0) { dataType = 7; }
  9677. try {
  9678. if (dataType & 1) {
  9679. if (xhr.responseText && xhr.responseText.length > 0) {
  9680. return true;
  9681. }
  9682. else if (dataType === 1) {
  9683. return false;
  9684. }
  9685. }
  9686. if (dataType & 2) {
  9687. // Check header width and height since there is no "TGA" magic number
  9688. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9689. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9690. return true;
  9691. }
  9692. else if (dataType === 2) {
  9693. return false;
  9694. }
  9695. }
  9696. if (dataType & 4) {
  9697. // Check for the "DDS" magic number
  9698. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9699. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9700. return true;
  9701. }
  9702. else {
  9703. return false;
  9704. }
  9705. }
  9706. }
  9707. catch (e) {
  9708. // Global protection
  9709. }
  9710. return false;
  9711. };
  9712. /**
  9713. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9714. * Be aware Math.random() could cause collisions, but:
  9715. * "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"
  9716. */
  9717. Tools.RandomId = function () {
  9718. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9719. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9720. return v.toString(16);
  9721. });
  9722. };
  9723. /**
  9724. * Test if the given uri is a base64 string.
  9725. * @param uri The uri to test
  9726. * @return True if the uri is a base64 string or false otherwise.
  9727. */
  9728. Tools.IsBase64 = function (uri) {
  9729. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9730. };
  9731. /**
  9732. * Decode the given base64 uri.
  9733. * @param uri The uri to decode
  9734. * @return The decoded base64 data.
  9735. */
  9736. Tools.DecodeBase64 = function (uri) {
  9737. var decodedString = atob(uri.split(",")[1]);
  9738. var bufferLength = decodedString.length;
  9739. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9740. for (var i = 0; i < bufferLength; i++) {
  9741. bufferView[i] = decodedString.charCodeAt(i);
  9742. }
  9743. return bufferView.buffer;
  9744. };
  9745. Object.defineProperty(Tools, "NoneLogLevel", {
  9746. get: function () {
  9747. return Tools._NoneLogLevel;
  9748. },
  9749. enumerable: true,
  9750. configurable: true
  9751. });
  9752. Object.defineProperty(Tools, "MessageLogLevel", {
  9753. get: function () {
  9754. return Tools._MessageLogLevel;
  9755. },
  9756. enumerable: true,
  9757. configurable: true
  9758. });
  9759. Object.defineProperty(Tools, "WarningLogLevel", {
  9760. get: function () {
  9761. return Tools._WarningLogLevel;
  9762. },
  9763. enumerable: true,
  9764. configurable: true
  9765. });
  9766. Object.defineProperty(Tools, "ErrorLogLevel", {
  9767. get: function () {
  9768. return Tools._ErrorLogLevel;
  9769. },
  9770. enumerable: true,
  9771. configurable: true
  9772. });
  9773. Object.defineProperty(Tools, "AllLogLevel", {
  9774. get: function () {
  9775. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9776. },
  9777. enumerable: true,
  9778. configurable: true
  9779. });
  9780. Tools._AddLogEntry = function (entry) {
  9781. Tools._LogCache = entry + Tools._LogCache;
  9782. if (Tools.OnNewCacheEntry) {
  9783. Tools.OnNewCacheEntry(entry);
  9784. }
  9785. };
  9786. Tools._FormatMessage = function (message) {
  9787. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9788. var date = new Date();
  9789. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9790. };
  9791. Tools._LogDisabled = function (message) {
  9792. // nothing to do
  9793. };
  9794. Tools._LogEnabled = function (message) {
  9795. var formattedMessage = Tools._FormatMessage(message);
  9796. console.log("BJS - " + formattedMessage);
  9797. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9798. Tools._AddLogEntry(entry);
  9799. };
  9800. Tools._WarnDisabled = function (message) {
  9801. // nothing to do
  9802. };
  9803. Tools._WarnEnabled = function (message) {
  9804. var formattedMessage = Tools._FormatMessage(message);
  9805. console.warn("BJS - " + formattedMessage);
  9806. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9807. Tools._AddLogEntry(entry);
  9808. };
  9809. Tools._ErrorDisabled = function (message) {
  9810. // nothing to do
  9811. };
  9812. Tools._ErrorEnabled = function (message) {
  9813. Tools.errorsCount++;
  9814. var formattedMessage = Tools._FormatMessage(message);
  9815. console.error("BJS - " + formattedMessage);
  9816. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9817. Tools._AddLogEntry(entry);
  9818. };
  9819. Object.defineProperty(Tools, "LogCache", {
  9820. get: function () {
  9821. return Tools._LogCache;
  9822. },
  9823. enumerable: true,
  9824. configurable: true
  9825. });
  9826. Tools.ClearLogCache = function () {
  9827. Tools._LogCache = "";
  9828. Tools.errorsCount = 0;
  9829. };
  9830. Object.defineProperty(Tools, "LogLevels", {
  9831. set: function (level) {
  9832. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9833. Tools.Log = Tools._LogEnabled;
  9834. }
  9835. else {
  9836. Tools.Log = Tools._LogDisabled;
  9837. }
  9838. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9839. Tools.Warn = Tools._WarnEnabled;
  9840. }
  9841. else {
  9842. Tools.Warn = Tools._WarnDisabled;
  9843. }
  9844. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9845. Tools.Error = Tools._ErrorEnabled;
  9846. }
  9847. else {
  9848. Tools.Error = Tools._ErrorDisabled;
  9849. }
  9850. },
  9851. enumerable: true,
  9852. configurable: true
  9853. });
  9854. Tools.IsWindowObjectExist = function () {
  9855. return (typeof window) !== "undefined";
  9856. };
  9857. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9858. get: function () {
  9859. return Tools._PerformanceNoneLogLevel;
  9860. },
  9861. enumerable: true,
  9862. configurable: true
  9863. });
  9864. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9865. get: function () {
  9866. return Tools._PerformanceUserMarkLogLevel;
  9867. },
  9868. enumerable: true,
  9869. configurable: true
  9870. });
  9871. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9872. get: function () {
  9873. return Tools._PerformanceConsoleLogLevel;
  9874. },
  9875. enumerable: true,
  9876. configurable: true
  9877. });
  9878. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9879. set: function (level) {
  9880. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9881. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9882. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9883. return;
  9884. }
  9885. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9886. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9887. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9888. return;
  9889. }
  9890. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9891. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9892. },
  9893. enumerable: true,
  9894. configurable: true
  9895. });
  9896. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9897. };
  9898. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9899. };
  9900. Tools._StartUserMark = function (counterName, condition) {
  9901. if (condition === void 0) { condition = true; }
  9902. if (!Tools._performance) {
  9903. if (!Tools.IsWindowObjectExist()) {
  9904. return;
  9905. }
  9906. Tools._performance = window.performance;
  9907. }
  9908. if (!condition || !Tools._performance.mark) {
  9909. return;
  9910. }
  9911. Tools._performance.mark(counterName + "-Begin");
  9912. };
  9913. Tools._EndUserMark = function (counterName, condition) {
  9914. if (condition === void 0) { condition = true; }
  9915. if (!condition || !Tools._performance.mark) {
  9916. return;
  9917. }
  9918. Tools._performance.mark(counterName + "-End");
  9919. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9920. };
  9921. Tools._StartPerformanceConsole = function (counterName, condition) {
  9922. if (condition === void 0) { condition = true; }
  9923. if (!condition) {
  9924. return;
  9925. }
  9926. Tools._StartUserMark(counterName, condition);
  9927. if (console.time) {
  9928. console.time(counterName);
  9929. }
  9930. };
  9931. Tools._EndPerformanceConsole = function (counterName, condition) {
  9932. if (condition === void 0) { condition = true; }
  9933. if (!condition) {
  9934. return;
  9935. }
  9936. Tools._EndUserMark(counterName, condition);
  9937. if (console.time) {
  9938. console.timeEnd(counterName);
  9939. }
  9940. };
  9941. Object.defineProperty(Tools, "Now", {
  9942. get: function () {
  9943. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9944. return window.performance.now();
  9945. }
  9946. return Date.now();
  9947. },
  9948. enumerable: true,
  9949. configurable: true
  9950. });
  9951. /**
  9952. * This method will return the name of the class used to create the instance of the given object.
  9953. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9954. * @param object the object to get the class name from
  9955. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9956. */
  9957. Tools.GetClassName = function (object, isType) {
  9958. if (isType === void 0) { isType = false; }
  9959. var name = null;
  9960. if (!isType && object.getClassName) {
  9961. name = object.getClassName();
  9962. }
  9963. else {
  9964. if (object instanceof Object) {
  9965. var classObj = isType ? object : Object.getPrototypeOf(object);
  9966. name = classObj.constructor["__bjsclassName__"];
  9967. }
  9968. if (!name) {
  9969. name = typeof object;
  9970. }
  9971. }
  9972. return name;
  9973. };
  9974. Tools.First = function (array, predicate) {
  9975. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9976. var el = array_1[_i];
  9977. if (predicate(el)) {
  9978. return el;
  9979. }
  9980. }
  9981. return null;
  9982. };
  9983. /**
  9984. * This method will return the name of the full name of the class, including its owning module (if any).
  9985. * 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).
  9986. * @param object the object to get the class name from
  9987. * @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.
  9988. */
  9989. Tools.getFullClassName = function (object, isType) {
  9990. if (isType === void 0) { isType = false; }
  9991. var className = null;
  9992. var moduleName = null;
  9993. if (!isType && object.getClassName) {
  9994. className = object.getClassName();
  9995. }
  9996. else {
  9997. if (object instanceof Object) {
  9998. var classObj = isType ? object : Object.getPrototypeOf(object);
  9999. className = classObj.constructor["__bjsclassName__"];
  10000. moduleName = classObj.constructor["__bjsmoduleName__"];
  10001. }
  10002. if (!className) {
  10003. className = typeof object;
  10004. }
  10005. }
  10006. if (!className) {
  10007. return null;
  10008. }
  10009. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10010. };
  10011. /**
  10012. * 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.
  10013. * @param array
  10014. */
  10015. Tools.arrayOrStringFeeder = function (array) {
  10016. return function (index) {
  10017. if (index >= array.length) {
  10018. return null;
  10019. }
  10020. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10021. if (val && val.getHashCode) {
  10022. val = val.getHashCode();
  10023. }
  10024. if (typeof val === "string") {
  10025. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10026. }
  10027. return val;
  10028. };
  10029. };
  10030. /**
  10031. * Compute the hashCode of a stream of number
  10032. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10033. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10034. * @return the hash code computed
  10035. */
  10036. Tools.hashCodeFromStream = function (feeder) {
  10037. // Based from here: http://stackoverflow.com/a/7616484/802124
  10038. var hash = 0;
  10039. var index = 0;
  10040. var chr = feeder(index++);
  10041. while (chr != null) {
  10042. hash = ((hash << 5) - hash) + chr;
  10043. hash |= 0; // Convert to 32bit integer
  10044. chr = feeder(index++);
  10045. }
  10046. return hash;
  10047. };
  10048. /**
  10049. * Returns a promise that resolves after the given amount of time.
  10050. * @param delay Number of milliseconds to delay
  10051. * @returns Promise that resolves after the given amount of time
  10052. */
  10053. Tools.DelayAsync = function (delay) {
  10054. return new Promise(function (resolve) {
  10055. setTimeout(function () {
  10056. resolve();
  10057. }, delay);
  10058. });
  10059. };
  10060. /**
  10061. * Gets the current gradient from an array of IValueGradient
  10062. * @param ratio defines the current ratio to get
  10063. * @param gradients defines the array of IValueGradient
  10064. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10065. */
  10066. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10067. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10068. var currentGradient = gradients[gradientIndex];
  10069. var nextGradient = gradients[gradientIndex + 1];
  10070. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10071. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10072. updateFunc(currentGradient, nextGradient, scale);
  10073. }
  10074. }
  10075. };
  10076. Tools.BaseUrl = "";
  10077. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10078. /**
  10079. * Default behaviour for cors in the application.
  10080. * It can be a string if the expected behavior is identical in the entire app.
  10081. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10082. */
  10083. Tools.CorsBehavior = "anonymous";
  10084. Tools.UseFallbackTexture = true;
  10085. /**
  10086. * Use this object to register external classes like custom textures or material
  10087. * to allow the laoders to instantiate them
  10088. */
  10089. Tools.RegisteredExternalClasses = {};
  10090. // Used in case of a texture loading problem
  10091. 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";
  10092. Tools._tmpFloatArray = new Float32Array(1);
  10093. Tools.PreprocessUrl = function (url) {
  10094. return url;
  10095. };
  10096. // Logs
  10097. Tools._NoneLogLevel = 0;
  10098. Tools._MessageLogLevel = 1;
  10099. Tools._WarningLogLevel = 2;
  10100. Tools._ErrorLogLevel = 4;
  10101. Tools._LogCache = "";
  10102. Tools.errorsCount = 0;
  10103. Tools.Log = Tools._LogEnabled;
  10104. Tools.Warn = Tools._WarnEnabled;
  10105. Tools.Error = Tools._ErrorEnabled;
  10106. // Performances
  10107. Tools._PerformanceNoneLogLevel = 0;
  10108. Tools._PerformanceUserMarkLogLevel = 1;
  10109. Tools._PerformanceConsoleLogLevel = 2;
  10110. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10111. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10112. return Tools;
  10113. }());
  10114. BABYLON.Tools = Tools;
  10115. /**
  10116. * This class is used to track a performance counter which is number based.
  10117. * The user has access to many properties which give statistics of different nature
  10118. *
  10119. * The implementer can track two kinds of Performance Counter: time and count
  10120. * 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.
  10121. * 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.
  10122. */
  10123. var PerfCounter = /** @class */ (function () {
  10124. function PerfCounter() {
  10125. this._startMonitoringTime = 0;
  10126. this._min = 0;
  10127. this._max = 0;
  10128. this._average = 0;
  10129. this._lastSecAverage = 0;
  10130. this._current = 0;
  10131. this._totalValueCount = 0;
  10132. this._totalAccumulated = 0;
  10133. this._lastSecAccumulated = 0;
  10134. this._lastSecTime = 0;
  10135. this._lastSecValueCount = 0;
  10136. }
  10137. Object.defineProperty(PerfCounter.prototype, "min", {
  10138. /**
  10139. * Returns the smallest value ever
  10140. */
  10141. get: function () {
  10142. return this._min;
  10143. },
  10144. enumerable: true,
  10145. configurable: true
  10146. });
  10147. Object.defineProperty(PerfCounter.prototype, "max", {
  10148. /**
  10149. * Returns the biggest value ever
  10150. */
  10151. get: function () {
  10152. return this._max;
  10153. },
  10154. enumerable: true,
  10155. configurable: true
  10156. });
  10157. Object.defineProperty(PerfCounter.prototype, "average", {
  10158. /**
  10159. * Returns the average value since the performance counter is running
  10160. */
  10161. get: function () {
  10162. return this._average;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10168. /**
  10169. * Returns the average value of the last second the counter was monitored
  10170. */
  10171. get: function () {
  10172. return this._lastSecAverage;
  10173. },
  10174. enumerable: true,
  10175. configurable: true
  10176. });
  10177. Object.defineProperty(PerfCounter.prototype, "current", {
  10178. /**
  10179. * Returns the current value
  10180. */
  10181. get: function () {
  10182. return this._current;
  10183. },
  10184. enumerable: true,
  10185. configurable: true
  10186. });
  10187. Object.defineProperty(PerfCounter.prototype, "total", {
  10188. get: function () {
  10189. return this._totalAccumulated;
  10190. },
  10191. enumerable: true,
  10192. configurable: true
  10193. });
  10194. Object.defineProperty(PerfCounter.prototype, "count", {
  10195. get: function () {
  10196. return this._totalValueCount;
  10197. },
  10198. enumerable: true,
  10199. configurable: true
  10200. });
  10201. /**
  10202. * Call this method to start monitoring a new frame.
  10203. * 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.
  10204. */
  10205. PerfCounter.prototype.fetchNewFrame = function () {
  10206. this._totalValueCount++;
  10207. this._current = 0;
  10208. this._lastSecValueCount++;
  10209. };
  10210. /**
  10211. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10212. * @param newCount the count value to add to the monitored count
  10213. * @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.
  10214. */
  10215. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10216. if (!PerfCounter.Enabled) {
  10217. return;
  10218. }
  10219. this._current += newCount;
  10220. if (fetchResult) {
  10221. this._fetchResult();
  10222. }
  10223. };
  10224. /**
  10225. * Start monitoring this performance counter
  10226. */
  10227. PerfCounter.prototype.beginMonitoring = function () {
  10228. if (!PerfCounter.Enabled) {
  10229. return;
  10230. }
  10231. this._startMonitoringTime = Tools.Now;
  10232. };
  10233. /**
  10234. * Compute the time lapsed since the previous beginMonitoring() call.
  10235. * @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
  10236. */
  10237. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10238. if (newFrame === void 0) { newFrame = true; }
  10239. if (!PerfCounter.Enabled) {
  10240. return;
  10241. }
  10242. if (newFrame) {
  10243. this.fetchNewFrame();
  10244. }
  10245. var currentTime = Tools.Now;
  10246. this._current = currentTime - this._startMonitoringTime;
  10247. if (newFrame) {
  10248. this._fetchResult();
  10249. }
  10250. };
  10251. PerfCounter.prototype._fetchResult = function () {
  10252. this._totalAccumulated += this._current;
  10253. this._lastSecAccumulated += this._current;
  10254. // Min/Max update
  10255. this._min = Math.min(this._min, this._current);
  10256. this._max = Math.max(this._max, this._current);
  10257. this._average = this._totalAccumulated / this._totalValueCount;
  10258. // Reset last sec?
  10259. var now = Tools.Now;
  10260. if ((now - this._lastSecTime) > 1000) {
  10261. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10262. this._lastSecTime = now;
  10263. this._lastSecAccumulated = 0;
  10264. this._lastSecValueCount = 0;
  10265. }
  10266. };
  10267. PerfCounter.Enabled = true;
  10268. return PerfCounter;
  10269. }());
  10270. BABYLON.PerfCounter = PerfCounter;
  10271. /**
  10272. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10273. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10274. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10275. * @param name The name of the class, case should be preserved
  10276. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10277. */
  10278. function className(name, module) {
  10279. return function (target) {
  10280. target["__bjsclassName__"] = name;
  10281. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10282. };
  10283. }
  10284. BABYLON.className = className;
  10285. /**
  10286. * An implementation of a loop for asynchronous functions.
  10287. */
  10288. var AsyncLoop = /** @class */ (function () {
  10289. /**
  10290. * Constroctor.
  10291. * @param iterations the number of iterations.
  10292. * @param _fn the function to run each iteration
  10293. * @param _successCallback the callback that will be called upon succesful execution
  10294. * @param offset starting offset.
  10295. */
  10296. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10297. if (offset === void 0) { offset = 0; }
  10298. this.iterations = iterations;
  10299. this._fn = _fn;
  10300. this._successCallback = _successCallback;
  10301. this.index = offset - 1;
  10302. this._done = false;
  10303. }
  10304. /**
  10305. * Execute the next iteration. Must be called after the last iteration was finished.
  10306. */
  10307. AsyncLoop.prototype.executeNext = function () {
  10308. if (!this._done) {
  10309. if (this.index + 1 < this.iterations) {
  10310. ++this.index;
  10311. this._fn(this);
  10312. }
  10313. else {
  10314. this.breakLoop();
  10315. }
  10316. }
  10317. };
  10318. /**
  10319. * Break the loop and run the success callback.
  10320. */
  10321. AsyncLoop.prototype.breakLoop = function () {
  10322. this._done = true;
  10323. this._successCallback();
  10324. };
  10325. /**
  10326. * Helper function
  10327. */
  10328. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10329. if (offset === void 0) { offset = 0; }
  10330. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10331. loop.executeNext();
  10332. return loop;
  10333. };
  10334. /**
  10335. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10336. * @param iterations total number of iterations
  10337. * @param syncedIterations number of synchronous iterations in each async iteration.
  10338. * @param fn the function to call each iteration.
  10339. * @param callback a success call back that will be called when iterating stops.
  10340. * @param breakFunction a break condition (optional)
  10341. * @param timeout timeout settings for the setTimeout function. default - 0.
  10342. * @constructor
  10343. */
  10344. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10345. if (timeout === void 0) { timeout = 0; }
  10346. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10347. if (breakFunction && breakFunction())
  10348. loop.breakLoop();
  10349. else {
  10350. setTimeout(function () {
  10351. for (var i = 0; i < syncedIterations; ++i) {
  10352. var iteration = (loop.index * syncedIterations) + i;
  10353. if (iteration >= iterations)
  10354. break;
  10355. fn(iteration);
  10356. if (breakFunction && breakFunction()) {
  10357. loop.breakLoop();
  10358. break;
  10359. }
  10360. }
  10361. loop.executeNext();
  10362. }, timeout);
  10363. }
  10364. }, callback);
  10365. };
  10366. return AsyncLoop;
  10367. }());
  10368. BABYLON.AsyncLoop = AsyncLoop;
  10369. })(BABYLON || (BABYLON = {}));
  10370. //# sourceMappingURL=babylon.tools.js.map
  10371. var BABYLON;
  10372. (function (BABYLON) {
  10373. var PromiseStates;
  10374. (function (PromiseStates) {
  10375. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10376. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10377. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10378. })(PromiseStates || (PromiseStates = {}));
  10379. var FulFillmentAgregator = /** @class */ (function () {
  10380. function FulFillmentAgregator() {
  10381. this.count = 0;
  10382. this.target = 0;
  10383. this.results = [];
  10384. }
  10385. return FulFillmentAgregator;
  10386. }());
  10387. var InternalPromise = /** @class */ (function () {
  10388. function InternalPromise(resolver) {
  10389. var _this = this;
  10390. this._state = PromiseStates.Pending;
  10391. this._children = new Array();
  10392. this._rejectWasConsumed = false;
  10393. if (!resolver) {
  10394. return;
  10395. }
  10396. try {
  10397. resolver(function (value) {
  10398. _this._resolve(value);
  10399. }, function (reason) {
  10400. _this._reject(reason);
  10401. });
  10402. }
  10403. catch (e) {
  10404. this._reject(e);
  10405. }
  10406. }
  10407. Object.defineProperty(InternalPromise.prototype, "_result", {
  10408. get: function () {
  10409. return this._resultValue;
  10410. },
  10411. set: function (value) {
  10412. this._resultValue = value;
  10413. if (this._parent && this._parent._result === undefined) {
  10414. this._parent._result = value;
  10415. }
  10416. },
  10417. enumerable: true,
  10418. configurable: true
  10419. });
  10420. InternalPromise.prototype.catch = function (onRejected) {
  10421. return this.then(undefined, onRejected);
  10422. };
  10423. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10424. var _this = this;
  10425. var newPromise = new InternalPromise();
  10426. newPromise._onFulfilled = onFulfilled;
  10427. newPromise._onRejected = onRejected;
  10428. // Composition
  10429. this._children.push(newPromise);
  10430. newPromise._parent = this;
  10431. if (this._state !== PromiseStates.Pending) {
  10432. BABYLON.Tools.SetImmediate(function () {
  10433. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10434. var returnedValue = newPromise._resolve(_this._result);
  10435. if (returnedValue !== undefined && returnedValue !== null) {
  10436. if (returnedValue._state !== undefined) {
  10437. var returnedPromise = returnedValue;
  10438. newPromise._children.push(returnedPromise);
  10439. returnedPromise._parent = newPromise;
  10440. newPromise = returnedPromise;
  10441. }
  10442. else {
  10443. newPromise._result = returnedValue;
  10444. }
  10445. }
  10446. }
  10447. else {
  10448. newPromise._reject(_this._reason);
  10449. }
  10450. });
  10451. }
  10452. return newPromise;
  10453. };
  10454. InternalPromise.prototype._moveChildren = function (children) {
  10455. var _this = this;
  10456. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10457. this._children.forEach(function (child) {
  10458. child._parent = _this;
  10459. });
  10460. if (this._state === PromiseStates.Fulfilled) {
  10461. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10462. var child = _b[_i];
  10463. child._resolve(this._result);
  10464. }
  10465. }
  10466. else if (this._state === PromiseStates.Rejected) {
  10467. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10468. var child = _d[_c];
  10469. child._reject(this._reason);
  10470. }
  10471. }
  10472. var _a;
  10473. };
  10474. InternalPromise.prototype._resolve = function (value) {
  10475. try {
  10476. this._state = PromiseStates.Fulfilled;
  10477. var returnedValue = null;
  10478. if (this._onFulfilled) {
  10479. returnedValue = this._onFulfilled(value);
  10480. }
  10481. if (returnedValue !== undefined && returnedValue !== null) {
  10482. if (returnedValue._state !== undefined) {
  10483. // Transmit children
  10484. var returnedPromise = returnedValue;
  10485. returnedPromise._parent = this;
  10486. returnedPromise._moveChildren(this._children);
  10487. value = returnedPromise._result;
  10488. }
  10489. else {
  10490. value = returnedValue;
  10491. }
  10492. }
  10493. this._result = value;
  10494. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10495. var child = _a[_i];
  10496. child._resolve(value);
  10497. }
  10498. this._children.length = 0;
  10499. delete this._onFulfilled;
  10500. delete this._onRejected;
  10501. }
  10502. catch (e) {
  10503. this._reject(e, true);
  10504. }
  10505. };
  10506. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10507. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10508. this._state = PromiseStates.Rejected;
  10509. this._reason = reason;
  10510. if (this._onRejected && !onLocalThrow) {
  10511. try {
  10512. this._onRejected(reason);
  10513. this._rejectWasConsumed = true;
  10514. }
  10515. catch (e) {
  10516. reason = e;
  10517. }
  10518. }
  10519. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10520. var child = _a[_i];
  10521. if (this._rejectWasConsumed) {
  10522. child._resolve(null);
  10523. }
  10524. else {
  10525. child._reject(reason);
  10526. }
  10527. }
  10528. this._children.length = 0;
  10529. delete this._onFulfilled;
  10530. delete this._onRejected;
  10531. };
  10532. InternalPromise.resolve = function (value) {
  10533. var newPromise = new InternalPromise();
  10534. newPromise._resolve(value);
  10535. return newPromise;
  10536. };
  10537. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10538. promise.then(function (value) {
  10539. agregator.results[index] = value;
  10540. agregator.count++;
  10541. if (agregator.count === agregator.target) {
  10542. agregator.rootPromise._resolve(agregator.results);
  10543. }
  10544. return null;
  10545. }, function (reason) {
  10546. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10547. agregator.rootPromise._reject(reason);
  10548. }
  10549. });
  10550. };
  10551. InternalPromise.all = function (promises) {
  10552. var newPromise = new InternalPromise();
  10553. var agregator = new FulFillmentAgregator();
  10554. agregator.target = promises.length;
  10555. agregator.rootPromise = newPromise;
  10556. if (promises.length) {
  10557. for (var index = 0; index < promises.length; index++) {
  10558. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10559. }
  10560. }
  10561. else {
  10562. newPromise._resolve([]);
  10563. }
  10564. return newPromise;
  10565. };
  10566. InternalPromise.race = function (promises) {
  10567. var newPromise = new InternalPromise();
  10568. if (promises.length) {
  10569. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10570. var promise = promises_1[_i];
  10571. promise.then(function (value) {
  10572. if (newPromise) {
  10573. newPromise._resolve(value);
  10574. newPromise = null;
  10575. }
  10576. return null;
  10577. }, function (reason) {
  10578. if (newPromise) {
  10579. newPromise._reject(reason);
  10580. newPromise = null;
  10581. }
  10582. });
  10583. }
  10584. }
  10585. return newPromise;
  10586. };
  10587. return InternalPromise;
  10588. }());
  10589. /**
  10590. * Helper class that provides a small promise polyfill
  10591. */
  10592. var PromisePolyfill = /** @class */ (function () {
  10593. function PromisePolyfill() {
  10594. }
  10595. /**
  10596. * Static function used to check if the polyfill is required
  10597. * If this is the case then the function will inject the polyfill to window.Promise
  10598. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10599. */
  10600. PromisePolyfill.Apply = function (force) {
  10601. if (force === void 0) { force = false; }
  10602. if (force || typeof Promise === 'undefined') {
  10603. var root = window;
  10604. root.Promise = InternalPromise;
  10605. }
  10606. };
  10607. return PromisePolyfill;
  10608. }());
  10609. BABYLON.PromisePolyfill = PromisePolyfill;
  10610. })(BABYLON || (BABYLON = {}));
  10611. //# sourceMappingURL=babylon.promise.js.map
  10612. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10613. var BABYLON;
  10614. (function (BABYLON) {
  10615. /**
  10616. * Helper class to push actions to a pool of workers.
  10617. */
  10618. var WorkerPool = /** @class */ (function () {
  10619. /**
  10620. * Constructor
  10621. * @param workers Array of workers to use for actions
  10622. */
  10623. function WorkerPool(workers) {
  10624. this._pendingActions = new Array();
  10625. this._workerInfos = workers.map(function (worker) { return ({
  10626. worker: worker,
  10627. active: false
  10628. }); });
  10629. }
  10630. /**
  10631. * Terminates all workers and clears any pending actions.
  10632. */
  10633. WorkerPool.prototype.dispose = function () {
  10634. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10635. var workerInfo = _a[_i];
  10636. workerInfo.worker.terminate();
  10637. }
  10638. delete this._workerInfos;
  10639. delete this._pendingActions;
  10640. };
  10641. /**
  10642. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10643. * pended until a worker has completed its action.
  10644. * @param action The action to perform. Call onComplete when the action is complete.
  10645. */
  10646. WorkerPool.prototype.push = function (action) {
  10647. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10648. var workerInfo = _a[_i];
  10649. if (!workerInfo.active) {
  10650. this._execute(workerInfo, action);
  10651. return;
  10652. }
  10653. }
  10654. this._pendingActions.push(action);
  10655. };
  10656. WorkerPool.prototype._execute = function (workerInfo, action) {
  10657. var _this = this;
  10658. workerInfo.active = true;
  10659. action(workerInfo.worker, function () {
  10660. workerInfo.active = false;
  10661. var nextAction = _this._pendingActions.shift();
  10662. if (nextAction) {
  10663. _this._execute(workerInfo, nextAction);
  10664. }
  10665. });
  10666. };
  10667. return WorkerPool;
  10668. }());
  10669. BABYLON.WorkerPool = WorkerPool;
  10670. })(BABYLON || (BABYLON = {}));
  10671. //# sourceMappingURL=babylon.workerPool.js.map
  10672. var BABYLON;
  10673. (function (BABYLON) {
  10674. /**
  10675. * @hidden
  10676. **/
  10677. var _AlphaState = /** @class */ (function () {
  10678. /**
  10679. * Initializes the state.
  10680. */
  10681. function _AlphaState() {
  10682. this._isAlphaBlendDirty = false;
  10683. this._isBlendFunctionParametersDirty = false;
  10684. this._isBlendEquationParametersDirty = false;
  10685. this._isBlendConstantsDirty = false;
  10686. this._alphaBlend = false;
  10687. this._blendFunctionParameters = new Array(4);
  10688. this._blendEquationParameters = new Array(2);
  10689. this._blendConstants = new Array(4);
  10690. this.reset();
  10691. }
  10692. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10693. get: function () {
  10694. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10695. },
  10696. enumerable: true,
  10697. configurable: true
  10698. });
  10699. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10700. get: function () {
  10701. return this._alphaBlend;
  10702. },
  10703. set: function (value) {
  10704. if (this._alphaBlend === value) {
  10705. return;
  10706. }
  10707. this._alphaBlend = value;
  10708. this._isAlphaBlendDirty = true;
  10709. },
  10710. enumerable: true,
  10711. configurable: true
  10712. });
  10713. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10714. if (this._blendConstants[0] === r &&
  10715. this._blendConstants[1] === g &&
  10716. this._blendConstants[2] === b &&
  10717. this._blendConstants[3] === a) {
  10718. return;
  10719. }
  10720. this._blendConstants[0] = r;
  10721. this._blendConstants[1] = g;
  10722. this._blendConstants[2] = b;
  10723. this._blendConstants[3] = a;
  10724. this._isBlendConstantsDirty = true;
  10725. };
  10726. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10727. if (this._blendFunctionParameters[0] === value0 &&
  10728. this._blendFunctionParameters[1] === value1 &&
  10729. this._blendFunctionParameters[2] === value2 &&
  10730. this._blendFunctionParameters[3] === value3) {
  10731. return;
  10732. }
  10733. this._blendFunctionParameters[0] = value0;
  10734. this._blendFunctionParameters[1] = value1;
  10735. this._blendFunctionParameters[2] = value2;
  10736. this._blendFunctionParameters[3] = value3;
  10737. this._isBlendFunctionParametersDirty = true;
  10738. };
  10739. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10740. if (this._blendEquationParameters[0] === rgb &&
  10741. this._blendEquationParameters[1] === alpha) {
  10742. return;
  10743. }
  10744. this._blendEquationParameters[0] = rgb;
  10745. this._blendEquationParameters[1] = alpha;
  10746. this._isBlendEquationParametersDirty = true;
  10747. };
  10748. _AlphaState.prototype.reset = function () {
  10749. this._alphaBlend = false;
  10750. this._blendFunctionParameters[0] = null;
  10751. this._blendFunctionParameters[1] = null;
  10752. this._blendFunctionParameters[2] = null;
  10753. this._blendFunctionParameters[3] = null;
  10754. this._blendEquationParameters[0] = null;
  10755. this._blendEquationParameters[1] = null;
  10756. this._blendConstants[0] = null;
  10757. this._blendConstants[1] = null;
  10758. this._blendConstants[2] = null;
  10759. this._blendConstants[3] = null;
  10760. this._isAlphaBlendDirty = true;
  10761. this._isBlendFunctionParametersDirty = false;
  10762. this._isBlendEquationParametersDirty = false;
  10763. this._isBlendConstantsDirty = false;
  10764. };
  10765. _AlphaState.prototype.apply = function (gl) {
  10766. if (!this.isDirty) {
  10767. return;
  10768. }
  10769. // Alpha blend
  10770. if (this._isAlphaBlendDirty) {
  10771. if (this._alphaBlend) {
  10772. gl.enable(gl.BLEND);
  10773. }
  10774. else {
  10775. gl.disable(gl.BLEND);
  10776. }
  10777. this._isAlphaBlendDirty = false;
  10778. }
  10779. // Alpha function
  10780. if (this._isBlendFunctionParametersDirty) {
  10781. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10782. this._isBlendFunctionParametersDirty = false;
  10783. }
  10784. // Alpha equation
  10785. if (this._isBlendEquationParametersDirty) {
  10786. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10787. this._isBlendEquationParametersDirty = false;
  10788. }
  10789. // Constants
  10790. if (this._isBlendConstantsDirty) {
  10791. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10792. this._isBlendConstantsDirty = false;
  10793. }
  10794. };
  10795. return _AlphaState;
  10796. }());
  10797. BABYLON._AlphaState = _AlphaState;
  10798. })(BABYLON || (BABYLON = {}));
  10799. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10800. var BABYLON;
  10801. (function (BABYLON) {
  10802. /**
  10803. * @hidden
  10804. **/
  10805. var _DepthCullingState = /** @class */ (function () {
  10806. /**
  10807. * Initializes the state.
  10808. */
  10809. function _DepthCullingState() {
  10810. this._isDepthTestDirty = false;
  10811. this._isDepthMaskDirty = false;
  10812. this._isDepthFuncDirty = false;
  10813. this._isCullFaceDirty = false;
  10814. this._isCullDirty = false;
  10815. this._isZOffsetDirty = false;
  10816. this._isFrontFaceDirty = false;
  10817. this.reset();
  10818. }
  10819. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10820. get: function () {
  10821. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10822. },
  10823. enumerable: true,
  10824. configurable: true
  10825. });
  10826. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10827. get: function () {
  10828. return this._zOffset;
  10829. },
  10830. set: function (value) {
  10831. if (this._zOffset === value) {
  10832. return;
  10833. }
  10834. this._zOffset = value;
  10835. this._isZOffsetDirty = true;
  10836. },
  10837. enumerable: true,
  10838. configurable: true
  10839. });
  10840. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10841. get: function () {
  10842. return this._cullFace;
  10843. },
  10844. set: function (value) {
  10845. if (this._cullFace === value) {
  10846. return;
  10847. }
  10848. this._cullFace = value;
  10849. this._isCullFaceDirty = true;
  10850. },
  10851. enumerable: true,
  10852. configurable: true
  10853. });
  10854. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10855. get: function () {
  10856. return this._cull;
  10857. },
  10858. set: function (value) {
  10859. if (this._cull === value) {
  10860. return;
  10861. }
  10862. this._cull = value;
  10863. this._isCullDirty = true;
  10864. },
  10865. enumerable: true,
  10866. configurable: true
  10867. });
  10868. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10869. get: function () {
  10870. return this._depthFunc;
  10871. },
  10872. set: function (value) {
  10873. if (this._depthFunc === value) {
  10874. return;
  10875. }
  10876. this._depthFunc = value;
  10877. this._isDepthFuncDirty = true;
  10878. },
  10879. enumerable: true,
  10880. configurable: true
  10881. });
  10882. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10883. get: function () {
  10884. return this._depthMask;
  10885. },
  10886. set: function (value) {
  10887. if (this._depthMask === value) {
  10888. return;
  10889. }
  10890. this._depthMask = value;
  10891. this._isDepthMaskDirty = true;
  10892. },
  10893. enumerable: true,
  10894. configurable: true
  10895. });
  10896. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10897. get: function () {
  10898. return this._depthTest;
  10899. },
  10900. set: function (value) {
  10901. if (this._depthTest === value) {
  10902. return;
  10903. }
  10904. this._depthTest = value;
  10905. this._isDepthTestDirty = true;
  10906. },
  10907. enumerable: true,
  10908. configurable: true
  10909. });
  10910. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10911. get: function () {
  10912. return this._frontFace;
  10913. },
  10914. set: function (value) {
  10915. if (this._frontFace === value) {
  10916. return;
  10917. }
  10918. this._frontFace = value;
  10919. this._isFrontFaceDirty = true;
  10920. },
  10921. enumerable: true,
  10922. configurable: true
  10923. });
  10924. _DepthCullingState.prototype.reset = function () {
  10925. this._depthMask = true;
  10926. this._depthTest = true;
  10927. this._depthFunc = null;
  10928. this._cullFace = null;
  10929. this._cull = null;
  10930. this._zOffset = 0;
  10931. this._frontFace = null;
  10932. this._isDepthTestDirty = true;
  10933. this._isDepthMaskDirty = true;
  10934. this._isDepthFuncDirty = false;
  10935. this._isCullFaceDirty = false;
  10936. this._isCullDirty = false;
  10937. this._isZOffsetDirty = false;
  10938. this._isFrontFaceDirty = false;
  10939. };
  10940. _DepthCullingState.prototype.apply = function (gl) {
  10941. if (!this.isDirty) {
  10942. return;
  10943. }
  10944. // Cull
  10945. if (this._isCullDirty) {
  10946. if (this.cull) {
  10947. gl.enable(gl.CULL_FACE);
  10948. }
  10949. else {
  10950. gl.disable(gl.CULL_FACE);
  10951. }
  10952. this._isCullDirty = false;
  10953. }
  10954. // Cull face
  10955. if (this._isCullFaceDirty) {
  10956. gl.cullFace(this.cullFace);
  10957. this._isCullFaceDirty = false;
  10958. }
  10959. // Depth mask
  10960. if (this._isDepthMaskDirty) {
  10961. gl.depthMask(this.depthMask);
  10962. this._isDepthMaskDirty = false;
  10963. }
  10964. // Depth test
  10965. if (this._isDepthTestDirty) {
  10966. if (this.depthTest) {
  10967. gl.enable(gl.DEPTH_TEST);
  10968. }
  10969. else {
  10970. gl.disable(gl.DEPTH_TEST);
  10971. }
  10972. this._isDepthTestDirty = false;
  10973. }
  10974. // Depth func
  10975. if (this._isDepthFuncDirty) {
  10976. gl.depthFunc(this.depthFunc);
  10977. this._isDepthFuncDirty = false;
  10978. }
  10979. // zOffset
  10980. if (this._isZOffsetDirty) {
  10981. if (this.zOffset) {
  10982. gl.enable(gl.POLYGON_OFFSET_FILL);
  10983. gl.polygonOffset(this.zOffset, 0);
  10984. }
  10985. else {
  10986. gl.disable(gl.POLYGON_OFFSET_FILL);
  10987. }
  10988. this._isZOffsetDirty = false;
  10989. }
  10990. // Front face
  10991. if (this._isFrontFaceDirty) {
  10992. gl.frontFace(this.frontFace);
  10993. this._isFrontFaceDirty = false;
  10994. }
  10995. };
  10996. return _DepthCullingState;
  10997. }());
  10998. BABYLON._DepthCullingState = _DepthCullingState;
  10999. })(BABYLON || (BABYLON = {}));
  11000. //# sourceMappingURL=babylon.depthCullingState.js.map
  11001. var BABYLON;
  11002. (function (BABYLON) {
  11003. /**
  11004. * @hidden
  11005. **/
  11006. var _StencilState = /** @class */ (function () {
  11007. function _StencilState() {
  11008. this._isStencilTestDirty = false;
  11009. this._isStencilMaskDirty = false;
  11010. this._isStencilFuncDirty = false;
  11011. this._isStencilOpDirty = false;
  11012. this.reset();
  11013. }
  11014. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11015. get: function () {
  11016. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11022. get: function () {
  11023. return this._stencilFunc;
  11024. },
  11025. set: function (value) {
  11026. if (this._stencilFunc === value) {
  11027. return;
  11028. }
  11029. this._stencilFunc = value;
  11030. this._isStencilFuncDirty = true;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11036. get: function () {
  11037. return this._stencilFuncRef;
  11038. },
  11039. set: function (value) {
  11040. if (this._stencilFuncRef === value) {
  11041. return;
  11042. }
  11043. this._stencilFuncRef = value;
  11044. this._isStencilFuncDirty = true;
  11045. },
  11046. enumerable: true,
  11047. configurable: true
  11048. });
  11049. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11050. get: function () {
  11051. return this._stencilFuncMask;
  11052. },
  11053. set: function (value) {
  11054. if (this._stencilFuncMask === value) {
  11055. return;
  11056. }
  11057. this._stencilFuncMask = value;
  11058. this._isStencilFuncDirty = true;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11064. get: function () {
  11065. return this._stencilOpStencilFail;
  11066. },
  11067. set: function (value) {
  11068. if (this._stencilOpStencilFail === value) {
  11069. return;
  11070. }
  11071. this._stencilOpStencilFail = value;
  11072. this._isStencilOpDirty = true;
  11073. },
  11074. enumerable: true,
  11075. configurable: true
  11076. });
  11077. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11078. get: function () {
  11079. return this._stencilOpDepthFail;
  11080. },
  11081. set: function (value) {
  11082. if (this._stencilOpDepthFail === value) {
  11083. return;
  11084. }
  11085. this._stencilOpDepthFail = value;
  11086. this._isStencilOpDirty = true;
  11087. },
  11088. enumerable: true,
  11089. configurable: true
  11090. });
  11091. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11092. get: function () {
  11093. return this._stencilOpStencilDepthPass;
  11094. },
  11095. set: function (value) {
  11096. if (this._stencilOpStencilDepthPass === value) {
  11097. return;
  11098. }
  11099. this._stencilOpStencilDepthPass = value;
  11100. this._isStencilOpDirty = true;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11106. get: function () {
  11107. return this._stencilMask;
  11108. },
  11109. set: function (value) {
  11110. if (this._stencilMask === value) {
  11111. return;
  11112. }
  11113. this._stencilMask = value;
  11114. this._isStencilMaskDirty = true;
  11115. },
  11116. enumerable: true,
  11117. configurable: true
  11118. });
  11119. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11120. get: function () {
  11121. return this._stencilTest;
  11122. },
  11123. set: function (value) {
  11124. if (this._stencilTest === value) {
  11125. return;
  11126. }
  11127. this._stencilTest = value;
  11128. this._isStencilTestDirty = true;
  11129. },
  11130. enumerable: true,
  11131. configurable: true
  11132. });
  11133. _StencilState.prototype.reset = function () {
  11134. this._stencilTest = false;
  11135. this._stencilMask = 0xFF;
  11136. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11137. this._stencilFuncRef = 1;
  11138. this._stencilFuncMask = 0xFF;
  11139. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11140. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11141. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11142. this._isStencilTestDirty = true;
  11143. this._isStencilMaskDirty = true;
  11144. this._isStencilFuncDirty = true;
  11145. this._isStencilOpDirty = true;
  11146. };
  11147. _StencilState.prototype.apply = function (gl) {
  11148. if (!this.isDirty) {
  11149. return;
  11150. }
  11151. // Stencil test
  11152. if (this._isStencilTestDirty) {
  11153. if (this.stencilTest) {
  11154. gl.enable(gl.STENCIL_TEST);
  11155. }
  11156. else {
  11157. gl.disable(gl.STENCIL_TEST);
  11158. }
  11159. this._isStencilTestDirty = false;
  11160. }
  11161. // Stencil mask
  11162. if (this._isStencilMaskDirty) {
  11163. gl.stencilMask(this.stencilMask);
  11164. this._isStencilMaskDirty = false;
  11165. }
  11166. // Stencil func
  11167. if (this._isStencilFuncDirty) {
  11168. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11169. this._isStencilFuncDirty = false;
  11170. }
  11171. // Stencil op
  11172. if (this._isStencilOpDirty) {
  11173. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11174. this._isStencilOpDirty = false;
  11175. }
  11176. };
  11177. return _StencilState;
  11178. }());
  11179. BABYLON._StencilState = _StencilState;
  11180. })(BABYLON || (BABYLON = {}));
  11181. //# sourceMappingURL=babylon.stencilState.js.map
  11182. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11183. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11184. s = arguments[i];
  11185. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11186. t[p] = s[p];
  11187. }
  11188. return t;
  11189. };
  11190. var BABYLON;
  11191. (function (BABYLON) {
  11192. /**
  11193. * Keeps track of all the buffer info used in engine.
  11194. */
  11195. var BufferPointer = /** @class */ (function () {
  11196. function BufferPointer() {
  11197. }
  11198. return BufferPointer;
  11199. }());
  11200. /**
  11201. * Interface for attribute information associated with buffer instanciation
  11202. */
  11203. var InstancingAttributeInfo = /** @class */ (function () {
  11204. function InstancingAttributeInfo() {
  11205. }
  11206. return InstancingAttributeInfo;
  11207. }());
  11208. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11209. /**
  11210. * Define options used to create a render target texture
  11211. */
  11212. var RenderTargetCreationOptions = /** @class */ (function () {
  11213. function RenderTargetCreationOptions() {
  11214. }
  11215. return RenderTargetCreationOptions;
  11216. }());
  11217. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11218. /**
  11219. * Define options used to create a depth texture
  11220. */
  11221. var DepthTextureCreationOptions = /** @class */ (function () {
  11222. function DepthTextureCreationOptions() {
  11223. }
  11224. return DepthTextureCreationOptions;
  11225. }());
  11226. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11227. /**
  11228. * Class used to describe the capabilities of the engine relatively to the current browser
  11229. */
  11230. var EngineCapabilities = /** @class */ (function () {
  11231. function EngineCapabilities() {
  11232. }
  11233. return EngineCapabilities;
  11234. }());
  11235. BABYLON.EngineCapabilities = EngineCapabilities;
  11236. /**
  11237. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11238. */
  11239. var Engine = /** @class */ (function () {
  11240. /**
  11241. * Creates a new engine
  11242. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11243. * @param antialias defines enable antialiasing (default: false)
  11244. * @param options defines further options to be sent to the getContext() function
  11245. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11246. */
  11247. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11248. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11249. var _this = this;
  11250. // Public members
  11251. /**
  11252. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11253. */
  11254. this.forcePOTTextures = false;
  11255. /**
  11256. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11257. */
  11258. this.isFullscreen = false;
  11259. /**
  11260. * Gets a boolean indicating if the pointer is currently locked
  11261. */
  11262. this.isPointerLock = false;
  11263. /**
  11264. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11265. */
  11266. this.cullBackFaces = true;
  11267. /**
  11268. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11269. */
  11270. this.renderEvenInBackground = true;
  11271. /**
  11272. * Gets or sets a boolean indicating that cache can be kept between frames
  11273. */
  11274. this.preventCacheWipeBetweenFrames = false;
  11275. /**
  11276. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11277. **/
  11278. this.enableOfflineSupport = false;
  11279. /**
  11280. * 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)
  11281. **/
  11282. this.disableManifestCheck = false;
  11283. /**
  11284. * Gets the list of created scenes
  11285. */
  11286. this.scenes = new Array();
  11287. /**
  11288. * Gets the list of created postprocesses
  11289. */
  11290. this.postProcesses = new Array();
  11291. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11292. this.validateShaderPrograms = false;
  11293. // Observables
  11294. /**
  11295. * Observable event triggered each time the rendering canvas is resized
  11296. */
  11297. this.onResizeObservable = new BABYLON.Observable();
  11298. /**
  11299. * Observable event triggered each time the canvas loses focus
  11300. */
  11301. this.onCanvasBlurObservable = new BABYLON.Observable();
  11302. /**
  11303. * Observable event triggered each time the canvas gains focus
  11304. */
  11305. this.onCanvasFocusObservable = new BABYLON.Observable();
  11306. /**
  11307. * Observable event triggered each time the canvas receives pointerout event
  11308. */
  11309. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11310. /**
  11311. * Observable event triggered before each texture is initialized
  11312. */
  11313. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11314. //WebVR
  11315. this._vrDisplay = undefined;
  11316. this._vrSupported = false;
  11317. this._vrExclusivePointerMode = false;
  11318. // Uniform buffers list
  11319. /**
  11320. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11321. */
  11322. this.disableUniformBuffers = false;
  11323. /** @hidden */
  11324. this._uniformBuffers = new Array();
  11325. // Observables
  11326. /**
  11327. * Observable raised when the engine begins a new frame
  11328. */
  11329. this.onBeginFrameObservable = new BABYLON.Observable();
  11330. /**
  11331. * Observable raised when the engine ends the current frame
  11332. */
  11333. this.onEndFrameObservable = new BABYLON.Observable();
  11334. /**
  11335. * Observable raised when the engine is about to compile a shader
  11336. */
  11337. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11338. /**
  11339. * Observable raised when the engine has jsut compiled a shader
  11340. */
  11341. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11342. this._windowIsBackground = false;
  11343. this._webGLVersion = 1.0;
  11344. /** @hidden */
  11345. this._badOS = false;
  11346. /** @hidden */
  11347. this._badDesktopOS = false;
  11348. /**
  11349. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11350. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11351. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11352. */
  11353. this.disableTextureBindingOptimization = false;
  11354. /**
  11355. * Observable signaled when VR display mode changes
  11356. */
  11357. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11358. /**
  11359. * Observable signaled when VR request present is complete
  11360. */
  11361. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11362. /**
  11363. * Observable signaled when VR request present starts
  11364. */
  11365. this.onVRRequestPresentStart = new BABYLON.Observable();
  11366. this._colorWrite = true;
  11367. /** @hidden */
  11368. this._drawCalls = new BABYLON.PerfCounter();
  11369. /** @hidden */
  11370. this._textureCollisions = new BABYLON.PerfCounter();
  11371. this._renderingQueueLaunched = false;
  11372. this._activeRenderLoops = new Array();
  11373. // Deterministic lockstepMaxSteps
  11374. this._deterministicLockstep = false;
  11375. this._lockstepMaxSteps = 4;
  11376. // Lost context
  11377. /**
  11378. * Observable signaled when a context lost event is raised
  11379. */
  11380. this.onContextLostObservable = new BABYLON.Observable();
  11381. /**
  11382. * Observable signaled when a context restored event is raised
  11383. */
  11384. this.onContextRestoredObservable = new BABYLON.Observable();
  11385. this._contextWasLost = false;
  11386. this._doNotHandleContextLost = false;
  11387. // FPS
  11388. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11389. this._fps = 60;
  11390. this._deltaTime = 0;
  11391. /**
  11392. * Turn this value on if you want to pause FPS computation when in background
  11393. */
  11394. this.disablePerformanceMonitorInBackground = false;
  11395. // States
  11396. /** @hidden */
  11397. this._depthCullingState = new BABYLON._DepthCullingState();
  11398. /** @hidden */
  11399. this._stencilState = new BABYLON._StencilState();
  11400. /** @hidden */
  11401. this._alphaState = new BABYLON._AlphaState();
  11402. /** @hidden */
  11403. this._alphaMode = Engine.ALPHA_DISABLE;
  11404. // Cache
  11405. this._internalTexturesCache = new Array();
  11406. /** @hidden */
  11407. this._activeChannel = 0;
  11408. this._currentTextureChannel = -1;
  11409. /** @hidden */
  11410. this._boundTexturesCache = {};
  11411. this._compiledEffects = {};
  11412. this._vertexAttribArraysEnabled = [];
  11413. this._uintIndicesCurrentlySet = false;
  11414. this._currentBoundBuffer = new Array();
  11415. /** @hidden */
  11416. this._currentFramebuffer = null;
  11417. this._currentBufferPointers = new Array();
  11418. this._currentInstanceLocations = new Array();
  11419. this._currentInstanceBuffers = new Array();
  11420. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11421. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11422. this._vaoRecordInProgress = false;
  11423. this._mustWipeVertexAttributes = false;
  11424. this._nextFreeTextureSlots = new Array();
  11425. this._maxSimultaneousTextures = 0;
  11426. this._activeRequests = new Array();
  11427. // Hardware supported Compressed Textures
  11428. this._texturesSupported = new Array();
  11429. /**
  11430. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11431. */
  11432. this.premultipliedAlpha = true;
  11433. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11434. this._onVRFullScreenTriggered = function () {
  11435. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11436. //get the old size before we change
  11437. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11438. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11439. //get the width and height, change the render size
  11440. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11441. _this.setHardwareScalingLevel(1);
  11442. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11443. }
  11444. else {
  11445. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11446. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11447. }
  11448. };
  11449. this._unpackFlipYCached = null;
  11450. this._boundUniforms = {};
  11451. // Register promises
  11452. BABYLON.PromisePolyfill.Apply();
  11453. var canvas = null;
  11454. Engine.Instances.push(this);
  11455. if (!canvasOrContext) {
  11456. return;
  11457. }
  11458. options = options || {};
  11459. if (canvasOrContext.getContext) {
  11460. canvas = canvasOrContext;
  11461. this._renderingCanvas = canvas;
  11462. if (antialias != null) {
  11463. options.antialias = antialias;
  11464. }
  11465. if (options.deterministicLockstep === undefined) {
  11466. options.deterministicLockstep = false;
  11467. }
  11468. if (options.lockstepMaxSteps === undefined) {
  11469. options.lockstepMaxSteps = 4;
  11470. }
  11471. if (options.preserveDrawingBuffer === undefined) {
  11472. options.preserveDrawingBuffer = false;
  11473. }
  11474. if (options.audioEngine === undefined) {
  11475. options.audioEngine = true;
  11476. }
  11477. if (options.stencil === undefined) {
  11478. options.stencil = true;
  11479. }
  11480. if (options.premultipliedAlpha === false) {
  11481. this.premultipliedAlpha = false;
  11482. }
  11483. this._deterministicLockstep = options.deterministicLockstep;
  11484. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11485. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11486. // Exceptions
  11487. if (navigator && navigator.userAgent) {
  11488. var ua = navigator.userAgent;
  11489. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11490. var exception = _a[_i];
  11491. var key = exception.key;
  11492. var targets = exception.targets;
  11493. if (ua.indexOf(key) > -1) {
  11494. if (exception.capture && exception.captureConstraint) {
  11495. var capture = exception.capture;
  11496. var constraint = exception.captureConstraint;
  11497. var regex = new RegExp(capture);
  11498. var matches = regex.exec(ua);
  11499. if (matches && matches.length > 0) {
  11500. var capturedValue = parseInt(matches[matches.length - 1]);
  11501. if (capturedValue >= constraint) {
  11502. continue;
  11503. }
  11504. }
  11505. }
  11506. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11507. var target = targets_1[_b];
  11508. switch (target) {
  11509. case "uniformBuffer":
  11510. this.disableUniformBuffers = true;
  11511. break;
  11512. case "textureBindingOptimization":
  11513. this.disableTextureBindingOptimization = true;
  11514. break;
  11515. }
  11516. }
  11517. }
  11518. }
  11519. }
  11520. // GL
  11521. if (!options.disableWebGL2Support) {
  11522. try {
  11523. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11524. if (this._gl) {
  11525. this._webGLVersion = 2.0;
  11526. }
  11527. }
  11528. catch (e) {
  11529. // Do nothing
  11530. }
  11531. }
  11532. if (!this._gl) {
  11533. if (!canvas) {
  11534. throw new Error("The provided canvas is null or undefined.");
  11535. }
  11536. try {
  11537. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11538. }
  11539. catch (e) {
  11540. throw new Error("WebGL not supported");
  11541. }
  11542. }
  11543. if (!this._gl) {
  11544. throw new Error("WebGL not supported");
  11545. }
  11546. this._onCanvasFocus = function () {
  11547. _this.onCanvasFocusObservable.notifyObservers(_this);
  11548. };
  11549. this._onCanvasBlur = function () {
  11550. _this.onCanvasBlurObservable.notifyObservers(_this);
  11551. };
  11552. canvas.addEventListener("focus", this._onCanvasFocus);
  11553. canvas.addEventListener("blur", this._onCanvasBlur);
  11554. this._onBlur = function () {
  11555. if (_this.disablePerformanceMonitorInBackground) {
  11556. _this._performanceMonitor.disable();
  11557. }
  11558. _this._windowIsBackground = true;
  11559. };
  11560. this._onFocus = function () {
  11561. if (_this.disablePerformanceMonitorInBackground) {
  11562. _this._performanceMonitor.enable();
  11563. }
  11564. _this._windowIsBackground = false;
  11565. };
  11566. this._onCanvasPointerOut = function (ev) {
  11567. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11568. };
  11569. window.addEventListener("blur", this._onBlur);
  11570. window.addEventListener("focus", this._onFocus);
  11571. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11572. // Context lost
  11573. if (!this._doNotHandleContextLost) {
  11574. this._onContextLost = function (evt) {
  11575. evt.preventDefault();
  11576. _this._contextWasLost = true;
  11577. BABYLON.Tools.Warn("WebGL context lost.");
  11578. _this.onContextLostObservable.notifyObservers(_this);
  11579. };
  11580. this._onContextRestored = function (evt) {
  11581. // Adding a timeout to avoid race condition at browser level
  11582. setTimeout(function () {
  11583. // Rebuild gl context
  11584. _this._initGLContext();
  11585. // Rebuild effects
  11586. _this._rebuildEffects();
  11587. // Rebuild textures
  11588. _this._rebuildInternalTextures();
  11589. // Rebuild buffers
  11590. _this._rebuildBuffers();
  11591. // Cache
  11592. _this.wipeCaches(true);
  11593. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11594. _this.onContextRestoredObservable.notifyObservers(_this);
  11595. _this._contextWasLost = false;
  11596. }, 0);
  11597. };
  11598. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11599. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11600. }
  11601. }
  11602. else {
  11603. this._gl = canvasOrContext;
  11604. this._renderingCanvas = this._gl.canvas;
  11605. if (this._gl.renderbufferStorageMultisample) {
  11606. this._webGLVersion = 2.0;
  11607. }
  11608. options.stencil = this._gl.getContextAttributes().stencil;
  11609. }
  11610. // Viewport
  11611. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11612. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11613. this.resize();
  11614. this._isStencilEnable = options.stencil ? true : false;
  11615. this._initGLContext();
  11616. if (canvas) {
  11617. // Fullscreen
  11618. this._onFullscreenChange = function () {
  11619. if (document.fullscreen !== undefined) {
  11620. _this.isFullscreen = document.fullscreen;
  11621. }
  11622. else if (document.mozFullScreen !== undefined) {
  11623. _this.isFullscreen = document.mozFullScreen;
  11624. }
  11625. else if (document.webkitIsFullScreen !== undefined) {
  11626. _this.isFullscreen = document.webkitIsFullScreen;
  11627. }
  11628. else if (document.msIsFullScreen !== undefined) {
  11629. _this.isFullscreen = document.msIsFullScreen;
  11630. }
  11631. // Pointer lock
  11632. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11633. canvas.requestPointerLock = canvas.requestPointerLock ||
  11634. canvas.msRequestPointerLock ||
  11635. canvas.mozRequestPointerLock ||
  11636. canvas.webkitRequestPointerLock;
  11637. if (canvas.requestPointerLock) {
  11638. canvas.requestPointerLock();
  11639. }
  11640. }
  11641. };
  11642. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11643. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11644. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11645. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11646. // Pointer lock
  11647. this._onPointerLockChange = function () {
  11648. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11649. document.webkitPointerLockElement === canvas ||
  11650. document.msPointerLockElement === canvas ||
  11651. document.pointerLockElement === canvas);
  11652. };
  11653. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11654. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11655. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11656. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11657. this._onVRDisplayPointerRestricted = function () {
  11658. if (canvas) {
  11659. canvas.requestPointerLock();
  11660. }
  11661. };
  11662. this._onVRDisplayPointerUnrestricted = function () {
  11663. document.exitPointerLock();
  11664. };
  11665. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11666. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11667. }
  11668. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11669. Engine.audioEngine = new BABYLON.AudioEngine();
  11670. }
  11671. // Prepare buffer pointers
  11672. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11673. this._currentBufferPointers[i] = new BufferPointer();
  11674. }
  11675. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11676. // Load WebVR Devices
  11677. if (options.autoEnableWebVR) {
  11678. this.initWebVR();
  11679. }
  11680. // Detect if we are running on a faulty buggy OS.
  11681. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11682. // Detect if we are running on a faulty buggy desktop OS.
  11683. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11684. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11685. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11686. }
  11687. Object.defineProperty(Engine, "LastCreatedEngine", {
  11688. /**
  11689. * Gets the latest created engine
  11690. */
  11691. get: function () {
  11692. if (Engine.Instances.length === 0) {
  11693. return null;
  11694. }
  11695. return Engine.Instances[Engine.Instances.length - 1];
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(Engine, "LastCreatedScene", {
  11701. /**
  11702. * Gets the latest created scene
  11703. */
  11704. get: function () {
  11705. var lastCreatedEngine = Engine.LastCreatedEngine;
  11706. if (!lastCreatedEngine) {
  11707. return null;
  11708. }
  11709. if (lastCreatedEngine.scenes.length === 0) {
  11710. return null;
  11711. }
  11712. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11713. },
  11714. enumerable: true,
  11715. configurable: true
  11716. });
  11717. /**
  11718. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11719. * @param flag defines which part of the materials must be marked as dirty
  11720. * @param predicate defines a predicate used to filter which materials should be affected
  11721. */
  11722. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11723. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11724. var engine = Engine.Instances[engineIndex];
  11725. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11726. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11727. }
  11728. }
  11729. };
  11730. Object.defineProperty(Engine, "Version", {
  11731. /**
  11732. * Returns the current version of the framework
  11733. */
  11734. get: function () {
  11735. return "3.3.0-alpha.13";
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11741. /**
  11742. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11743. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11744. */
  11745. get: function () {
  11746. return this._vrExclusivePointerMode;
  11747. },
  11748. enumerable: true,
  11749. configurable: true
  11750. });
  11751. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11752. /**
  11753. * Gets a boolean indicating that the engine supports uniform buffers
  11754. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11755. */
  11756. get: function () {
  11757. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11758. },
  11759. enumerable: true,
  11760. configurable: true
  11761. });
  11762. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11763. /**
  11764. * Gets a boolean indicating that only power of 2 textures are supported
  11765. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11766. */
  11767. get: function () {
  11768. return this._webGLVersion < 2 || this.forcePOTTextures;
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11774. /**
  11775. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11776. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11777. */
  11778. get: function () {
  11779. return this._doNotHandleContextLost;
  11780. },
  11781. set: function (value) {
  11782. this._doNotHandleContextLost = value;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11788. /**
  11789. * Gets the performance monitor attached to this engine
  11790. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11791. */
  11792. get: function () {
  11793. return this._performanceMonitor;
  11794. },
  11795. enumerable: true,
  11796. configurable: true
  11797. });
  11798. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11799. /**
  11800. * Gets the list of texture formats supported
  11801. */
  11802. get: function () {
  11803. return this._texturesSupported;
  11804. },
  11805. enumerable: true,
  11806. configurable: true
  11807. });
  11808. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11809. /**
  11810. * Gets the list of texture formats in use
  11811. */
  11812. get: function () {
  11813. return this._textureFormatInUse;
  11814. },
  11815. enumerable: true,
  11816. configurable: true
  11817. });
  11818. Object.defineProperty(Engine.prototype, "currentViewport", {
  11819. /**
  11820. * Gets the current viewport
  11821. */
  11822. get: function () {
  11823. return this._cachedViewport;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11829. /**
  11830. * Gets the default empty texture
  11831. */
  11832. get: function () {
  11833. if (!this._emptyTexture) {
  11834. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11835. }
  11836. return this._emptyTexture;
  11837. },
  11838. enumerable: true,
  11839. configurable: true
  11840. });
  11841. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11842. /**
  11843. * Gets the default empty 3D texture
  11844. */
  11845. get: function () {
  11846. if (!this._emptyTexture3D) {
  11847. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11848. }
  11849. return this._emptyTexture3D;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11855. /**
  11856. * Gets the default empty cube texture
  11857. */
  11858. get: function () {
  11859. if (!this._emptyCubeTexture) {
  11860. var faceData = new Uint8Array(4);
  11861. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11862. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11863. }
  11864. return this._emptyCubeTexture;
  11865. },
  11866. enumerable: true,
  11867. configurable: true
  11868. });
  11869. Engine.prototype._rebuildInternalTextures = function () {
  11870. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11871. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11872. var internalTexture = currentState_1[_i];
  11873. internalTexture._rebuild();
  11874. }
  11875. };
  11876. Engine.prototype._rebuildEffects = function () {
  11877. for (var key in this._compiledEffects) {
  11878. var effect = this._compiledEffects[key];
  11879. effect._prepareEffect();
  11880. }
  11881. BABYLON.Effect.ResetCache();
  11882. };
  11883. Engine.prototype._rebuildBuffers = function () {
  11884. // Index / Vertex
  11885. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11886. var scene = _a[_i];
  11887. scene.resetCachedMaterial();
  11888. scene._rebuildGeometries();
  11889. scene._rebuildTextures();
  11890. }
  11891. // Uniforms
  11892. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11893. var uniformBuffer = _c[_b];
  11894. uniformBuffer._rebuild();
  11895. }
  11896. };
  11897. Engine.prototype._initGLContext = function () {
  11898. // Caps
  11899. this._caps = new EngineCapabilities();
  11900. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11901. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11902. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11903. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11904. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11905. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11906. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11907. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11908. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11909. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11910. // Infos
  11911. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11912. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11913. if (rendererInfo != null) {
  11914. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11915. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11916. }
  11917. if (!this._glVendor) {
  11918. this._glVendor = "Unknown vendor";
  11919. }
  11920. if (!this._glRenderer) {
  11921. this._glRenderer = "Unknown renderer";
  11922. }
  11923. // Constants
  11924. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11925. if (this._gl.RGBA16F !== 0x881A) {
  11926. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11927. }
  11928. if (this._gl.RGBA32F !== 0x8814) {
  11929. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11930. }
  11931. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11932. this._gl.DEPTH24_STENCIL8 = 35056;
  11933. }
  11934. // Extensions
  11935. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11936. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11937. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11938. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11939. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11940. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11941. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11942. 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');
  11943. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11944. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11945. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11946. this._caps.highPrecisionShaderSupported = true;
  11947. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11948. if (this._caps.timerQuery) {
  11949. if (this._webGLVersion === 1) {
  11950. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11951. }
  11952. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11953. }
  11954. // Checks if some of the format renders first to allow the use of webgl inspector.
  11955. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11956. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11957. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11958. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11959. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11960. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11961. if (this._webGLVersion > 1) {
  11962. this._gl.HALF_FLOAT_OES = 0x140B;
  11963. }
  11964. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11965. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11966. // Draw buffers
  11967. if (this._webGLVersion > 1) {
  11968. this._caps.drawBuffersExtension = true;
  11969. }
  11970. else {
  11971. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11972. if (drawBuffersExtension !== null) {
  11973. this._caps.drawBuffersExtension = true;
  11974. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11975. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11976. for (var i = 0; i < 16; i++) {
  11977. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11978. }
  11979. }
  11980. else {
  11981. this._caps.drawBuffersExtension = false;
  11982. }
  11983. }
  11984. // Depth Texture
  11985. if (this._webGLVersion > 1) {
  11986. this._caps.depthTextureExtension = true;
  11987. }
  11988. else {
  11989. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11990. if (depthTextureExtension != null) {
  11991. this._caps.depthTextureExtension = true;
  11992. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11993. }
  11994. }
  11995. // Vertex array object
  11996. if (this._webGLVersion > 1) {
  11997. this._caps.vertexArrayObject = true;
  11998. }
  11999. else {
  12000. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12001. if (vertexArrayObjectExtension != null) {
  12002. this._caps.vertexArrayObject = true;
  12003. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12004. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12005. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12006. }
  12007. else {
  12008. this._caps.vertexArrayObject = false;
  12009. }
  12010. }
  12011. // Instances count
  12012. if (this._webGLVersion > 1) {
  12013. this._caps.instancedArrays = true;
  12014. }
  12015. else {
  12016. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12017. if (instanceExtension != null) {
  12018. this._caps.instancedArrays = true;
  12019. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12020. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12021. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12022. }
  12023. else {
  12024. this._caps.instancedArrays = false;
  12025. }
  12026. }
  12027. // Intelligently add supported compressed formats in order to check for.
  12028. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12029. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12030. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12031. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12032. if (this._caps.astc)
  12033. this.texturesSupported.push('-astc.ktx');
  12034. if (this._caps.s3tc)
  12035. this.texturesSupported.push('-dxt.ktx');
  12036. if (this._caps.pvrtc)
  12037. this.texturesSupported.push('-pvrtc.ktx');
  12038. if (this._caps.etc2)
  12039. this.texturesSupported.push('-etc2.ktx');
  12040. if (this._caps.etc1)
  12041. this.texturesSupported.push('-etc1.ktx');
  12042. if (this._gl.getShaderPrecisionFormat) {
  12043. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12044. if (highp) {
  12045. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12046. }
  12047. }
  12048. // Depth buffer
  12049. this.setDepthBuffer(true);
  12050. this.setDepthFunctionToLessOrEqual();
  12051. this.setDepthWrite(true);
  12052. // Texture maps
  12053. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12054. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12055. this._nextFreeTextureSlots.push(slot);
  12056. }
  12057. };
  12058. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12059. /**
  12060. * Gets version of the current webGL context
  12061. */
  12062. get: function () {
  12063. return this._webGLVersion;
  12064. },
  12065. enumerable: true,
  12066. configurable: true
  12067. });
  12068. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12069. /**
  12070. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12071. */
  12072. get: function () {
  12073. return this._isStencilEnable;
  12074. },
  12075. enumerable: true,
  12076. configurable: true
  12077. });
  12078. Engine.prototype._prepareWorkingCanvas = function () {
  12079. if (this._workingCanvas) {
  12080. return;
  12081. }
  12082. this._workingCanvas = document.createElement("canvas");
  12083. var context = this._workingCanvas.getContext("2d");
  12084. if (context) {
  12085. this._workingContext = context;
  12086. }
  12087. };
  12088. /**
  12089. * Reset the texture cache to empty state
  12090. */
  12091. Engine.prototype.resetTextureCache = function () {
  12092. for (var key in this._boundTexturesCache) {
  12093. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12094. continue;
  12095. }
  12096. var boundTexture = this._boundTexturesCache[key];
  12097. if (boundTexture) {
  12098. this._removeDesignatedSlot(boundTexture);
  12099. }
  12100. this._boundTexturesCache[key] = null;
  12101. }
  12102. if (!this.disableTextureBindingOptimization) {
  12103. this._nextFreeTextureSlots = [];
  12104. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12105. this._nextFreeTextureSlots.push(slot);
  12106. }
  12107. }
  12108. this._currentTextureChannel = -1;
  12109. };
  12110. /**
  12111. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12112. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12113. * @returns true if engine is in deterministic lock step mode
  12114. */
  12115. Engine.prototype.isDeterministicLockStep = function () {
  12116. return this._deterministicLockstep;
  12117. };
  12118. /**
  12119. * Gets the max steps when engine is running in deterministic lock step
  12120. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12121. * @returns the max steps
  12122. */
  12123. Engine.prototype.getLockstepMaxSteps = function () {
  12124. return this._lockstepMaxSteps;
  12125. };
  12126. /**
  12127. * Gets an object containing information about the current webGL context
  12128. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12129. */
  12130. Engine.prototype.getGlInfo = function () {
  12131. return {
  12132. vendor: this._glVendor,
  12133. renderer: this._glRenderer,
  12134. version: this._glVersion
  12135. };
  12136. };
  12137. /**
  12138. * Gets current aspect ratio
  12139. * @param camera defines the camera to use to get the aspect ratio
  12140. * @param useScreen defines if screen size must be used (or the current render target if any)
  12141. * @returns a number defining the aspect ratio
  12142. */
  12143. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12144. if (useScreen === void 0) { useScreen = false; }
  12145. var viewport = camera.viewport;
  12146. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12147. };
  12148. /**
  12149. * Gets current screen aspect ratio
  12150. * @returns a number defining the aspect ratio
  12151. */
  12152. Engine.prototype.getScreenAspectRatio = function () {
  12153. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12154. };
  12155. /**
  12156. * Gets the current render width
  12157. * @param useScreen defines if screen size must be used (or the current render target if any)
  12158. * @returns a number defining the current render width
  12159. */
  12160. Engine.prototype.getRenderWidth = function (useScreen) {
  12161. if (useScreen === void 0) { useScreen = false; }
  12162. if (!useScreen && this._currentRenderTarget) {
  12163. return this._currentRenderTarget.width;
  12164. }
  12165. return this._gl.drawingBufferWidth;
  12166. };
  12167. /**
  12168. * Gets the current render height
  12169. * @param useScreen defines if screen size must be used (or the current render target if any)
  12170. * @returns a number defining the current render height
  12171. */
  12172. Engine.prototype.getRenderHeight = function (useScreen) {
  12173. if (useScreen === void 0) { useScreen = false; }
  12174. if (!useScreen && this._currentRenderTarget) {
  12175. return this._currentRenderTarget.height;
  12176. }
  12177. return this._gl.drawingBufferHeight;
  12178. };
  12179. /**
  12180. * Gets the HTML canvas attached with the current webGL context
  12181. * @returns a HTML canvas
  12182. */
  12183. Engine.prototype.getRenderingCanvas = function () {
  12184. return this._renderingCanvas;
  12185. };
  12186. /**
  12187. * Gets the client rect of the HTML canvas attached with the current webGL context
  12188. * @returns a client rectanglee
  12189. */
  12190. Engine.prototype.getRenderingCanvasClientRect = function () {
  12191. if (!this._renderingCanvas) {
  12192. return null;
  12193. }
  12194. return this._renderingCanvas.getBoundingClientRect();
  12195. };
  12196. /**
  12197. * Defines the hardware scaling level.
  12198. * By default the hardware scaling level is computed from the window device ratio.
  12199. * 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.
  12200. * @param level defines the level to use
  12201. */
  12202. Engine.prototype.setHardwareScalingLevel = function (level) {
  12203. this._hardwareScalingLevel = level;
  12204. this.resize();
  12205. };
  12206. /**
  12207. * Gets the current hardware scaling level.
  12208. * By default the hardware scaling level is computed from the window device ratio.
  12209. * 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.
  12210. * @returns a number indicating the current hardware scaling level
  12211. */
  12212. Engine.prototype.getHardwareScalingLevel = function () {
  12213. return this._hardwareScalingLevel;
  12214. };
  12215. /**
  12216. * Gets the list of loaded textures
  12217. * @returns an array containing all loaded textures
  12218. */
  12219. Engine.prototype.getLoadedTexturesCache = function () {
  12220. return this._internalTexturesCache;
  12221. };
  12222. /**
  12223. * Gets the object containing all engine capabilities
  12224. * @returns the EngineCapabilities object
  12225. */
  12226. Engine.prototype.getCaps = function () {
  12227. return this._caps;
  12228. };
  12229. Object.defineProperty(Engine.prototype, "drawCalls", {
  12230. /** @hidden */
  12231. get: function () {
  12232. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12233. return 0;
  12234. },
  12235. enumerable: true,
  12236. configurable: true
  12237. });
  12238. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12239. /** @hidden */
  12240. get: function () {
  12241. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12242. return null;
  12243. },
  12244. enumerable: true,
  12245. configurable: true
  12246. });
  12247. /**
  12248. * Gets the current depth function
  12249. * @returns a number defining the depth function
  12250. */
  12251. Engine.prototype.getDepthFunction = function () {
  12252. return this._depthCullingState.depthFunc;
  12253. };
  12254. /**
  12255. * Sets the current depth function
  12256. * @param depthFunc defines the function to use
  12257. */
  12258. Engine.prototype.setDepthFunction = function (depthFunc) {
  12259. this._depthCullingState.depthFunc = depthFunc;
  12260. };
  12261. /**
  12262. * Sets the current depth function to GREATER
  12263. */
  12264. Engine.prototype.setDepthFunctionToGreater = function () {
  12265. this._depthCullingState.depthFunc = this._gl.GREATER;
  12266. };
  12267. /**
  12268. * Sets the current depth function to GEQUAL
  12269. */
  12270. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12271. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12272. };
  12273. /**
  12274. * Sets the current depth function to LESS
  12275. */
  12276. Engine.prototype.setDepthFunctionToLess = function () {
  12277. this._depthCullingState.depthFunc = this._gl.LESS;
  12278. };
  12279. /**
  12280. * Sets the current depth function to LEQUAL
  12281. */
  12282. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12283. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12284. };
  12285. /**
  12286. * Gets a boolean indicating if stencil buffer is enabled
  12287. * @returns the current stencil buffer state
  12288. */
  12289. Engine.prototype.getStencilBuffer = function () {
  12290. return this._stencilState.stencilTest;
  12291. };
  12292. /**
  12293. * Enable or disable the stencil buffer
  12294. * @param enable defines if the stencil buffer must be enabled or disabled
  12295. */
  12296. Engine.prototype.setStencilBuffer = function (enable) {
  12297. this._stencilState.stencilTest = enable;
  12298. };
  12299. /**
  12300. * Gets the current stencil mask
  12301. * @returns a number defining the new stencil mask to use
  12302. */
  12303. Engine.prototype.getStencilMask = function () {
  12304. return this._stencilState.stencilMask;
  12305. };
  12306. /**
  12307. * Sets the current stencil mask
  12308. * @param mask defines the new stencil mask to use
  12309. */
  12310. Engine.prototype.setStencilMask = function (mask) {
  12311. this._stencilState.stencilMask = mask;
  12312. };
  12313. /**
  12314. * Gets the current stencil function
  12315. * @returns a number defining the stencil function to use
  12316. */
  12317. Engine.prototype.getStencilFunction = function () {
  12318. return this._stencilState.stencilFunc;
  12319. };
  12320. /**
  12321. * Gets the current stencil reference value
  12322. * @returns a number defining the stencil reference value to use
  12323. */
  12324. Engine.prototype.getStencilFunctionReference = function () {
  12325. return this._stencilState.stencilFuncRef;
  12326. };
  12327. /**
  12328. * Gets the current stencil mask
  12329. * @returns a number defining the stencil mask to use
  12330. */
  12331. Engine.prototype.getStencilFunctionMask = function () {
  12332. return this._stencilState.stencilFuncMask;
  12333. };
  12334. /**
  12335. * Sets the current stencil function
  12336. * @param stencilFunc defines the new stencil function to use
  12337. */
  12338. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12339. this._stencilState.stencilFunc = stencilFunc;
  12340. };
  12341. /**
  12342. * Sets the current stencil reference
  12343. * @param reference defines the new stencil reference to use
  12344. */
  12345. Engine.prototype.setStencilFunctionReference = function (reference) {
  12346. this._stencilState.stencilFuncRef = reference;
  12347. };
  12348. /**
  12349. * Sets the current stencil mask
  12350. * @param mask defines the new stencil mask to use
  12351. */
  12352. Engine.prototype.setStencilFunctionMask = function (mask) {
  12353. this._stencilState.stencilFuncMask = mask;
  12354. };
  12355. /**
  12356. * Gets the current stencil operation when stencil fails
  12357. * @returns a number defining stencil operation to use when stencil fails
  12358. */
  12359. Engine.prototype.getStencilOperationFail = function () {
  12360. return this._stencilState.stencilOpStencilFail;
  12361. };
  12362. /**
  12363. * Gets the current stencil operation when depth fails
  12364. * @returns a number defining stencil operation to use when depth fails
  12365. */
  12366. Engine.prototype.getStencilOperationDepthFail = function () {
  12367. return this._stencilState.stencilOpDepthFail;
  12368. };
  12369. /**
  12370. * Gets the current stencil operation when stencil passes
  12371. * @returns a number defining stencil operation to use when stencil passes
  12372. */
  12373. Engine.prototype.getStencilOperationPass = function () {
  12374. return this._stencilState.stencilOpStencilDepthPass;
  12375. };
  12376. /**
  12377. * Sets the stencil operation to use when stencil fails
  12378. * @param operation defines the stencil operation to use when stencil fails
  12379. */
  12380. Engine.prototype.setStencilOperationFail = function (operation) {
  12381. this._stencilState.stencilOpStencilFail = operation;
  12382. };
  12383. /**
  12384. * Sets the stencil operation to use when depth fails
  12385. * @param operation defines the stencil operation to use when depth fails
  12386. */
  12387. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12388. this._stencilState.stencilOpDepthFail = operation;
  12389. };
  12390. /**
  12391. * Sets the stencil operation to use when stencil passes
  12392. * @param operation defines the stencil operation to use when stencil passes
  12393. */
  12394. Engine.prototype.setStencilOperationPass = function (operation) {
  12395. this._stencilState.stencilOpStencilDepthPass = operation;
  12396. };
  12397. /**
  12398. * Sets a boolean indicating if the dithering state is enabled or disabled
  12399. * @param value defines the dithering state
  12400. */
  12401. Engine.prototype.setDitheringState = function (value) {
  12402. if (value) {
  12403. this._gl.enable(this._gl.DITHER);
  12404. }
  12405. else {
  12406. this._gl.disable(this._gl.DITHER);
  12407. }
  12408. };
  12409. /**
  12410. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12411. * @param value defines the rasterizer state
  12412. */
  12413. Engine.prototype.setRasterizerState = function (value) {
  12414. if (value) {
  12415. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12416. }
  12417. else {
  12418. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12419. }
  12420. };
  12421. /**
  12422. * stop executing a render loop function and remove it from the execution array
  12423. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12424. */
  12425. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12426. if (!renderFunction) {
  12427. this._activeRenderLoops = [];
  12428. return;
  12429. }
  12430. var index = this._activeRenderLoops.indexOf(renderFunction);
  12431. if (index >= 0) {
  12432. this._activeRenderLoops.splice(index, 1);
  12433. }
  12434. };
  12435. /** @hidden */
  12436. Engine.prototype._renderLoop = function () {
  12437. if (!this._contextWasLost) {
  12438. var shouldRender = true;
  12439. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12440. shouldRender = false;
  12441. }
  12442. if (shouldRender) {
  12443. // Start new frame
  12444. this.beginFrame();
  12445. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12446. var renderFunction = this._activeRenderLoops[index];
  12447. renderFunction();
  12448. }
  12449. // Present
  12450. this.endFrame();
  12451. }
  12452. }
  12453. if (this._activeRenderLoops.length > 0) {
  12454. // Register new frame
  12455. var requester = null;
  12456. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12457. requester = this._vrDisplay;
  12458. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12459. }
  12460. else {
  12461. this._renderingQueueLaunched = false;
  12462. }
  12463. };
  12464. /**
  12465. * Register and execute a render loop. The engine can have more than one render function
  12466. * @param renderFunction defines the function to continuously execute
  12467. */
  12468. Engine.prototype.runRenderLoop = function (renderFunction) {
  12469. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12470. return;
  12471. }
  12472. this._activeRenderLoops.push(renderFunction);
  12473. if (!this._renderingQueueLaunched) {
  12474. this._renderingQueueLaunched = true;
  12475. this._bindedRenderFunction = this._renderLoop.bind(this);
  12476. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12477. }
  12478. };
  12479. /**
  12480. * Toggle full screen mode
  12481. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12482. * @param options defines an option object to be sent to the requestFullscreen function
  12483. */
  12484. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12485. if (this.isFullscreen) {
  12486. BABYLON.Tools.ExitFullscreen();
  12487. }
  12488. else {
  12489. this._pointerLockRequested = requestPointerLock;
  12490. if (this._renderingCanvas) {
  12491. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12492. }
  12493. }
  12494. };
  12495. /**
  12496. * Clear the current render buffer or the current render target (if any is set up)
  12497. * @param color defines the color to use
  12498. * @param backBuffer defines if the back buffer must be cleared
  12499. * @param depth defines if the depth buffer must be cleared
  12500. * @param stencil defines if the stencil buffer must be cleared
  12501. */
  12502. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12503. if (stencil === void 0) { stencil = false; }
  12504. this.applyStates();
  12505. var mode = 0;
  12506. if (backBuffer && color) {
  12507. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12508. mode |= this._gl.COLOR_BUFFER_BIT;
  12509. }
  12510. if (depth) {
  12511. this._gl.clearDepth(1.0);
  12512. mode |= this._gl.DEPTH_BUFFER_BIT;
  12513. }
  12514. if (stencil) {
  12515. this._gl.clearStencil(0);
  12516. mode |= this._gl.STENCIL_BUFFER_BIT;
  12517. }
  12518. this._gl.clear(mode);
  12519. };
  12520. /**
  12521. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12522. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12523. * @param y defines the y-coordinate of the corner of the clear rectangle
  12524. * @param width defines the width of the clear rectangle
  12525. * @param height defines the height of the clear rectangle
  12526. * @param clearColor defines the clear color
  12527. */
  12528. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12529. var gl = this._gl;
  12530. // Save state
  12531. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12532. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12533. // Change state
  12534. gl.enable(gl.SCISSOR_TEST);
  12535. gl.scissor(x, y, width, height);
  12536. // Clear
  12537. this.clear(clearColor, true, true, true);
  12538. // Restore state
  12539. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12540. if (curScissor === true) {
  12541. gl.enable(gl.SCISSOR_TEST);
  12542. }
  12543. else {
  12544. gl.disable(gl.SCISSOR_TEST);
  12545. }
  12546. };
  12547. /** @hidden */
  12548. Engine.prototype._viewport = function (x, y, width, height) {
  12549. if (x !== this._viewportCached.x ||
  12550. y !== this._viewportCached.y ||
  12551. width !== this._viewportCached.z ||
  12552. height !== this._viewportCached.w) {
  12553. this._viewportCached.x = x;
  12554. this._viewportCached.y = y;
  12555. this._viewportCached.z = width;
  12556. this._viewportCached.w = height;
  12557. this._gl.viewport(x, y, width, height);
  12558. }
  12559. };
  12560. /**
  12561. * Set the WebGL's viewport
  12562. * @param viewport defines the viewport element to be used
  12563. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12564. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12565. */
  12566. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12567. var width = requiredWidth || this.getRenderWidth();
  12568. var height = requiredHeight || this.getRenderHeight();
  12569. var x = viewport.x || 0;
  12570. var y = viewport.y || 0;
  12571. this._cachedViewport = viewport;
  12572. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12573. };
  12574. /**
  12575. * Directly set the WebGL Viewport
  12576. * @param x defines the x coordinate of the viewport (in screen space)
  12577. * @param y defines the y coordinate of the viewport (in screen space)
  12578. * @param width defines the width of the viewport (in screen space)
  12579. * @param height defines the height of the viewport (in screen space)
  12580. * @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
  12581. */
  12582. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12583. var currentViewport = this._cachedViewport;
  12584. this._cachedViewport = null;
  12585. this._viewport(x, y, width, height);
  12586. return currentViewport;
  12587. };
  12588. /**
  12589. * Begin a new frame
  12590. */
  12591. Engine.prototype.beginFrame = function () {
  12592. this.onBeginFrameObservable.notifyObservers(this);
  12593. this._measureFps();
  12594. };
  12595. /**
  12596. * Enf the current frame
  12597. */
  12598. Engine.prototype.endFrame = function () {
  12599. // Force a flush in case we are using a bad OS.
  12600. if (this._badOS) {
  12601. this.flushFramebuffer();
  12602. }
  12603. // Submit frame to the vr device, if enabled
  12604. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12605. // TODO: We should only submit the frame if we read frameData successfully.
  12606. this._vrDisplay.submitFrame();
  12607. }
  12608. this.onEndFrameObservable.notifyObservers(this);
  12609. };
  12610. /**
  12611. * Resize the view according to the canvas' size
  12612. */
  12613. Engine.prototype.resize = function () {
  12614. // We're not resizing the size of the canvas while in VR mode & presenting
  12615. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12616. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12617. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12618. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12619. }
  12620. };
  12621. /**
  12622. * Force a specific size of the canvas
  12623. * @param width defines the new canvas' width
  12624. * @param height defines the new canvas' height
  12625. */
  12626. Engine.prototype.setSize = function (width, height) {
  12627. if (!this._renderingCanvas) {
  12628. return;
  12629. }
  12630. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12631. return;
  12632. }
  12633. this._renderingCanvas.width = width;
  12634. this._renderingCanvas.height = height;
  12635. for (var index = 0; index < this.scenes.length; index++) {
  12636. var scene = this.scenes[index];
  12637. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12638. var cam = scene.cameras[camIndex];
  12639. cam._currentRenderId = 0;
  12640. }
  12641. }
  12642. if (this.onResizeObservable.hasObservers) {
  12643. this.onResizeObservable.notifyObservers(this);
  12644. }
  12645. };
  12646. // WebVR functions
  12647. /**
  12648. * Gets a boolean indicating if a webVR device was detected
  12649. * @returns true if a webVR device was detected
  12650. */
  12651. Engine.prototype.isVRDevicePresent = function () {
  12652. return !!this._vrDisplay;
  12653. };
  12654. /**
  12655. * Gets the current webVR device
  12656. * @returns the current webVR device (or null)
  12657. */
  12658. Engine.prototype.getVRDevice = function () {
  12659. return this._vrDisplay;
  12660. };
  12661. /**
  12662. * Initializes a webVR display and starts listening to display change events
  12663. * The onVRDisplayChangedObservable will be notified upon these changes
  12664. * @returns The onVRDisplayChangedObservable
  12665. */
  12666. Engine.prototype.initWebVR = function () {
  12667. this.initWebVRAsync();
  12668. return this.onVRDisplayChangedObservable;
  12669. };
  12670. /**
  12671. * Initializes a webVR display and starts listening to display change events
  12672. * The onVRDisplayChangedObservable will be notified upon these changes
  12673. * @returns A promise containing a VRDisplay and if vr is supported
  12674. */
  12675. Engine.prototype.initWebVRAsync = function () {
  12676. var _this = this;
  12677. var notifyObservers = function () {
  12678. var eventArgs = {
  12679. vrDisplay: _this._vrDisplay,
  12680. vrSupported: _this._vrSupported
  12681. };
  12682. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12683. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12684. };
  12685. if (!this._onVrDisplayConnect) {
  12686. this._onVrDisplayConnect = function (event) {
  12687. _this._vrDisplay = event.display;
  12688. notifyObservers();
  12689. };
  12690. this._onVrDisplayDisconnect = function () {
  12691. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12692. _this._vrDisplay = undefined;
  12693. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12694. notifyObservers();
  12695. };
  12696. this._onVrDisplayPresentChange = function () {
  12697. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12698. };
  12699. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12700. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12701. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12702. }
  12703. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12704. this._webVRInitPromise.then(notifyObservers);
  12705. return this._webVRInitPromise;
  12706. };
  12707. /**
  12708. * Call this function to switch to webVR mode
  12709. * Will do nothing if webVR is not supported or if there is no webVR device
  12710. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12711. */
  12712. Engine.prototype.enableVR = function () {
  12713. var _this = this;
  12714. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12715. var onResolved = function () {
  12716. _this.onVRRequestPresentComplete.notifyObservers(true);
  12717. _this._onVRFullScreenTriggered();
  12718. };
  12719. var onRejected = function () {
  12720. _this.onVRRequestPresentComplete.notifyObservers(false);
  12721. };
  12722. this.onVRRequestPresentStart.notifyObservers(this);
  12723. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12724. }
  12725. };
  12726. /**
  12727. * Call this function to leave webVR mode
  12728. * Will do nothing if webVR is not supported or if there is no webVR device
  12729. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12730. */
  12731. Engine.prototype.disableVR = function () {
  12732. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12733. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12734. }
  12735. };
  12736. Engine.prototype._getVRDisplaysAsync = function () {
  12737. var _this = this;
  12738. return new Promise(function (res, rej) {
  12739. if (navigator.getVRDisplays) {
  12740. navigator.getVRDisplays().then(function (devices) {
  12741. _this._vrSupported = true;
  12742. // note that devices may actually be an empty array. This is fine;
  12743. // we expect this._vrDisplay to be undefined in this case.
  12744. _this._vrDisplay = devices[0];
  12745. res({
  12746. vrDisplay: _this._vrDisplay,
  12747. vrSupported: _this._vrSupported
  12748. });
  12749. });
  12750. }
  12751. else {
  12752. _this._vrDisplay = undefined;
  12753. _this._vrSupported = false;
  12754. res({
  12755. vrDisplay: _this._vrDisplay,
  12756. vrSupported: _this._vrSupported
  12757. });
  12758. }
  12759. });
  12760. };
  12761. /**
  12762. * Binds the frame buffer to the specified texture.
  12763. * @param texture The texture to render to or null for the default canvas
  12764. * @param faceIndex The face of the texture to render to in case of cube texture
  12765. * @param requiredWidth The width of the target to render to
  12766. * @param requiredHeight The height of the target to render to
  12767. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12768. * @param depthStencilTexture The depth stencil texture to use to render
  12769. * @param lodLevel defines le lod level to bind to the frame buffer
  12770. */
  12771. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12772. if (lodLevel === void 0) { lodLevel = 0; }
  12773. if (this._currentRenderTarget) {
  12774. this.unBindFramebuffer(this._currentRenderTarget);
  12775. }
  12776. this._currentRenderTarget = texture;
  12777. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12778. var gl = this._gl;
  12779. if (texture.isCube) {
  12780. if (faceIndex === undefined) {
  12781. faceIndex = 0;
  12782. }
  12783. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12784. if (depthStencilTexture) {
  12785. if (depthStencilTexture._generateStencilBuffer) {
  12786. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12787. }
  12788. else {
  12789. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12790. }
  12791. }
  12792. }
  12793. if (this._cachedViewport && !forceFullscreenViewport) {
  12794. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12795. }
  12796. else {
  12797. if (!requiredWidth) {
  12798. requiredWidth = texture.width;
  12799. if (lodLevel) {
  12800. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12801. }
  12802. }
  12803. if (!requiredHeight) {
  12804. requiredHeight = texture.height;
  12805. if (lodLevel) {
  12806. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12807. }
  12808. }
  12809. this._viewport(0, 0, requiredWidth, requiredHeight);
  12810. }
  12811. this.wipeCaches();
  12812. };
  12813. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12814. if (this._currentFramebuffer !== framebuffer) {
  12815. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12816. this._currentFramebuffer = framebuffer;
  12817. }
  12818. };
  12819. /**
  12820. * Unbind the current render target texture from the webGL context
  12821. * @param texture defines the render target texture to unbind
  12822. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12823. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12824. */
  12825. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12826. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12827. this._currentRenderTarget = null;
  12828. // If MSAA, we need to bitblt back to main texture
  12829. var gl = this._gl;
  12830. if (texture._MSAAFramebuffer) {
  12831. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12832. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12833. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12834. }
  12835. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12836. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12837. gl.generateMipmap(gl.TEXTURE_2D);
  12838. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12839. }
  12840. if (onBeforeUnbind) {
  12841. if (texture._MSAAFramebuffer) {
  12842. // Bind the correct framebuffer
  12843. this.bindUnboundFramebuffer(texture._framebuffer);
  12844. }
  12845. onBeforeUnbind();
  12846. }
  12847. this.bindUnboundFramebuffer(null);
  12848. };
  12849. /**
  12850. * Unbind a list of render target textures from the webGL context
  12851. * This is used only when drawBuffer extension or webGL2 are active
  12852. * @param textures defines the render target textures to unbind
  12853. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12854. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12855. */
  12856. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12857. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12858. this._currentRenderTarget = null;
  12859. // If MSAA, we need to bitblt back to main texture
  12860. var gl = this._gl;
  12861. if (textures[0]._MSAAFramebuffer) {
  12862. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12863. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12864. var attachments = textures[0]._attachments;
  12865. if (!attachments) {
  12866. attachments = new Array(textures.length);
  12867. textures[0]._attachments = attachments;
  12868. }
  12869. for (var i = 0; i < textures.length; i++) {
  12870. var texture = textures[i];
  12871. for (var j = 0; j < attachments.length; j++) {
  12872. attachments[j] = gl.NONE;
  12873. }
  12874. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12875. gl.readBuffer(attachments[i]);
  12876. gl.drawBuffers(attachments);
  12877. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12878. }
  12879. for (var i = 0; i < attachments.length; i++) {
  12880. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12881. }
  12882. gl.drawBuffers(attachments);
  12883. }
  12884. for (var i = 0; i < textures.length; i++) {
  12885. var texture = textures[i];
  12886. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12887. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12888. gl.generateMipmap(gl.TEXTURE_2D);
  12889. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12890. }
  12891. }
  12892. if (onBeforeUnbind) {
  12893. if (textures[0]._MSAAFramebuffer) {
  12894. // Bind the correct framebuffer
  12895. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12896. }
  12897. onBeforeUnbind();
  12898. }
  12899. this.bindUnboundFramebuffer(null);
  12900. };
  12901. /**
  12902. * Force the mipmap generation for the given render target texture
  12903. * @param texture defines the render target texture to use
  12904. */
  12905. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12906. if (texture.generateMipMaps) {
  12907. var gl = this._gl;
  12908. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12909. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12910. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12911. }
  12912. };
  12913. /**
  12914. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12915. */
  12916. Engine.prototype.flushFramebuffer = function () {
  12917. this._gl.flush();
  12918. };
  12919. /**
  12920. * Unbind the current render target and bind the default framebuffer
  12921. */
  12922. Engine.prototype.restoreDefaultFramebuffer = function () {
  12923. if (this._currentRenderTarget) {
  12924. this.unBindFramebuffer(this._currentRenderTarget);
  12925. }
  12926. else {
  12927. this.bindUnboundFramebuffer(null);
  12928. }
  12929. if (this._cachedViewport) {
  12930. this.setViewport(this._cachedViewport);
  12931. }
  12932. this.wipeCaches();
  12933. };
  12934. // UBOs
  12935. /**
  12936. * Create an uniform buffer
  12937. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12938. * @param elements defines the content of the uniform buffer
  12939. * @returns the webGL uniform buffer
  12940. */
  12941. Engine.prototype.createUniformBuffer = function (elements) {
  12942. var ubo = this._gl.createBuffer();
  12943. if (!ubo) {
  12944. throw new Error("Unable to create uniform buffer");
  12945. }
  12946. this.bindUniformBuffer(ubo);
  12947. if (elements instanceof Float32Array) {
  12948. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12949. }
  12950. else {
  12951. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12952. }
  12953. this.bindUniformBuffer(null);
  12954. ubo.references = 1;
  12955. return ubo;
  12956. };
  12957. /**
  12958. * Create a dynamic uniform buffer
  12959. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12960. * @param elements defines the content of the uniform buffer
  12961. * @returns the webGL uniform buffer
  12962. */
  12963. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12964. var ubo = this._gl.createBuffer();
  12965. if (!ubo) {
  12966. throw new Error("Unable to create dynamic uniform buffer");
  12967. }
  12968. this.bindUniformBuffer(ubo);
  12969. if (elements instanceof Float32Array) {
  12970. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12971. }
  12972. else {
  12973. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12974. }
  12975. this.bindUniformBuffer(null);
  12976. ubo.references = 1;
  12977. return ubo;
  12978. };
  12979. /**
  12980. * Update an existing uniform buffer
  12981. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12982. * @param uniformBuffer defines the target uniform buffer
  12983. * @param elements defines the content to update
  12984. * @param offset defines the offset in the uniform buffer where update should start
  12985. * @param count defines the size of the data to update
  12986. */
  12987. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12988. this.bindUniformBuffer(uniformBuffer);
  12989. if (offset === undefined) {
  12990. offset = 0;
  12991. }
  12992. if (count === undefined) {
  12993. if (elements instanceof Float32Array) {
  12994. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12995. }
  12996. else {
  12997. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12998. }
  12999. }
  13000. else {
  13001. if (elements instanceof Float32Array) {
  13002. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13003. }
  13004. else {
  13005. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13006. }
  13007. }
  13008. this.bindUniformBuffer(null);
  13009. };
  13010. // VBOs
  13011. Engine.prototype._resetVertexBufferBinding = function () {
  13012. this.bindArrayBuffer(null);
  13013. this._cachedVertexBuffers = null;
  13014. };
  13015. /**
  13016. * Creates a vertex buffer
  13017. * @param data the data for the vertex buffer
  13018. * @returns the new WebGL static buffer
  13019. */
  13020. Engine.prototype.createVertexBuffer = function (data) {
  13021. var vbo = this._gl.createBuffer();
  13022. if (!vbo) {
  13023. throw new Error("Unable to create vertex buffer");
  13024. }
  13025. this.bindArrayBuffer(vbo);
  13026. if (data instanceof Array) {
  13027. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13028. }
  13029. else {
  13030. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13031. }
  13032. this._resetVertexBufferBinding();
  13033. vbo.references = 1;
  13034. return vbo;
  13035. };
  13036. /**
  13037. * Creates a dynamic vertex buffer
  13038. * @param data the data for the dynamic vertex buffer
  13039. * @returns the new WebGL dynamic buffer
  13040. */
  13041. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13042. var vbo = this._gl.createBuffer();
  13043. if (!vbo) {
  13044. throw new Error("Unable to create dynamic vertex buffer");
  13045. }
  13046. this.bindArrayBuffer(vbo);
  13047. if (data instanceof Array) {
  13048. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13049. }
  13050. else {
  13051. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13052. }
  13053. this._resetVertexBufferBinding();
  13054. vbo.references = 1;
  13055. return vbo;
  13056. };
  13057. /**
  13058. * Update a dynamic index buffer
  13059. * @param indexBuffer defines the target index buffer
  13060. * @param indices defines the data to update
  13061. * @param offset defines the offset in the target index buffer where update should start
  13062. */
  13063. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13064. if (offset === void 0) { offset = 0; }
  13065. // Force cache update
  13066. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13067. this.bindIndexBuffer(indexBuffer);
  13068. var arrayBuffer;
  13069. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13070. arrayBuffer = indices;
  13071. }
  13072. else {
  13073. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13074. }
  13075. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13076. this._resetIndexBufferBinding();
  13077. };
  13078. /**
  13079. * Updates a dynamic vertex buffer.
  13080. * @param vertexBuffer the vertex buffer to update
  13081. * @param data the data used to update the vertex buffer
  13082. * @param byteOffset the byte offset of the data
  13083. * @param byteLength the byte length of the data
  13084. */
  13085. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13086. this.bindArrayBuffer(vertexBuffer);
  13087. if (byteOffset === undefined) {
  13088. byteOffset = 0;
  13089. }
  13090. if (byteLength === undefined) {
  13091. if (data instanceof Array) {
  13092. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13093. }
  13094. else {
  13095. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13096. }
  13097. }
  13098. else {
  13099. if (data instanceof Array) {
  13100. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13101. }
  13102. else {
  13103. if (data instanceof ArrayBuffer) {
  13104. data = new Uint8Array(data, byteOffset, byteLength);
  13105. }
  13106. else {
  13107. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13108. }
  13109. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13110. }
  13111. }
  13112. this._resetVertexBufferBinding();
  13113. };
  13114. Engine.prototype._resetIndexBufferBinding = function () {
  13115. this.bindIndexBuffer(null);
  13116. this._cachedIndexBuffer = null;
  13117. };
  13118. /**
  13119. * Creates a new index buffer
  13120. * @param indices defines the content of the index buffer
  13121. * @param updatable defines if the index buffer must be updatable
  13122. * @returns a new webGL buffer
  13123. */
  13124. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13125. var vbo = this._gl.createBuffer();
  13126. if (!vbo) {
  13127. throw new Error("Unable to create index buffer");
  13128. }
  13129. this.bindIndexBuffer(vbo);
  13130. // Check for 32 bits indices
  13131. var arrayBuffer;
  13132. var need32Bits = false;
  13133. if (indices instanceof Uint16Array) {
  13134. arrayBuffer = indices;
  13135. }
  13136. else {
  13137. //check 32 bit support
  13138. if (this._caps.uintIndices) {
  13139. if (indices instanceof Uint32Array) {
  13140. arrayBuffer = indices;
  13141. need32Bits = true;
  13142. }
  13143. else {
  13144. //number[] or Int32Array, check if 32 bit is necessary
  13145. for (var index = 0; index < indices.length; index++) {
  13146. if (indices[index] > 65535) {
  13147. need32Bits = true;
  13148. break;
  13149. }
  13150. }
  13151. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13152. }
  13153. }
  13154. else {
  13155. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13156. arrayBuffer = new Uint16Array(indices);
  13157. }
  13158. }
  13159. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13160. this._resetIndexBufferBinding();
  13161. vbo.references = 1;
  13162. vbo.is32Bits = need32Bits;
  13163. return vbo;
  13164. };
  13165. /**
  13166. * Bind a webGL buffer to the webGL context
  13167. * @param buffer defines the buffer to bind
  13168. */
  13169. Engine.prototype.bindArrayBuffer = function (buffer) {
  13170. if (!this._vaoRecordInProgress) {
  13171. this._unbindVertexArrayObject();
  13172. }
  13173. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13174. };
  13175. /**
  13176. * Bind an uniform buffer to the current webGL context
  13177. * @param buffer defines the buffer to bind
  13178. */
  13179. Engine.prototype.bindUniformBuffer = function (buffer) {
  13180. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13181. };
  13182. /**
  13183. * Bind a buffer to the current webGL context at a given location
  13184. * @param buffer defines the buffer to bind
  13185. * @param location defines the index where to bind the buffer
  13186. */
  13187. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13188. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13189. };
  13190. /**
  13191. * Bind a specific block at a given index in a specific shader program
  13192. * @param shaderProgram defines the shader program
  13193. * @param blockName defines the block name
  13194. * @param index defines the index where to bind the block
  13195. */
  13196. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13197. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13198. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13199. };
  13200. ;
  13201. Engine.prototype.bindIndexBuffer = function (buffer) {
  13202. if (!this._vaoRecordInProgress) {
  13203. this._unbindVertexArrayObject();
  13204. }
  13205. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13206. };
  13207. Engine.prototype.bindBuffer = function (buffer, target) {
  13208. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13209. this._gl.bindBuffer(target, buffer);
  13210. this._currentBoundBuffer[target] = buffer;
  13211. }
  13212. };
  13213. /**
  13214. * update the bound buffer with the given data
  13215. * @param data defines the data to update
  13216. */
  13217. Engine.prototype.updateArrayBuffer = function (data) {
  13218. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13219. };
  13220. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13221. var pointer = this._currentBufferPointers[indx];
  13222. var changed = false;
  13223. if (!pointer.active) {
  13224. changed = true;
  13225. pointer.active = true;
  13226. pointer.index = indx;
  13227. pointer.size = size;
  13228. pointer.type = type;
  13229. pointer.normalized = normalized;
  13230. pointer.stride = stride;
  13231. pointer.offset = offset;
  13232. pointer.buffer = buffer;
  13233. }
  13234. else {
  13235. if (pointer.buffer !== buffer) {
  13236. pointer.buffer = buffer;
  13237. changed = true;
  13238. }
  13239. if (pointer.size !== size) {
  13240. pointer.size = size;
  13241. changed = true;
  13242. }
  13243. if (pointer.type !== type) {
  13244. pointer.type = type;
  13245. changed = true;
  13246. }
  13247. if (pointer.normalized !== normalized) {
  13248. pointer.normalized = normalized;
  13249. changed = true;
  13250. }
  13251. if (pointer.stride !== stride) {
  13252. pointer.stride = stride;
  13253. changed = true;
  13254. }
  13255. if (pointer.offset !== offset) {
  13256. pointer.offset = offset;
  13257. changed = true;
  13258. }
  13259. }
  13260. if (changed || this._vaoRecordInProgress) {
  13261. this.bindArrayBuffer(buffer);
  13262. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13263. }
  13264. };
  13265. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13266. if (indexBuffer == null) {
  13267. return;
  13268. }
  13269. if (this._cachedIndexBuffer !== indexBuffer) {
  13270. this._cachedIndexBuffer = indexBuffer;
  13271. this.bindIndexBuffer(indexBuffer);
  13272. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13273. }
  13274. };
  13275. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13276. var attributes = effect.getAttributesNames();
  13277. if (!this._vaoRecordInProgress) {
  13278. this._unbindVertexArrayObject();
  13279. }
  13280. this.unbindAllAttributes();
  13281. for (var index = 0; index < attributes.length; index++) {
  13282. var order = effect.getAttributeLocation(index);
  13283. if (order >= 0) {
  13284. var vertexBuffer = vertexBuffers[attributes[index]];
  13285. if (!vertexBuffer) {
  13286. continue;
  13287. }
  13288. this._gl.enableVertexAttribArray(order);
  13289. if (!this._vaoRecordInProgress) {
  13290. this._vertexAttribArraysEnabled[order] = true;
  13291. }
  13292. var buffer = vertexBuffer.getBuffer();
  13293. if (buffer) {
  13294. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13295. if (vertexBuffer.getIsInstanced()) {
  13296. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13297. if (!this._vaoRecordInProgress) {
  13298. this._currentInstanceLocations.push(order);
  13299. this._currentInstanceBuffers.push(buffer);
  13300. }
  13301. }
  13302. }
  13303. }
  13304. }
  13305. };
  13306. /**
  13307. * Records a vertex array object
  13308. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13309. * @param vertexBuffers defines the list of vertex buffers to store
  13310. * @param indexBuffer defines the index buffer to store
  13311. * @param effect defines the effect to store
  13312. * @returns the new vertex array object
  13313. */
  13314. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13315. var vao = this._gl.createVertexArray();
  13316. this._vaoRecordInProgress = true;
  13317. this._gl.bindVertexArray(vao);
  13318. this._mustWipeVertexAttributes = true;
  13319. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13320. this.bindIndexBuffer(indexBuffer);
  13321. this._vaoRecordInProgress = false;
  13322. this._gl.bindVertexArray(null);
  13323. return vao;
  13324. };
  13325. /**
  13326. * Bind a specific vertex array object
  13327. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13328. * @param vertexArrayObject defines the vertex array object to bind
  13329. * @param indexBuffer defines the index buffer to bind
  13330. */
  13331. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13332. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13333. this._cachedVertexArrayObject = vertexArrayObject;
  13334. this._gl.bindVertexArray(vertexArrayObject);
  13335. this._cachedVertexBuffers = null;
  13336. this._cachedIndexBuffer = null;
  13337. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13338. this._mustWipeVertexAttributes = true;
  13339. }
  13340. };
  13341. /**
  13342. * Bind webGl buffers directly to the webGL context
  13343. * @param vertexBuffer defines the vertex buffer to bind
  13344. * @param indexBuffer defines the index buffer to bind
  13345. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13346. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13347. * @param effect defines the effect associated with the vertex buffer
  13348. */
  13349. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13350. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13351. this._cachedVertexBuffers = vertexBuffer;
  13352. this._cachedEffectForVertexBuffers = effect;
  13353. var attributesCount = effect.getAttributesCount();
  13354. this._unbindVertexArrayObject();
  13355. this.unbindAllAttributes();
  13356. var offset = 0;
  13357. for (var index = 0; index < attributesCount; index++) {
  13358. if (index < vertexDeclaration.length) {
  13359. var order = effect.getAttributeLocation(index);
  13360. if (order >= 0) {
  13361. this._gl.enableVertexAttribArray(order);
  13362. this._vertexAttribArraysEnabled[order] = true;
  13363. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13364. }
  13365. offset += vertexDeclaration[index] * 4;
  13366. }
  13367. }
  13368. }
  13369. this._bindIndexBufferWithCache(indexBuffer);
  13370. };
  13371. Engine.prototype._unbindVertexArrayObject = function () {
  13372. if (!this._cachedVertexArrayObject) {
  13373. return;
  13374. }
  13375. this._cachedVertexArrayObject = null;
  13376. this._gl.bindVertexArray(null);
  13377. };
  13378. /**
  13379. * Bind a list of vertex buffers to the webGL context
  13380. * @param vertexBuffers defines the list of vertex buffers to bind
  13381. * @param indexBuffer defines the index buffer to bind
  13382. * @param effect defines the effect associated with the vertex buffers
  13383. */
  13384. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13385. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13386. this._cachedVertexBuffers = vertexBuffers;
  13387. this._cachedEffectForVertexBuffers = effect;
  13388. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13389. }
  13390. this._bindIndexBufferWithCache(indexBuffer);
  13391. };
  13392. /**
  13393. * Unbind all instance attributes
  13394. */
  13395. Engine.prototype.unbindInstanceAttributes = function () {
  13396. var boundBuffer;
  13397. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13398. var instancesBuffer = this._currentInstanceBuffers[i];
  13399. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13400. boundBuffer = instancesBuffer;
  13401. this.bindArrayBuffer(instancesBuffer);
  13402. }
  13403. var offsetLocation = this._currentInstanceLocations[i];
  13404. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13405. }
  13406. this._currentInstanceBuffers.length = 0;
  13407. this._currentInstanceLocations.length = 0;
  13408. };
  13409. /**
  13410. * Release and free the memory of a vertex array object
  13411. * @param vao defines the vertex array object to delete
  13412. */
  13413. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13414. this._gl.deleteVertexArray(vao);
  13415. };
  13416. /** @hidden */
  13417. Engine.prototype._releaseBuffer = function (buffer) {
  13418. buffer.references--;
  13419. if (buffer.references === 0) {
  13420. this._gl.deleteBuffer(buffer);
  13421. return true;
  13422. }
  13423. return false;
  13424. };
  13425. /**
  13426. * Creates a webGL buffer to use with instanciation
  13427. * @param capacity defines the size of the buffer
  13428. * @returns the webGL buffer
  13429. */
  13430. Engine.prototype.createInstancesBuffer = function (capacity) {
  13431. var buffer = this._gl.createBuffer();
  13432. if (!buffer) {
  13433. throw new Error("Unable to create instance buffer");
  13434. }
  13435. buffer.capacity = capacity;
  13436. this.bindArrayBuffer(buffer);
  13437. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13438. return buffer;
  13439. };
  13440. /**
  13441. * Delete a webGL buffer used with instanciation
  13442. * @param buffer defines the webGL buffer to delete
  13443. */
  13444. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13445. this._gl.deleteBuffer(buffer);
  13446. };
  13447. /**
  13448. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13449. * @param instancesBuffer defines the webGL buffer to update and bind
  13450. * @param data defines the data to store in the buffer
  13451. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13452. */
  13453. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13454. this.bindArrayBuffer(instancesBuffer);
  13455. if (data) {
  13456. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13457. }
  13458. if (offsetLocations[0].index !== undefined) {
  13459. var stride = 0;
  13460. for (var i = 0; i < offsetLocations.length; i++) {
  13461. var ai = offsetLocations[i];
  13462. stride += ai.attributeSize * 4;
  13463. }
  13464. for (var i = 0; i < offsetLocations.length; i++) {
  13465. var ai = offsetLocations[i];
  13466. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13467. this._gl.enableVertexAttribArray(ai.index);
  13468. this._vertexAttribArraysEnabled[ai.index] = true;
  13469. }
  13470. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13471. this._gl.vertexAttribDivisor(ai.index, 1);
  13472. this._currentInstanceLocations.push(ai.index);
  13473. this._currentInstanceBuffers.push(instancesBuffer);
  13474. }
  13475. }
  13476. else {
  13477. for (var index = 0; index < 4; index++) {
  13478. var offsetLocation = offsetLocations[index];
  13479. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13480. this._gl.enableVertexAttribArray(offsetLocation);
  13481. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13482. }
  13483. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13484. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13485. this._currentInstanceLocations.push(offsetLocation);
  13486. this._currentInstanceBuffers.push(instancesBuffer);
  13487. }
  13488. }
  13489. };
  13490. /**
  13491. * Apply all cached states (depth, culling, stencil and alpha)
  13492. */
  13493. Engine.prototype.applyStates = function () {
  13494. this._depthCullingState.apply(this._gl);
  13495. this._stencilState.apply(this._gl);
  13496. this._alphaState.apply(this._gl);
  13497. };
  13498. /**
  13499. * Send a draw order
  13500. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13501. * @param indexStart defines the starting index
  13502. * @param indexCount defines the number of index to draw
  13503. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13504. */
  13505. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13506. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13507. };
  13508. /**
  13509. * Draw a list of points
  13510. * @param verticesStart defines the index of first vertex to draw
  13511. * @param verticesCount defines the count of vertices to draw
  13512. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13513. */
  13514. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13515. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13516. };
  13517. /**
  13518. * Draw a list of unindexed primitives
  13519. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13520. * @param verticesStart defines the index of first vertex to draw
  13521. * @param verticesCount defines the count of vertices to draw
  13522. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13523. */
  13524. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13525. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13526. };
  13527. /**
  13528. * Draw a list of indexed primitives
  13529. * @param fillMode defines the primitive to use
  13530. * @param indexStart defines the starting index
  13531. * @param indexCount defines the number of index to draw
  13532. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13533. */
  13534. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13535. // Apply states
  13536. this.applyStates();
  13537. this._drawCalls.addCount(1, false);
  13538. // Render
  13539. var drawMode = this._drawMode(fillMode);
  13540. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13541. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13542. if (instancesCount) {
  13543. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13544. }
  13545. else {
  13546. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13547. }
  13548. };
  13549. /**
  13550. * Draw a list of unindexed primitives
  13551. * @param fillMode defines the primitive to use
  13552. * @param verticesStart defines the index of first vertex to draw
  13553. * @param verticesCount defines the count of vertices to draw
  13554. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13555. */
  13556. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13557. // Apply states
  13558. this.applyStates();
  13559. this._drawCalls.addCount(1, false);
  13560. var drawMode = this._drawMode(fillMode);
  13561. if (instancesCount) {
  13562. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13563. }
  13564. else {
  13565. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13566. }
  13567. };
  13568. Engine.prototype._drawMode = function (fillMode) {
  13569. switch (fillMode) {
  13570. // Triangle views
  13571. case BABYLON.Material.TriangleFillMode:
  13572. return this._gl.TRIANGLES;
  13573. case BABYLON.Material.PointFillMode:
  13574. return this._gl.POINTS;
  13575. case BABYLON.Material.WireFrameFillMode:
  13576. return this._gl.LINES;
  13577. // Draw modes
  13578. case BABYLON.Material.PointListDrawMode:
  13579. return this._gl.POINTS;
  13580. case BABYLON.Material.LineListDrawMode:
  13581. return this._gl.LINES;
  13582. case BABYLON.Material.LineLoopDrawMode:
  13583. return this._gl.LINE_LOOP;
  13584. case BABYLON.Material.LineStripDrawMode:
  13585. return this._gl.LINE_STRIP;
  13586. case BABYLON.Material.TriangleStripDrawMode:
  13587. return this._gl.TRIANGLE_STRIP;
  13588. case BABYLON.Material.TriangleFanDrawMode:
  13589. return this._gl.TRIANGLE_FAN;
  13590. default:
  13591. return this._gl.TRIANGLES;
  13592. }
  13593. };
  13594. // Shaders
  13595. /** @hidden */
  13596. Engine.prototype._releaseEffect = function (effect) {
  13597. if (this._compiledEffects[effect._key]) {
  13598. delete this._compiledEffects[effect._key];
  13599. this._deleteProgram(effect.getProgram());
  13600. }
  13601. };
  13602. /** @hidden */
  13603. Engine.prototype._deleteProgram = function (program) {
  13604. if (program) {
  13605. program.__SPECTOR_rebuildProgram = null;
  13606. if (program.transformFeedback) {
  13607. this.deleteTransformFeedback(program.transformFeedback);
  13608. program.transformFeedback = null;
  13609. }
  13610. this._gl.deleteProgram(program);
  13611. }
  13612. };
  13613. /**
  13614. * Create a new effect (used to store vertex/fragment shaders)
  13615. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13616. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13617. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13618. * @param samplers defines an array of string used to represent textures
  13619. * @param defines defines the string containing the defines to use to compile the shaders
  13620. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13621. * @param onCompiled defines a function to call when the effect creation is successful
  13622. * @param onError defines a function to call when the effect creation has failed
  13623. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13624. * @returns the new Effect
  13625. */
  13626. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13627. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13628. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13629. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13630. if (this._compiledEffects[name]) {
  13631. var compiledEffect = this._compiledEffects[name];
  13632. if (onCompiled && compiledEffect.isReady()) {
  13633. onCompiled(compiledEffect);
  13634. }
  13635. return compiledEffect;
  13636. }
  13637. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13638. effect._key = name;
  13639. this._compiledEffects[name] = effect;
  13640. return effect;
  13641. };
  13642. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13643. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13644. };
  13645. ;
  13646. Engine.prototype._compileRawShader = function (source, type) {
  13647. var gl = this._gl;
  13648. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13649. gl.shaderSource(shader, source);
  13650. gl.compileShader(shader);
  13651. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13652. var log = gl.getShaderInfoLog(shader);
  13653. if (log) {
  13654. throw new Error(log);
  13655. }
  13656. }
  13657. if (!shader) {
  13658. throw new Error("Something went wrong while compile the shader.");
  13659. }
  13660. return shader;
  13661. };
  13662. ;
  13663. /**
  13664. * Directly creates a webGL program
  13665. * @param vertexCode defines the vertex shader code to use
  13666. * @param fragmentCode defines the fragment shader code to use
  13667. * @param context defines the webGL context to use (if not set, the current one will be used)
  13668. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13669. * @returns the new webGL program
  13670. */
  13671. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13672. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13673. context = context || this._gl;
  13674. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13675. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13676. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13677. };
  13678. /**
  13679. * Creates a webGL program
  13680. * @param vertexCode defines the vertex shader code to use
  13681. * @param fragmentCode defines the fragment shader code to use
  13682. * @param defines defines the string containing the defines to use to compile the shaders
  13683. * @param context defines the webGL context to use (if not set, the current one will be used)
  13684. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13685. * @returns the new webGL program
  13686. */
  13687. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13688. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13689. context = context || this._gl;
  13690. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13691. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13692. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13693. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13694. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13695. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13696. return program;
  13697. };
  13698. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13699. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13700. var shaderProgram = context.createProgram();
  13701. if (!shaderProgram) {
  13702. throw new Error("Unable to create program");
  13703. }
  13704. context.attachShader(shaderProgram, vertexShader);
  13705. context.attachShader(shaderProgram, fragmentShader);
  13706. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13707. var transformFeedback = this.createTransformFeedback();
  13708. this.bindTransformFeedback(transformFeedback);
  13709. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13710. shaderProgram.transformFeedback = transformFeedback;
  13711. }
  13712. context.linkProgram(shaderProgram);
  13713. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13714. this.bindTransformFeedback(null);
  13715. }
  13716. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13717. if (!linked) {
  13718. var error = context.getProgramInfoLog(shaderProgram);
  13719. if (error) {
  13720. throw new Error(error);
  13721. }
  13722. }
  13723. if (this.validateShaderPrograms) {
  13724. context.validateProgram(shaderProgram);
  13725. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13726. if (!validated) {
  13727. var error = context.getProgramInfoLog(shaderProgram);
  13728. if (error) {
  13729. throw new Error(error);
  13730. }
  13731. }
  13732. }
  13733. context.deleteShader(vertexShader);
  13734. context.deleteShader(fragmentShader);
  13735. return shaderProgram;
  13736. };
  13737. /**
  13738. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13739. * @param shaderProgram defines the webGL program to use
  13740. * @param uniformsNames defines the list of uniform names
  13741. * @returns an array of webGL uniform locations
  13742. */
  13743. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13744. var results = new Array();
  13745. for (var index = 0; index < uniformsNames.length; index++) {
  13746. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13747. }
  13748. return results;
  13749. };
  13750. /**
  13751. * Gets the lsit of active attributes for a given webGL program
  13752. * @param shaderProgram defines the webGL program to use
  13753. * @param attributesNames defines the list of attribute names to get
  13754. * @returns an array of indices indicating the offset of each attribute
  13755. */
  13756. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13757. var results = [];
  13758. for (var index = 0; index < attributesNames.length; index++) {
  13759. try {
  13760. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13761. }
  13762. catch (e) {
  13763. results.push(-1);
  13764. }
  13765. }
  13766. return results;
  13767. };
  13768. /**
  13769. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13770. * @param effect defines the effect to activate
  13771. */
  13772. Engine.prototype.enableEffect = function (effect) {
  13773. if (!effect || effect === this._currentEffect) {
  13774. return;
  13775. }
  13776. // Use program
  13777. this.bindSamplers(effect);
  13778. this._currentEffect = effect;
  13779. if (effect.onBind) {
  13780. effect.onBind(effect);
  13781. }
  13782. if (effect._onBindObservable) {
  13783. effect._onBindObservable.notifyObservers(effect);
  13784. }
  13785. };
  13786. /**
  13787. * Set the value of an uniform to an array of int32
  13788. * @param uniform defines the webGL uniform location where to store the value
  13789. * @param array defines the array of int32 to store
  13790. */
  13791. Engine.prototype.setIntArray = function (uniform, array) {
  13792. if (!uniform)
  13793. return;
  13794. this._gl.uniform1iv(uniform, array);
  13795. };
  13796. /**
  13797. * Set the value of an uniform to an array of int32 (stored as vec2)
  13798. * @param uniform defines the webGL uniform location where to store the value
  13799. * @param array defines the array of int32 to store
  13800. */
  13801. Engine.prototype.setIntArray2 = function (uniform, array) {
  13802. if (!uniform || array.length % 2 !== 0)
  13803. return;
  13804. this._gl.uniform2iv(uniform, array);
  13805. };
  13806. /**
  13807. * Set the value of an uniform to an array of int32 (stored as vec3)
  13808. * @param uniform defines the webGL uniform location where to store the value
  13809. * @param array defines the array of int32 to store
  13810. */
  13811. Engine.prototype.setIntArray3 = function (uniform, array) {
  13812. if (!uniform || array.length % 3 !== 0)
  13813. return;
  13814. this._gl.uniform3iv(uniform, array);
  13815. };
  13816. /**
  13817. * Set the value of an uniform to an array of int32 (stored as vec4)
  13818. * @param uniform defines the webGL uniform location where to store the value
  13819. * @param array defines the array of int32 to store
  13820. */
  13821. Engine.prototype.setIntArray4 = function (uniform, array) {
  13822. if (!uniform || array.length % 4 !== 0)
  13823. return;
  13824. this._gl.uniform4iv(uniform, array);
  13825. };
  13826. /**
  13827. * Set the value of an uniform to an array of float32
  13828. * @param uniform defines the webGL uniform location where to store the value
  13829. * @param array defines the array of float32 to store
  13830. */
  13831. Engine.prototype.setFloatArray = function (uniform, array) {
  13832. if (!uniform)
  13833. return;
  13834. this._gl.uniform1fv(uniform, array);
  13835. };
  13836. /**
  13837. * Set the value of an uniform to an array of float32 (stored as vec2)
  13838. * @param uniform defines the webGL uniform location where to store the value
  13839. * @param array defines the array of float32 to store
  13840. */
  13841. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13842. if (!uniform || array.length % 2 !== 0)
  13843. return;
  13844. this._gl.uniform2fv(uniform, array);
  13845. };
  13846. /**
  13847. * Set the value of an uniform to an array of float32 (stored as vec3)
  13848. * @param uniform defines the webGL uniform location where to store the value
  13849. * @param array defines the array of float32 to store
  13850. */
  13851. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13852. if (!uniform || array.length % 3 !== 0)
  13853. return;
  13854. this._gl.uniform3fv(uniform, array);
  13855. };
  13856. /**
  13857. * Set the value of an uniform to an array of float32 (stored as vec4)
  13858. * @param uniform defines the webGL uniform location where to store the value
  13859. * @param array defines the array of float32 to store
  13860. */
  13861. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13862. if (!uniform || array.length % 4 !== 0)
  13863. return;
  13864. this._gl.uniform4fv(uniform, array);
  13865. };
  13866. /**
  13867. * Set the value of an uniform to an array of number
  13868. * @param uniform defines the webGL uniform location where to store the value
  13869. * @param array defines the array of number to store
  13870. */
  13871. Engine.prototype.setArray = function (uniform, array) {
  13872. if (!uniform)
  13873. return;
  13874. this._gl.uniform1fv(uniform, array);
  13875. };
  13876. /**
  13877. * Set the value of an uniform to an array of number (stored as vec2)
  13878. * @param uniform defines the webGL uniform location where to store the value
  13879. * @param array defines the array of number to store
  13880. */
  13881. Engine.prototype.setArray2 = function (uniform, array) {
  13882. if (!uniform || array.length % 2 !== 0)
  13883. return;
  13884. this._gl.uniform2fv(uniform, array);
  13885. };
  13886. /**
  13887. * Set the value of an uniform to an array of number (stored as vec3)
  13888. * @param uniform defines the webGL uniform location where to store the value
  13889. * @param array defines the array of number to store
  13890. */
  13891. Engine.prototype.setArray3 = function (uniform, array) {
  13892. if (!uniform || array.length % 3 !== 0)
  13893. return;
  13894. this._gl.uniform3fv(uniform, array);
  13895. };
  13896. /**
  13897. * Set the value of an uniform to an array of number (stored as vec4)
  13898. * @param uniform defines the webGL uniform location where to store the value
  13899. * @param array defines the array of number to store
  13900. */
  13901. Engine.prototype.setArray4 = function (uniform, array) {
  13902. if (!uniform || array.length % 4 !== 0)
  13903. return;
  13904. this._gl.uniform4fv(uniform, array);
  13905. };
  13906. /**
  13907. * Set the value of an uniform to an array of float32 (stored as matrices)
  13908. * @param uniform defines the webGL uniform location where to store the value
  13909. * @param matrices defines the array of float32 to store
  13910. */
  13911. Engine.prototype.setMatrices = function (uniform, matrices) {
  13912. if (!uniform)
  13913. return;
  13914. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13915. };
  13916. /**
  13917. * Set the value of an uniform to a matrix
  13918. * @param uniform defines the webGL uniform location where to store the value
  13919. * @param matrix defines the matrix to store
  13920. */
  13921. Engine.prototype.setMatrix = function (uniform, matrix) {
  13922. if (!uniform)
  13923. return;
  13924. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13925. };
  13926. /**
  13927. * Set the value of an uniform to a matrix (3x3)
  13928. * @param uniform defines the webGL uniform location where to store the value
  13929. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13930. */
  13931. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13932. if (!uniform)
  13933. return;
  13934. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13935. };
  13936. /**
  13937. * Set the value of an uniform to a matrix (2x2)
  13938. * @param uniform defines the webGL uniform location where to store the value
  13939. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13940. */
  13941. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13942. if (!uniform)
  13943. return;
  13944. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13945. };
  13946. /**
  13947. * Set the value of an uniform to a number (int)
  13948. * @param uniform defines the webGL uniform location where to store the value
  13949. * @param value defines the int number to store
  13950. */
  13951. Engine.prototype.setInt = function (uniform, value) {
  13952. if (!uniform)
  13953. return;
  13954. this._gl.uniform1i(uniform, value);
  13955. };
  13956. /**
  13957. * Set the value of an uniform to a number (float)
  13958. * @param uniform defines the webGL uniform location where to store the value
  13959. * @param value defines the float number to store
  13960. */
  13961. Engine.prototype.setFloat = function (uniform, value) {
  13962. if (!uniform)
  13963. return;
  13964. this._gl.uniform1f(uniform, value);
  13965. };
  13966. /**
  13967. * Set the value of an uniform to a vec2
  13968. * @param uniform defines the webGL uniform location where to store the value
  13969. * @param x defines the 1st component of the value
  13970. * @param y defines the 2nd component of the value
  13971. */
  13972. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13973. if (!uniform)
  13974. return;
  13975. this._gl.uniform2f(uniform, x, y);
  13976. };
  13977. /**
  13978. * Set the value of an uniform to a vec3
  13979. * @param uniform defines the webGL uniform location where to store the value
  13980. * @param x defines the 1st component of the value
  13981. * @param y defines the 2nd component of the value
  13982. * @param z defines the 3rd component of the value
  13983. */
  13984. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13985. if (!uniform)
  13986. return;
  13987. this._gl.uniform3f(uniform, x, y, z);
  13988. };
  13989. /**
  13990. * Set the value of an uniform to a boolean
  13991. * @param uniform defines the webGL uniform location where to store the value
  13992. * @param bool defines the boolean to store
  13993. */
  13994. Engine.prototype.setBool = function (uniform, bool) {
  13995. if (!uniform)
  13996. return;
  13997. this._gl.uniform1i(uniform, bool);
  13998. };
  13999. /**
  14000. * Set the value of an uniform to a vec4
  14001. * @param uniform defines the webGL uniform location where to store the value
  14002. * @param x defines the 1st component of the value
  14003. * @param y defines the 2nd component of the value
  14004. * @param z defines the 3rd component of the value
  14005. * @param w defines the 4th component of the value
  14006. */
  14007. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14008. if (!uniform)
  14009. return;
  14010. this._gl.uniform4f(uniform, x, y, z, w);
  14011. };
  14012. /**
  14013. * Set the value of an uniform to a Color3
  14014. * @param uniform defines the webGL uniform location where to store the value
  14015. * @param color3 defines the color to store
  14016. */
  14017. Engine.prototype.setColor3 = function (uniform, color3) {
  14018. if (!uniform)
  14019. return;
  14020. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14021. };
  14022. /**
  14023. * Set the value of an uniform to a Color3 and an alpha value
  14024. * @param uniform defines the webGL uniform location where to store the value
  14025. * @param color3 defines the color to store
  14026. * @param alpha defines the alpha component to store
  14027. */
  14028. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14029. if (!uniform)
  14030. return;
  14031. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14032. };
  14033. /**
  14034. * Sets a Color4 on a uniform variable
  14035. * @param uniform defines the uniform location
  14036. * @param color4 defines the value to be set
  14037. */
  14038. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14039. if (!uniform)
  14040. return;
  14041. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14042. };
  14043. // States
  14044. /**
  14045. * Set various states to the webGL context
  14046. * @param culling defines backface culling state
  14047. * @param zOffset defines the value to apply to zOffset (0 by default)
  14048. * @param force defines if states must be applied even if cache is up to date
  14049. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14050. */
  14051. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14052. if (zOffset === void 0) { zOffset = 0; }
  14053. if (reverseSide === void 0) { reverseSide = false; }
  14054. // Culling
  14055. if (this._depthCullingState.cull !== culling || force) {
  14056. this._depthCullingState.cull = culling;
  14057. }
  14058. // Cull face
  14059. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14060. if (this._depthCullingState.cullFace !== cullFace || force) {
  14061. this._depthCullingState.cullFace = cullFace;
  14062. }
  14063. // Z offset
  14064. this.setZOffset(zOffset);
  14065. // Front face
  14066. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14067. if (this._depthCullingState.frontFace !== frontFace || force) {
  14068. this._depthCullingState.frontFace = frontFace;
  14069. }
  14070. };
  14071. /**
  14072. * Set the z offset to apply to current rendering
  14073. * @param value defines the offset to apply
  14074. */
  14075. Engine.prototype.setZOffset = function (value) {
  14076. this._depthCullingState.zOffset = value;
  14077. };
  14078. /**
  14079. * Gets the current value of the zOffset
  14080. * @returns the current zOffset state
  14081. */
  14082. Engine.prototype.getZOffset = function () {
  14083. return this._depthCullingState.zOffset;
  14084. };
  14085. /**
  14086. * Enable or disable depth buffering
  14087. * @param enable defines the state to set
  14088. */
  14089. Engine.prototype.setDepthBuffer = function (enable) {
  14090. this._depthCullingState.depthTest = enable;
  14091. };
  14092. /**
  14093. * Gets a boolean indicating if depth writing is enabled
  14094. * @returns the current depth writing state
  14095. */
  14096. Engine.prototype.getDepthWrite = function () {
  14097. return this._depthCullingState.depthMask;
  14098. };
  14099. /**
  14100. * Enable or disable depth writing
  14101. * @param enable defines the state to set
  14102. */
  14103. Engine.prototype.setDepthWrite = function (enable) {
  14104. this._depthCullingState.depthMask = enable;
  14105. };
  14106. /**
  14107. * Enable or disable color writing
  14108. * @param enable defines the state to set
  14109. */
  14110. Engine.prototype.setColorWrite = function (enable) {
  14111. this._gl.colorMask(enable, enable, enable, enable);
  14112. this._colorWrite = enable;
  14113. };
  14114. /**
  14115. * Gets a boolean indicating if color writing is enabled
  14116. * @returns the current color writing state
  14117. */
  14118. Engine.prototype.getColorWrite = function () {
  14119. return this._colorWrite;
  14120. };
  14121. /**
  14122. * Sets alpha constants used by some alpha blending modes
  14123. * @param r defines the red component
  14124. * @param g defines the green component
  14125. * @param b defines the blue component
  14126. * @param a defines the alpha component
  14127. */
  14128. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14129. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14130. };
  14131. /**
  14132. * Sets the current alpha mode
  14133. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14134. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14135. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14136. */
  14137. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14138. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14139. if (this._alphaMode === mode) {
  14140. return;
  14141. }
  14142. switch (mode) {
  14143. case Engine.ALPHA_DISABLE:
  14144. this._alphaState.alphaBlend = false;
  14145. break;
  14146. case Engine.ALPHA_PREMULTIPLIED:
  14147. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14148. this._alphaState.alphaBlend = true;
  14149. break;
  14150. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14151. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14152. this._alphaState.alphaBlend = true;
  14153. break;
  14154. case Engine.ALPHA_COMBINE:
  14155. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14156. this._alphaState.alphaBlend = true;
  14157. break;
  14158. case Engine.ALPHA_ONEONE:
  14159. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14160. this._alphaState.alphaBlend = true;
  14161. break;
  14162. case Engine.ALPHA_ADD:
  14163. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14164. this._alphaState.alphaBlend = true;
  14165. break;
  14166. case Engine.ALPHA_SUBTRACT:
  14167. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14168. this._alphaState.alphaBlend = true;
  14169. break;
  14170. case Engine.ALPHA_MULTIPLY:
  14171. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14172. this._alphaState.alphaBlend = true;
  14173. break;
  14174. case Engine.ALPHA_MAXIMIZED:
  14175. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14176. this._alphaState.alphaBlend = true;
  14177. break;
  14178. case Engine.ALPHA_INTERPOLATE:
  14179. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14180. this._alphaState.alphaBlend = true;
  14181. break;
  14182. case Engine.ALPHA_SCREENMODE:
  14183. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14184. this._alphaState.alphaBlend = true;
  14185. break;
  14186. }
  14187. if (!noDepthWriteChange) {
  14188. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14189. }
  14190. this._alphaMode = mode;
  14191. };
  14192. /**
  14193. * Gets the current alpha mode
  14194. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14195. * @returns the current alpha mode
  14196. */
  14197. Engine.prototype.getAlphaMode = function () {
  14198. return this._alphaMode;
  14199. };
  14200. // Textures
  14201. /**
  14202. * Clears the list of texture accessible through engine.
  14203. * This can help preventing texture load conflict due to name collision.
  14204. */
  14205. Engine.prototype.clearInternalTexturesCache = function () {
  14206. this._internalTexturesCache = [];
  14207. };
  14208. /**
  14209. * Force the entire cache to be cleared
  14210. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14211. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14212. */
  14213. Engine.prototype.wipeCaches = function (bruteForce) {
  14214. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14215. return;
  14216. }
  14217. this._currentEffect = null;
  14218. this._unpackFlipYCached = null;
  14219. this._viewportCached.x = 0;
  14220. this._viewportCached.y = 0;
  14221. this._viewportCached.z = 0;
  14222. this._viewportCached.w = 0;
  14223. if (bruteForce) {
  14224. this.resetTextureCache();
  14225. this._currentProgram = null;
  14226. this._stencilState.reset();
  14227. this._depthCullingState.reset();
  14228. this.setDepthFunctionToLessOrEqual();
  14229. this._alphaState.reset();
  14230. }
  14231. this._resetVertexBufferBinding();
  14232. this._cachedIndexBuffer = null;
  14233. this._cachedEffectForVertexBuffers = null;
  14234. this._unbindVertexArrayObject();
  14235. this.bindIndexBuffer(null);
  14236. };
  14237. /**
  14238. * Set the compressed texture format to use, based on the formats you have, and the formats
  14239. * supported by the hardware / browser.
  14240. *
  14241. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14242. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14243. * to API arguments needed to compressed textures. This puts the burden on the container
  14244. * generator to house the arcane code for determining these for current & future formats.
  14245. *
  14246. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14247. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14248. *
  14249. * Note: The result of this call is not taken into account when a texture is base64.
  14250. *
  14251. * @param formatsAvailable defines the list of those format families you have created
  14252. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14253. *
  14254. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14255. * @returns The extension selected.
  14256. */
  14257. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14258. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14259. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14260. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14261. return this._textureFormatInUse = this._texturesSupported[i];
  14262. }
  14263. }
  14264. }
  14265. // actively set format to nothing, to allow this to be called more than once
  14266. // and possibly fail the 2nd time
  14267. this._textureFormatInUse = null;
  14268. return null;
  14269. };
  14270. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14271. var gl = this._gl;
  14272. var magFilter = gl.NEAREST;
  14273. var minFilter = gl.NEAREST;
  14274. switch (samplingMode) {
  14275. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14276. magFilter = gl.LINEAR;
  14277. if (generateMipMaps) {
  14278. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14279. }
  14280. else {
  14281. minFilter = gl.LINEAR;
  14282. }
  14283. break;
  14284. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14285. magFilter = gl.LINEAR;
  14286. if (generateMipMaps) {
  14287. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14288. }
  14289. else {
  14290. minFilter = gl.LINEAR;
  14291. }
  14292. break;
  14293. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14294. magFilter = gl.NEAREST;
  14295. if (generateMipMaps) {
  14296. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14297. }
  14298. else {
  14299. minFilter = gl.NEAREST;
  14300. }
  14301. break;
  14302. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14303. magFilter = gl.NEAREST;
  14304. if (generateMipMaps) {
  14305. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14306. }
  14307. else {
  14308. minFilter = gl.NEAREST;
  14309. }
  14310. break;
  14311. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14312. magFilter = gl.NEAREST;
  14313. if (generateMipMaps) {
  14314. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14315. }
  14316. else {
  14317. minFilter = gl.LINEAR;
  14318. }
  14319. break;
  14320. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14321. magFilter = gl.NEAREST;
  14322. if (generateMipMaps) {
  14323. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14324. }
  14325. else {
  14326. minFilter = gl.LINEAR;
  14327. }
  14328. break;
  14329. case Engine.TEXTURE_NEAREST_LINEAR:
  14330. magFilter = gl.NEAREST;
  14331. minFilter = gl.LINEAR;
  14332. break;
  14333. case Engine.TEXTURE_NEAREST_NEAREST:
  14334. magFilter = gl.NEAREST;
  14335. minFilter = gl.NEAREST;
  14336. break;
  14337. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14338. magFilter = gl.LINEAR;
  14339. if (generateMipMaps) {
  14340. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14341. }
  14342. else {
  14343. minFilter = gl.NEAREST;
  14344. }
  14345. break;
  14346. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14347. magFilter = gl.LINEAR;
  14348. if (generateMipMaps) {
  14349. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14350. }
  14351. else {
  14352. minFilter = gl.NEAREST;
  14353. }
  14354. break;
  14355. case Engine.TEXTURE_LINEAR_LINEAR:
  14356. magFilter = gl.LINEAR;
  14357. minFilter = gl.LINEAR;
  14358. break;
  14359. case Engine.TEXTURE_LINEAR_NEAREST:
  14360. magFilter = gl.LINEAR;
  14361. minFilter = gl.NEAREST;
  14362. break;
  14363. }
  14364. return {
  14365. min: minFilter,
  14366. mag: magFilter
  14367. };
  14368. };
  14369. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14370. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14371. var img;
  14372. var onload = function () {
  14373. loadedImages[index] = img;
  14374. loadedImages._internalCount++;
  14375. if (scene) {
  14376. scene._removePendingData(img);
  14377. }
  14378. if (loadedImages._internalCount === 6) {
  14379. onfinish(loadedImages);
  14380. }
  14381. };
  14382. var onerror = function (message, exception) {
  14383. if (scene) {
  14384. scene._removePendingData(img);
  14385. }
  14386. if (onErrorCallBack) {
  14387. onErrorCallBack(message, exception);
  14388. }
  14389. };
  14390. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14391. if (scene) {
  14392. scene._addPendingData(img);
  14393. }
  14394. };
  14395. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14396. if (onError === void 0) { onError = null; }
  14397. var loadedImages = [];
  14398. loadedImages._internalCount = 0;
  14399. for (var index = 0; index < 6; index++) {
  14400. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14401. }
  14402. };
  14403. ;
  14404. /** @hidden */
  14405. Engine.prototype._createTexture = function () {
  14406. var texture = this._gl.createTexture();
  14407. if (!texture) {
  14408. throw new Error("Unable to create texture");
  14409. }
  14410. return texture;
  14411. };
  14412. /**
  14413. * Usually called from BABYLON.Texture.ts.
  14414. * Passed information to create a WebGLTexture
  14415. * @param urlArg defines a value which contains one of the following:
  14416. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14417. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14418. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14419. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14420. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14421. * @param scene needed for loading to the correct scene
  14422. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14423. * @param onLoad optional callback to be called upon successful completion
  14424. * @param onError optional callback to be called upon failure
  14425. * @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
  14426. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14427. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14428. * @param forcedExtension defines the extension to use to pick the right loader
  14429. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14430. */
  14431. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14432. var _this = this;
  14433. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14434. if (onLoad === void 0) { onLoad = null; }
  14435. if (onError === void 0) { onError = null; }
  14436. if (buffer === void 0) { buffer = null; }
  14437. if (fallback === void 0) { fallback = null; }
  14438. if (format === void 0) { format = null; }
  14439. if (forcedExtension === void 0) { forcedExtension = null; }
  14440. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14441. var fromData = url.substr(0, 5) === "data:";
  14442. var fromBlob = url.substr(0, 5) === "blob:";
  14443. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14444. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14445. // establish the file extension, if possible
  14446. var lastDot = url.lastIndexOf('.');
  14447. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14448. var loader = null;
  14449. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14450. var availableLoader = _a[_i];
  14451. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14452. loader = availableLoader;
  14453. break;
  14454. }
  14455. }
  14456. if (loader) {
  14457. url = loader.transformUrl(url, this._textureFormatInUse);
  14458. }
  14459. if (scene) {
  14460. scene._addPendingData(texture);
  14461. }
  14462. texture.url = url;
  14463. texture.generateMipMaps = !noMipmap;
  14464. texture.samplingMode = samplingMode;
  14465. texture.invertY = invertY;
  14466. if (!this._doNotHandleContextLost) {
  14467. // Keep a link to the buffer only if we plan to handle context lost
  14468. texture._buffer = buffer;
  14469. }
  14470. var onLoadObserver = null;
  14471. if (onLoad && !fallback) {
  14472. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14473. }
  14474. if (!fallback)
  14475. this._internalTexturesCache.push(texture);
  14476. var onInternalError = function (message, exception) {
  14477. if (scene) {
  14478. scene._removePendingData(texture);
  14479. }
  14480. var customFallback = false;
  14481. if (loader) {
  14482. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14483. if (fallbackUrl) {
  14484. // Add Back
  14485. customFallback = true;
  14486. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14487. }
  14488. }
  14489. if (!customFallback) {
  14490. if (onLoadObserver) {
  14491. texture.onLoadedObservable.remove(onLoadObserver);
  14492. }
  14493. if (BABYLON.Tools.UseFallbackTexture) {
  14494. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14495. }
  14496. }
  14497. if (onError) {
  14498. onError(message || "Unknown error", exception);
  14499. }
  14500. };
  14501. // processing for non-image formats
  14502. if (loader) {
  14503. var callback = function (data) {
  14504. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14505. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14506. done();
  14507. return false;
  14508. }, samplingMode);
  14509. });
  14510. };
  14511. if (!buffer) {
  14512. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14513. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14514. });
  14515. }
  14516. else {
  14517. callback(buffer);
  14518. }
  14519. }
  14520. else {
  14521. var onload = function (img) {
  14522. if (fromBlob && !_this._doNotHandleContextLost) {
  14523. // We need to store the image if we need to rebuild the texture
  14524. // in case of a webgl context lost
  14525. texture._buffer = img;
  14526. }
  14527. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14528. var gl = _this._gl;
  14529. var isPot = (img.width === potWidth && img.height === potHeight);
  14530. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14531. if (isPot) {
  14532. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14533. return false;
  14534. }
  14535. var maxTextureSize = _this._caps.maxTextureSize;
  14536. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14537. _this._prepareWorkingCanvas();
  14538. if (!_this._workingCanvas || !_this._workingContext) {
  14539. return false;
  14540. }
  14541. _this._workingCanvas.width = potWidth;
  14542. _this._workingCanvas.height = potHeight;
  14543. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14544. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14545. texture.width = potWidth;
  14546. texture.height = potHeight;
  14547. return false;
  14548. }
  14549. else {
  14550. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14551. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14552. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14553. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14554. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14555. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14556. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14557. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14558. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14559. _this._releaseTexture(source_1);
  14560. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14561. continuationCallback();
  14562. });
  14563. }
  14564. return true;
  14565. }, samplingMode);
  14566. };
  14567. if (!fromData || isBase64) {
  14568. if (buffer instanceof HTMLImageElement) {
  14569. onload(buffer);
  14570. }
  14571. else {
  14572. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14573. }
  14574. }
  14575. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14576. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14577. }
  14578. else {
  14579. onload(buffer);
  14580. }
  14581. }
  14582. return texture;
  14583. };
  14584. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14585. var _this = this;
  14586. var rtt = this.createRenderTargetTexture({
  14587. width: destination.width,
  14588. height: destination.height,
  14589. }, {
  14590. generateMipMaps: false,
  14591. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14592. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14593. generateDepthBuffer: false,
  14594. generateStencilBuffer: false
  14595. });
  14596. if (!this._rescalePostProcess) {
  14597. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14598. }
  14599. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14600. _this._rescalePostProcess.onApply = function (effect) {
  14601. effect._bindTexture("textureSampler", source);
  14602. };
  14603. var hostingScene = scene;
  14604. if (!hostingScene) {
  14605. hostingScene = _this.scenes[_this.scenes.length - 1];
  14606. }
  14607. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14608. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14609. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14610. _this.unBindFramebuffer(rtt);
  14611. _this._releaseTexture(rtt);
  14612. if (onComplete) {
  14613. onComplete();
  14614. }
  14615. });
  14616. };
  14617. /**
  14618. * Update a raw texture
  14619. * @param texture defines the texture to update
  14620. * @param data defines the data to store in the texture
  14621. * @param format defines the format of the data
  14622. * @param invertY defines if data must be stored with Y axis inverted
  14623. * @param compression defines the compression used (null by default)
  14624. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14625. */
  14626. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14627. if (compression === void 0) { compression = null; }
  14628. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14629. if (!texture) {
  14630. return;
  14631. }
  14632. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14633. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14634. // babylon's internalFormat but gl's texImage2D format
  14635. var internalFormat = this._getInternalFormat(format);
  14636. var textureType = this._getWebGLTextureType(type);
  14637. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14638. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14639. if (!this._doNotHandleContextLost) {
  14640. texture._bufferView = data;
  14641. texture.format = format;
  14642. texture.type = type;
  14643. texture.invertY = invertY;
  14644. texture._compression = compression;
  14645. }
  14646. if (texture.width % 4 !== 0) {
  14647. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14648. }
  14649. if (compression && data) {
  14650. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14651. }
  14652. else {
  14653. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14654. }
  14655. if (texture.generateMipMaps) {
  14656. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14657. }
  14658. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14659. // this.resetTextureCache();
  14660. texture.isReady = true;
  14661. };
  14662. /**
  14663. * Creates a raw texture
  14664. * @param data defines the data to store in the texture
  14665. * @param width defines the width of the texture
  14666. * @param height defines the height of the texture
  14667. * @param format defines the format of the data
  14668. * @param generateMipMaps defines if the engine should generate the mip levels
  14669. * @param invertY defines if data must be stored with Y axis inverted
  14670. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14671. * @param compression defines the compression used (null by default)
  14672. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14673. * @returns the raw texture inside an InternalTexture
  14674. */
  14675. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14676. if (compression === void 0) { compression = null; }
  14677. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14678. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14679. texture.baseWidth = width;
  14680. texture.baseHeight = height;
  14681. texture.width = width;
  14682. texture.height = height;
  14683. texture.format = format;
  14684. texture.generateMipMaps = generateMipMaps;
  14685. texture.samplingMode = samplingMode;
  14686. texture.invertY = invertY;
  14687. texture._compression = compression;
  14688. texture.type = type;
  14689. if (!this._doNotHandleContextLost) {
  14690. texture._bufferView = data;
  14691. }
  14692. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14693. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14694. // Filters
  14695. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14696. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14697. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14698. if (generateMipMaps) {
  14699. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14700. }
  14701. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14702. this._internalTexturesCache.push(texture);
  14703. return texture;
  14704. };
  14705. /** @hidden */
  14706. Engine.prototype._unpackFlipY = function (value) {
  14707. if (this._unpackFlipYCached !== value) {
  14708. this._unpackFlipYCached = value;
  14709. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14710. }
  14711. };
  14712. /** @hidden */
  14713. Engine.prototype._getUnpackAlignement = function () {
  14714. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14715. };
  14716. /**
  14717. * Creates a dynamic texture
  14718. * @param width defines the width of the texture
  14719. * @param height defines the height of the texture
  14720. * @param generateMipMaps defines if the engine should generate the mip levels
  14721. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14722. * @returns the dynamic texture inside an InternalTexture
  14723. */
  14724. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14725. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14726. texture.baseWidth = width;
  14727. texture.baseHeight = height;
  14728. if (generateMipMaps) {
  14729. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14730. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14731. }
  14732. // this.resetTextureCache();
  14733. texture.width = width;
  14734. texture.height = height;
  14735. texture.isReady = false;
  14736. texture.generateMipMaps = generateMipMaps;
  14737. texture.samplingMode = samplingMode;
  14738. this.updateTextureSamplingMode(samplingMode, texture);
  14739. this._internalTexturesCache.push(texture);
  14740. return texture;
  14741. };
  14742. /**
  14743. * Update the sampling mode of a given texture
  14744. * @param samplingMode defines the required sampling mode
  14745. * @param texture defines the texture to update
  14746. */
  14747. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14748. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14749. if (texture.isCube) {
  14750. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14751. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14752. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14753. }
  14754. else if (texture.is3D) {
  14755. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14756. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14757. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14758. }
  14759. else {
  14760. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14761. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14762. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14763. }
  14764. texture.samplingMode = samplingMode;
  14765. };
  14766. /**
  14767. * Update the content of a dynamic texture
  14768. * @param texture defines the texture to update
  14769. * @param canvas defines the canvas containing the source
  14770. * @param invertY defines if data must be stored with Y axis inverted
  14771. * @param premulAlpha defines if alpha is stored as premultiplied
  14772. * @param format defines the format of the data
  14773. */
  14774. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14775. if (premulAlpha === void 0) { premulAlpha = false; }
  14776. if (!texture) {
  14777. return;
  14778. }
  14779. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14780. this._unpackFlipY(invertY);
  14781. if (premulAlpha) {
  14782. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14783. }
  14784. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14785. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14786. if (texture.generateMipMaps) {
  14787. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14788. }
  14789. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14790. if (premulAlpha) {
  14791. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14792. }
  14793. texture.isReady = true;
  14794. };
  14795. /**
  14796. * Update a video texture
  14797. * @param texture defines the texture to update
  14798. * @param video defines the video element to use
  14799. * @param invertY defines if data must be stored with Y axis inverted
  14800. */
  14801. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14802. if (!texture || texture._isDisabled) {
  14803. return;
  14804. }
  14805. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14806. this._unpackFlipY(!invertY); // Video are upside down by default
  14807. try {
  14808. // Testing video texture support
  14809. if (this._videoTextureSupported === undefined) {
  14810. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14811. if (this._gl.getError() !== 0) {
  14812. this._videoTextureSupported = false;
  14813. }
  14814. else {
  14815. this._videoTextureSupported = true;
  14816. }
  14817. }
  14818. // Copy video through the current working canvas if video texture is not supported
  14819. if (!this._videoTextureSupported) {
  14820. if (!texture._workingCanvas) {
  14821. texture._workingCanvas = document.createElement("canvas");
  14822. var context = texture._workingCanvas.getContext("2d");
  14823. if (!context) {
  14824. throw new Error("Unable to get 2d context");
  14825. }
  14826. texture._workingContext = context;
  14827. texture._workingCanvas.width = texture.width;
  14828. texture._workingCanvas.height = texture.height;
  14829. }
  14830. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14831. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14832. }
  14833. else {
  14834. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14835. }
  14836. if (texture.generateMipMaps) {
  14837. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14838. }
  14839. if (!wasPreviouslyBound) {
  14840. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14841. }
  14842. // this.resetTextureCache();
  14843. texture.isReady = true;
  14844. }
  14845. catch (ex) {
  14846. // Something unexpected
  14847. // Let's disable the texture
  14848. texture._isDisabled = true;
  14849. }
  14850. };
  14851. /**
  14852. * Updates a depth texture Comparison Mode and Function.
  14853. * If the comparison Function is equal to 0, the mode will be set to none.
  14854. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14855. * @param texture The texture to set the comparison function for
  14856. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14857. */
  14858. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14859. if (this.webGLVersion === 1) {
  14860. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14861. return;
  14862. }
  14863. var gl = this._gl;
  14864. if (texture.isCube) {
  14865. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14866. if (comparisonFunction === 0) {
  14867. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14868. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14869. }
  14870. else {
  14871. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14873. }
  14874. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14875. }
  14876. else {
  14877. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14878. if (comparisonFunction === 0) {
  14879. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14880. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14881. }
  14882. else {
  14883. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14884. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14885. }
  14886. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14887. }
  14888. texture._comparisonFunction = comparisonFunction;
  14889. };
  14890. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14891. var width = size.width || size;
  14892. var height = size.height || size;
  14893. internalTexture.baseWidth = width;
  14894. internalTexture.baseHeight = height;
  14895. internalTexture.width = width;
  14896. internalTexture.height = height;
  14897. internalTexture.isReady = true;
  14898. internalTexture.samples = 1;
  14899. internalTexture.generateMipMaps = false;
  14900. internalTexture._generateDepthBuffer = true;
  14901. internalTexture._generateStencilBuffer = generateStencil;
  14902. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14903. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14904. internalTexture._comparisonFunction = comparisonFunction;
  14905. var gl = this._gl;
  14906. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14907. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14908. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14909. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14910. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14911. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14912. if (comparisonFunction === 0) {
  14913. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14914. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14915. }
  14916. else {
  14917. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14918. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14919. }
  14920. };
  14921. /**
  14922. * Creates a depth stencil texture.
  14923. * This is only available in WebGL 2 or with the depth texture extension available.
  14924. * @param size The size of face edge in the texture.
  14925. * @param options The options defining the texture.
  14926. * @returns The texture
  14927. */
  14928. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14929. if (options.isCube) {
  14930. var width = size.width || size;
  14931. return this._createDepthStencilCubeTexture(width, options);
  14932. }
  14933. else {
  14934. return this._createDepthStencilTexture(size, options);
  14935. }
  14936. };
  14937. /**
  14938. * Creates a depth stencil texture.
  14939. * This is only available in WebGL 2 or with the depth texture extension available.
  14940. * @param size The size of face edge in the texture.
  14941. * @param options The options defining the texture.
  14942. * @returns The texture
  14943. */
  14944. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14945. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14946. if (!this._caps.depthTextureExtension) {
  14947. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14948. return internalTexture;
  14949. }
  14950. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14951. var gl = this._gl;
  14952. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14953. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14954. if (this.webGLVersion > 1) {
  14955. if (internalOptions.generateStencil) {
  14956. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14957. }
  14958. else {
  14959. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14960. }
  14961. }
  14962. else {
  14963. if (internalOptions.generateStencil) {
  14964. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14965. }
  14966. else {
  14967. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14968. }
  14969. }
  14970. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14971. return internalTexture;
  14972. };
  14973. /**
  14974. * Creates a depth stencil cube texture.
  14975. * This is only available in WebGL 2.
  14976. * @param size The size of face edge in the cube texture.
  14977. * @param options The options defining the cube texture.
  14978. * @returns The cube texture
  14979. */
  14980. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14981. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14982. internalTexture.isCube = true;
  14983. if (this.webGLVersion === 1) {
  14984. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14985. return internalTexture;
  14986. }
  14987. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14988. var gl = this._gl;
  14989. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14990. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14991. // Create the depth/stencil buffer
  14992. for (var face = 0; face < 6; face++) {
  14993. if (internalOptions.generateStencil) {
  14994. 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);
  14995. }
  14996. else {
  14997. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14998. }
  14999. }
  15000. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15001. return internalTexture;
  15002. };
  15003. /**
  15004. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15005. * @param renderTarget The render target to set the frame buffer for
  15006. */
  15007. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15008. // Create the framebuffer
  15009. var internalTexture = renderTarget.getInternalTexture();
  15010. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15011. return;
  15012. }
  15013. var gl = this._gl;
  15014. var depthStencilTexture = renderTarget.depthStencilTexture;
  15015. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15016. if (depthStencilTexture.isCube) {
  15017. if (depthStencilTexture._generateStencilBuffer) {
  15018. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15019. }
  15020. else {
  15021. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15022. }
  15023. }
  15024. else {
  15025. if (depthStencilTexture._generateStencilBuffer) {
  15026. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15027. }
  15028. else {
  15029. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15030. }
  15031. }
  15032. this.bindUnboundFramebuffer(null);
  15033. };
  15034. /**
  15035. * Creates a new render target texture
  15036. * @param size defines the size of the texture
  15037. * @param options defines the options used to create the texture
  15038. * @returns a new render target texture stored in an InternalTexture
  15039. */
  15040. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15041. var fullOptions = new RenderTargetCreationOptions();
  15042. if (options !== undefined && typeof options === "object") {
  15043. fullOptions.generateMipMaps = options.generateMipMaps;
  15044. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15045. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15046. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15047. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15048. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15049. }
  15050. else {
  15051. fullOptions.generateMipMaps = options;
  15052. fullOptions.generateDepthBuffer = true;
  15053. fullOptions.generateStencilBuffer = false;
  15054. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15055. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15056. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15057. }
  15058. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15059. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15060. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15061. }
  15062. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15063. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15064. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15065. }
  15066. var gl = this._gl;
  15067. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15068. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15069. var width = size.width || size;
  15070. var height = size.height || size;
  15071. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15072. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15073. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15074. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15075. }
  15076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15080. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15081. // Create the framebuffer
  15082. var currentFrameBuffer = this._currentFramebuffer;
  15083. var framebuffer = gl.createFramebuffer();
  15084. this.bindUnboundFramebuffer(framebuffer);
  15085. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15086. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15087. if (fullOptions.generateMipMaps) {
  15088. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15089. }
  15090. // Unbind
  15091. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15092. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15093. this.bindUnboundFramebuffer(currentFrameBuffer);
  15094. texture._framebuffer = framebuffer;
  15095. texture.baseWidth = width;
  15096. texture.baseHeight = height;
  15097. texture.width = width;
  15098. texture.height = height;
  15099. texture.isReady = true;
  15100. texture.samples = 1;
  15101. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15102. texture.samplingMode = fullOptions.samplingMode;
  15103. texture.type = fullOptions.type;
  15104. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15105. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15106. // this.resetTextureCache();
  15107. this._internalTexturesCache.push(texture);
  15108. return texture;
  15109. };
  15110. /**
  15111. * Create a multi render target texture
  15112. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15113. * @param size defines the size of the texture
  15114. * @param options defines the creation options
  15115. * @returns the cube texture as an InternalTexture
  15116. */
  15117. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15118. var generateMipMaps = false;
  15119. var generateDepthBuffer = true;
  15120. var generateStencilBuffer = false;
  15121. var generateDepthTexture = false;
  15122. var textureCount = 1;
  15123. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15124. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15125. var types = new Array();
  15126. var samplingModes = new Array();
  15127. if (options !== undefined) {
  15128. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15129. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15130. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15131. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15132. textureCount = options.textureCount || 1;
  15133. if (options.types) {
  15134. types = options.types;
  15135. }
  15136. if (options.samplingModes) {
  15137. samplingModes = options.samplingModes;
  15138. }
  15139. }
  15140. var gl = this._gl;
  15141. // Create the framebuffer
  15142. var framebuffer = gl.createFramebuffer();
  15143. this.bindUnboundFramebuffer(framebuffer);
  15144. var width = size.width || size;
  15145. var height = size.height || size;
  15146. var textures = [];
  15147. var attachments = [];
  15148. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15149. for (var i = 0; i < textureCount; i++) {
  15150. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15151. var type = types[i] || defaultType;
  15152. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15153. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15154. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15155. }
  15156. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15157. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15158. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15159. }
  15160. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15161. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15162. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15163. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15164. }
  15165. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15166. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15167. textures.push(texture);
  15168. attachments.push(attachment);
  15169. gl.activeTexture(gl["TEXTURE" + i]);
  15170. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15171. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15172. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15175. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15176. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15177. if (generateMipMaps) {
  15178. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15179. }
  15180. // Unbind
  15181. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15182. texture._framebuffer = framebuffer;
  15183. texture._depthStencilBuffer = depthStencilBuffer;
  15184. texture.baseWidth = width;
  15185. texture.baseHeight = height;
  15186. texture.width = width;
  15187. texture.height = height;
  15188. texture.isReady = true;
  15189. texture.samples = 1;
  15190. texture.generateMipMaps = generateMipMaps;
  15191. texture.samplingMode = samplingMode;
  15192. texture.type = type;
  15193. texture._generateDepthBuffer = generateDepthBuffer;
  15194. texture._generateStencilBuffer = generateStencilBuffer;
  15195. texture._attachments = attachments;
  15196. this._internalTexturesCache.push(texture);
  15197. }
  15198. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15199. // Depth texture
  15200. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15201. gl.activeTexture(gl.TEXTURE0);
  15202. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15203. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15204. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15205. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15206. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15207. 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);
  15208. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15209. depthTexture._framebuffer = framebuffer;
  15210. depthTexture.baseWidth = width;
  15211. depthTexture.baseHeight = height;
  15212. depthTexture.width = width;
  15213. depthTexture.height = height;
  15214. depthTexture.isReady = true;
  15215. depthTexture.samples = 1;
  15216. depthTexture.generateMipMaps = generateMipMaps;
  15217. depthTexture.samplingMode = gl.NEAREST;
  15218. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15219. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15220. textures.push(depthTexture);
  15221. this._internalTexturesCache.push(depthTexture);
  15222. }
  15223. gl.drawBuffers(attachments);
  15224. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15225. this.bindUnboundFramebuffer(null);
  15226. this.resetTextureCache();
  15227. return textures;
  15228. };
  15229. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15230. if (samples === void 0) { samples = 1; }
  15231. var depthStencilBuffer = null;
  15232. var gl = this._gl;
  15233. // Create the depth/stencil buffer
  15234. if (generateStencilBuffer) {
  15235. depthStencilBuffer = gl.createRenderbuffer();
  15236. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15237. if (samples > 1) {
  15238. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15239. }
  15240. else {
  15241. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15242. }
  15243. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15244. }
  15245. else if (generateDepthBuffer) {
  15246. depthStencilBuffer = gl.createRenderbuffer();
  15247. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15248. if (samples > 1) {
  15249. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15250. }
  15251. else {
  15252. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15253. }
  15254. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15255. }
  15256. return depthStencilBuffer;
  15257. };
  15258. /**
  15259. * Updates the sample count of a render target texture
  15260. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15261. * @param texture defines the texture to update
  15262. * @param samples defines the sample count to set
  15263. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15264. */
  15265. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15266. if (this.webGLVersion < 2 || !texture) {
  15267. return 1;
  15268. }
  15269. if (texture.samples === samples) {
  15270. return samples;
  15271. }
  15272. var gl = this._gl;
  15273. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15274. // Dispose previous render buffers
  15275. if (texture._depthStencilBuffer) {
  15276. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15277. texture._depthStencilBuffer = null;
  15278. }
  15279. if (texture._MSAAFramebuffer) {
  15280. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15281. texture._MSAAFramebuffer = null;
  15282. }
  15283. if (texture._MSAARenderBuffer) {
  15284. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15285. texture._MSAARenderBuffer = null;
  15286. }
  15287. if (samples > 1) {
  15288. var framebuffer = gl.createFramebuffer();
  15289. if (!framebuffer) {
  15290. throw new Error("Unable to create multi sampled framebuffer");
  15291. }
  15292. texture._MSAAFramebuffer = framebuffer;
  15293. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15294. var colorRenderbuffer = gl.createRenderbuffer();
  15295. if (!colorRenderbuffer) {
  15296. throw new Error("Unable to create multi sampled framebuffer");
  15297. }
  15298. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15299. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15300. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15301. texture._MSAARenderBuffer = colorRenderbuffer;
  15302. }
  15303. else {
  15304. this.bindUnboundFramebuffer(texture._framebuffer);
  15305. }
  15306. texture.samples = samples;
  15307. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15308. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15309. this.bindUnboundFramebuffer(null);
  15310. return samples;
  15311. };
  15312. /**
  15313. * Update the sample count for a given multiple render target texture
  15314. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15315. * @param textures defines the textures to update
  15316. * @param samples defines the sample count to set
  15317. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15318. */
  15319. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15320. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15321. return 1;
  15322. }
  15323. if (textures[0].samples === samples) {
  15324. return samples;
  15325. }
  15326. var gl = this._gl;
  15327. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15328. // Dispose previous render buffers
  15329. if (textures[0]._depthStencilBuffer) {
  15330. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15331. textures[0]._depthStencilBuffer = null;
  15332. }
  15333. if (textures[0]._MSAAFramebuffer) {
  15334. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15335. textures[0]._MSAAFramebuffer = null;
  15336. }
  15337. for (var i = 0; i < textures.length; i++) {
  15338. if (textures[i]._MSAARenderBuffer) {
  15339. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15340. textures[i]._MSAARenderBuffer = null;
  15341. }
  15342. }
  15343. if (samples > 1) {
  15344. var framebuffer = gl.createFramebuffer();
  15345. if (!framebuffer) {
  15346. throw new Error("Unable to create multi sampled framebuffer");
  15347. }
  15348. this.bindUnboundFramebuffer(framebuffer);
  15349. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15350. var attachments = [];
  15351. for (var i = 0; i < textures.length; i++) {
  15352. var texture = textures[i];
  15353. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15354. var colorRenderbuffer = gl.createRenderbuffer();
  15355. if (!colorRenderbuffer) {
  15356. throw new Error("Unable to create multi sampled framebuffer");
  15357. }
  15358. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15359. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15360. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15361. texture._MSAAFramebuffer = framebuffer;
  15362. texture._MSAARenderBuffer = colorRenderbuffer;
  15363. texture.samples = samples;
  15364. texture._depthStencilBuffer = depthStencilBuffer;
  15365. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15366. attachments.push(attachment);
  15367. }
  15368. gl.drawBuffers(attachments);
  15369. }
  15370. else {
  15371. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15372. }
  15373. this.bindUnboundFramebuffer(null);
  15374. return samples;
  15375. };
  15376. /** @hidden */
  15377. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15378. if (faceIndex === void 0) { faceIndex = 0; }
  15379. if (lod === void 0) { lod = 0; }
  15380. var gl = this._gl;
  15381. var target = gl.TEXTURE_2D;
  15382. if (texture.isCube) {
  15383. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15384. }
  15385. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15386. };
  15387. /** @hidden */
  15388. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15389. if (faceIndex === void 0) { faceIndex = 0; }
  15390. if (lod === void 0) { lod = 0; }
  15391. var gl = this._gl;
  15392. var textureType = this._getWebGLTextureType(texture.type);
  15393. var format = this._getInternalFormat(texture.format);
  15394. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15395. this._unpackFlipY(texture.invertY);
  15396. var target = gl.TEXTURE_2D;
  15397. if (texture.isCube) {
  15398. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15399. }
  15400. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15401. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15402. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15403. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15404. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15405. };
  15406. /** @hidden */
  15407. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15408. if (faceIndex === void 0) { faceIndex = 0; }
  15409. if (lod === void 0) { lod = 0; }
  15410. var gl = this._gl;
  15411. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15412. this._bindTextureDirectly(bindTarget, texture, true);
  15413. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15414. this._bindTextureDirectly(bindTarget, null, true);
  15415. };
  15416. /** @hidden */
  15417. Engine.prototype._uploadImageToTexture = function (texture, image, 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. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15425. this._bindTextureDirectly(bindTarget, texture, true);
  15426. this._unpackFlipY(texture.invertY);
  15427. var target = gl.TEXTURE_2D;
  15428. if (texture.isCube) {
  15429. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15430. }
  15431. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15432. this._bindTextureDirectly(bindTarget, null, true);
  15433. };
  15434. /**
  15435. * Creates a new render target cube texture
  15436. * @param size defines the size of the texture
  15437. * @param options defines the options used to create the texture
  15438. * @returns a new render target cube texture stored in an InternalTexture
  15439. */
  15440. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15441. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15442. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15443. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15444. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15445. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15446. }
  15447. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15448. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15449. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15450. }
  15451. var gl = this._gl;
  15452. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15453. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15454. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15455. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15456. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15457. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15458. }
  15459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15462. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15463. for (var face = 0; face < 6; face++) {
  15464. 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);
  15465. }
  15466. // Create the framebuffer
  15467. var framebuffer = gl.createFramebuffer();
  15468. this.bindUnboundFramebuffer(framebuffer);
  15469. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15470. // MipMaps
  15471. if (fullOptions.generateMipMaps) {
  15472. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15473. }
  15474. // Unbind
  15475. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15476. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15477. this.bindUnboundFramebuffer(null);
  15478. texture._framebuffer = framebuffer;
  15479. texture.width = size;
  15480. texture.height = size;
  15481. texture.isReady = true;
  15482. texture.isCube = true;
  15483. texture.samples = 1;
  15484. texture.generateMipMaps = fullOptions.generateMipMaps;
  15485. texture.samplingMode = fullOptions.samplingMode;
  15486. texture.type = fullOptions.type;
  15487. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15488. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15489. this._internalTexturesCache.push(texture);
  15490. return texture;
  15491. };
  15492. /**
  15493. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15494. * @param rootUrl defines the url where the file to load is located
  15495. * @param scene defines the current scene
  15496. * @param lodScale defines scale to apply to the mip map selection
  15497. * @param lodOffset defines offset to apply to the mip map selection
  15498. * @param onLoad defines an optional callback raised when the texture is loaded
  15499. * @param onError defines an optional callback raised if there is an issue to load the texture
  15500. * @param format defines the format of the data
  15501. * @param forcedExtension defines the extension to use to pick the right loader
  15502. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15503. * @returns the cube texture as an InternalTexture
  15504. */
  15505. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15506. var _this = this;
  15507. if (onLoad === void 0) { onLoad = null; }
  15508. if (onError === void 0) { onError = null; }
  15509. if (forcedExtension === void 0) { forcedExtension = null; }
  15510. if (createPolynomials === void 0) { createPolynomials = true; }
  15511. var callback = function (loadData) {
  15512. if (!loadData) {
  15513. if (onLoad) {
  15514. onLoad(null);
  15515. }
  15516. return;
  15517. }
  15518. var texture = loadData.texture;
  15519. if (!createPolynomials) {
  15520. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15521. }
  15522. else if (loadData.info.sphericalPolynomial) {
  15523. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15524. }
  15525. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15526. if (_this._caps.textureLOD) {
  15527. // Do not add extra process if texture lod is supported.
  15528. if (onLoad) {
  15529. onLoad(texture);
  15530. }
  15531. return;
  15532. }
  15533. var mipSlices = 3;
  15534. var gl = _this._gl;
  15535. var width = loadData.width;
  15536. if (!width) {
  15537. return;
  15538. }
  15539. var textures = [];
  15540. for (var i = 0; i < mipSlices; i++) {
  15541. //compute LOD from even spacing in smoothness (matching shader calculation)
  15542. var smoothness = i / (mipSlices - 1);
  15543. var roughness = 1 - smoothness;
  15544. var minLODIndex = lodOffset; // roughness = 0
  15545. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15546. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15547. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15548. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15549. glTextureFromLod.type = texture.type;
  15550. glTextureFromLod.format = texture.format;
  15551. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15552. glTextureFromLod.height = glTextureFromLod.width;
  15553. glTextureFromLod.isCube = true;
  15554. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15555. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15559. if (loadData.isDDS) {
  15560. var info = loadData.info;
  15561. var data = loadData.data;
  15562. _this._unpackFlipY(info.isCompressed);
  15563. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15564. }
  15565. else {
  15566. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15567. }
  15568. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15569. // Wrap in a base texture for easy binding.
  15570. var lodTexture = new BABYLON.BaseTexture(scene);
  15571. lodTexture.isCube = true;
  15572. lodTexture._texture = glTextureFromLod;
  15573. glTextureFromLod.isReady = true;
  15574. textures.push(lodTexture);
  15575. }
  15576. texture._lodTextureHigh = textures[2];
  15577. texture._lodTextureMid = textures[1];
  15578. texture._lodTextureLow = textures[0];
  15579. if (onLoad) {
  15580. onLoad(texture);
  15581. }
  15582. };
  15583. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15584. };
  15585. /**
  15586. * Creates a cube texture
  15587. * @param rootUrl defines the url where the files to load is located
  15588. * @param scene defines the current scene
  15589. * @param files defines the list of files to load (1 per face)
  15590. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15591. * @param onLoad defines an optional callback raised when the texture is loaded
  15592. * @param onError defines an optional callback raised if there is an issue to load the texture
  15593. * @param format defines the format of the data
  15594. * @param forcedExtension defines the extension to use to pick the right loader
  15595. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15596. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15597. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15598. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15599. * @returns the cube texture as an InternalTexture
  15600. */
  15601. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15602. var _this = this;
  15603. if (onLoad === void 0) { onLoad = null; }
  15604. if (onError === void 0) { onError = null; }
  15605. if (forcedExtension === void 0) { forcedExtension = null; }
  15606. if (createPolynomials === void 0) { createPolynomials = false; }
  15607. if (lodScale === void 0) { lodScale = 0; }
  15608. if (lodOffset === void 0) { lodOffset = 0; }
  15609. if (fallback === void 0) { fallback = null; }
  15610. var gl = this._gl;
  15611. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15612. texture.isCube = true;
  15613. texture.url = rootUrl;
  15614. texture.generateMipMaps = !noMipmap;
  15615. texture._lodGenerationScale = lodScale;
  15616. texture._lodGenerationOffset = lodOffset;
  15617. if (!this._doNotHandleContextLost) {
  15618. texture._extension = forcedExtension;
  15619. texture._files = files;
  15620. }
  15621. var lastDot = rootUrl.lastIndexOf('.');
  15622. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15623. var loader = null;
  15624. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15625. var availableLoader = _a[_i];
  15626. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15627. loader = availableLoader;
  15628. break;
  15629. }
  15630. }
  15631. var onInternalError = function (request, exception) {
  15632. if (loader) {
  15633. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15634. if (fallbackUrl) {
  15635. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15636. }
  15637. }
  15638. if (onError && request) {
  15639. onError(request.status + " " + request.statusText, exception);
  15640. }
  15641. };
  15642. if (loader) {
  15643. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15644. var onloaddata = function (data) {
  15645. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15646. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15647. };
  15648. if (files && files.length === 6) {
  15649. if (loader.supportCascades) {
  15650. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15651. }
  15652. else if (onError) {
  15653. onError("Textures type does not support cascades.");
  15654. }
  15655. }
  15656. else {
  15657. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15658. }
  15659. }
  15660. else {
  15661. if (!files) {
  15662. throw new Error("Cannot load cubemap because files were not defined");
  15663. }
  15664. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15665. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15666. var height = width;
  15667. _this._prepareWorkingCanvas();
  15668. if (!_this._workingCanvas || !_this._workingContext) {
  15669. return;
  15670. }
  15671. _this._workingCanvas.width = width;
  15672. _this._workingCanvas.height = height;
  15673. var faces = [
  15674. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15675. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15676. ];
  15677. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15678. _this._unpackFlipY(false);
  15679. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15680. for (var index = 0; index < faces.length; index++) {
  15681. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15682. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15683. }
  15684. if (!noMipmap) {
  15685. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15686. }
  15687. _this._setCubeMapTextureParams(!noMipmap);
  15688. texture.width = width;
  15689. texture.height = height;
  15690. texture.isReady = true;
  15691. if (format) {
  15692. texture.format = format;
  15693. }
  15694. texture.onLoadedObservable.notifyObservers(texture);
  15695. texture.onLoadedObservable.clear();
  15696. if (onLoad) {
  15697. onLoad();
  15698. }
  15699. }, files, onError);
  15700. }
  15701. this._internalTexturesCache.push(texture);
  15702. return texture;
  15703. };
  15704. /**
  15705. * @hidden
  15706. */
  15707. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15708. var gl = this._gl;
  15709. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15710. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15711. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15712. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15713. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15714. // this.resetTextureCache();
  15715. };
  15716. /**
  15717. * Update a raw cube texture
  15718. * @param texture defines the texture to udpdate
  15719. * @param data defines the data to store
  15720. * @param format defines the data format
  15721. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15722. * @param invertY defines if data must be stored with Y axis inverted
  15723. * @param compression defines the compression used (null by default)
  15724. * @param level defines which level of the texture to update
  15725. */
  15726. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15727. if (compression === void 0) { compression = null; }
  15728. if (level === void 0) { level = 0; }
  15729. texture._bufferViewArray = data;
  15730. texture.format = format;
  15731. texture.type = type;
  15732. texture.invertY = invertY;
  15733. texture._compression = compression;
  15734. var gl = this._gl;
  15735. var textureType = this._getWebGLTextureType(type);
  15736. var internalFormat = this._getInternalFormat(format);
  15737. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15738. var needConversion = false;
  15739. if (internalFormat === gl.RGB) {
  15740. internalFormat = gl.RGBA;
  15741. needConversion = true;
  15742. }
  15743. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15744. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15745. if (texture.width % 4 !== 0) {
  15746. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15747. }
  15748. // Data are known to be in +X +Y +Z -X -Y -Z
  15749. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15750. var faceData = data[faceIndex];
  15751. if (compression) {
  15752. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15753. }
  15754. else {
  15755. if (needConversion) {
  15756. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15757. }
  15758. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15759. }
  15760. }
  15761. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15762. if (isPot && texture.generateMipMaps && level === 0) {
  15763. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15764. }
  15765. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15766. // this.resetTextureCache();
  15767. texture.isReady = true;
  15768. };
  15769. /**
  15770. * Creates a new raw cube texture
  15771. * @param data defines the array of data to use to create each face
  15772. * @param size defines the size of the textures
  15773. * @param format defines the format of the data
  15774. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15775. * @param generateMipMaps defines if the engine should generate the mip levels
  15776. * @param invertY defines if data must be stored with Y axis inverted
  15777. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15778. * @param compression defines the compression used (null by default)
  15779. * @returns the cube texture as an InternalTexture
  15780. */
  15781. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15782. if (compression === void 0) { compression = null; }
  15783. var gl = this._gl;
  15784. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15785. texture.isCube = true;
  15786. texture.format = format;
  15787. texture.type = type;
  15788. if (!this._doNotHandleContextLost) {
  15789. texture._bufferViewArray = data;
  15790. }
  15791. var textureType = this._getWebGLTextureType(type);
  15792. var internalFormat = this._getInternalFormat(format);
  15793. if (internalFormat === gl.RGB) {
  15794. internalFormat = gl.RGBA;
  15795. }
  15796. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15797. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15798. generateMipMaps = false;
  15799. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15800. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15801. }
  15802. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15803. generateMipMaps = false;
  15804. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15805. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15806. }
  15807. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15808. generateMipMaps = false;
  15809. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15810. }
  15811. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15812. generateMipMaps = false;
  15813. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15814. }
  15815. var width = size;
  15816. var height = width;
  15817. texture.width = width;
  15818. texture.height = height;
  15819. // Double check on POT to generate Mips.
  15820. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15821. if (!isPot) {
  15822. generateMipMaps = false;
  15823. }
  15824. // Upload data if needed. The texture won't be ready until then.
  15825. if (data) {
  15826. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15827. }
  15828. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15829. // Filters
  15830. if (data && generateMipMaps) {
  15831. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15832. }
  15833. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15837. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15838. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15839. texture.generateMipMaps = generateMipMaps;
  15840. return texture;
  15841. };
  15842. /**
  15843. * Creates a new raw cube texture from a specified url
  15844. * @param url defines the url where the data is located
  15845. * @param scene defines the current scene
  15846. * @param size defines the size of the textures
  15847. * @param format defines the format of the data
  15848. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15849. * @param noMipmap defines if the engine should avoid generating the mip levels
  15850. * @param callback defines a callback used to extract texture data from loaded data
  15851. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15852. * @param onLoad defines a callback called when texture is loaded
  15853. * @param onError defines a callback called if there is an error
  15854. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15855. * @param invertY defines if data must be stored with Y axis inverted
  15856. * @returns the cube texture as an InternalTexture
  15857. */
  15858. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15859. var _this = this;
  15860. if (onLoad === void 0) { onLoad = null; }
  15861. if (onError === void 0) { onError = null; }
  15862. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15863. if (invertY === void 0) { invertY = false; }
  15864. var gl = this._gl;
  15865. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15866. scene._addPendingData(texture);
  15867. texture.url = url;
  15868. this._internalTexturesCache.push(texture);
  15869. var onerror = function (request, exception) {
  15870. scene._removePendingData(texture);
  15871. if (onError && request) {
  15872. onError(request.status + " " + request.statusText, exception);
  15873. }
  15874. };
  15875. var internalCallback = function (data) {
  15876. var width = texture.width;
  15877. var faceDataArrays = callback(data);
  15878. if (!faceDataArrays) {
  15879. return;
  15880. }
  15881. if (mipmapGenerator) {
  15882. var textureType = _this._getWebGLTextureType(type);
  15883. var internalFormat = _this._getInternalFormat(format);
  15884. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15885. var needConversion = false;
  15886. if (internalFormat === gl.RGB) {
  15887. internalFormat = gl.RGBA;
  15888. needConversion = true;
  15889. }
  15890. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15891. _this._unpackFlipY(false);
  15892. var mipData = mipmapGenerator(faceDataArrays);
  15893. for (var level = 0; level < mipData.length; level++) {
  15894. var mipSize = width >> level;
  15895. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15896. var mipFaceData = mipData[level][faceIndex];
  15897. if (needConversion) {
  15898. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15899. }
  15900. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15901. }
  15902. }
  15903. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15904. }
  15905. else {
  15906. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15907. }
  15908. texture.isReady = true;
  15909. // this.resetTextureCache();
  15910. scene._removePendingData(texture);
  15911. if (onLoad) {
  15912. onLoad();
  15913. }
  15914. };
  15915. this._loadFile(url, function (data) {
  15916. internalCallback(data);
  15917. }, undefined, scene.database, true, onerror);
  15918. return texture;
  15919. };
  15920. ;
  15921. /**
  15922. * Update a raw 3D texture
  15923. * @param texture defines the texture to update
  15924. * @param data defines the data to store
  15925. * @param format defines the data format
  15926. * @param invertY defines if data must be stored with Y axis inverted
  15927. * @param compression defines the used compression (can be null)
  15928. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15929. */
  15930. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15931. if (compression === void 0) { compression = null; }
  15932. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15933. var internalType = this._getWebGLTextureType(textureType);
  15934. var internalFormat = this._getInternalFormat(format);
  15935. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15936. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15937. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15938. if (!this._doNotHandleContextLost) {
  15939. texture._bufferView = data;
  15940. texture.format = format;
  15941. texture.invertY = invertY;
  15942. texture._compression = compression;
  15943. }
  15944. if (texture.width % 4 !== 0) {
  15945. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15946. }
  15947. if (compression && data) {
  15948. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15949. }
  15950. else {
  15951. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15952. }
  15953. if (texture.generateMipMaps) {
  15954. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15955. }
  15956. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15957. // this.resetTextureCache();
  15958. texture.isReady = true;
  15959. };
  15960. /**
  15961. * Creates a new raw 3D texture
  15962. * @param data defines the data used to create the texture
  15963. * @param width defines the width of the texture
  15964. * @param height defines the height of the texture
  15965. * @param depth defines the depth of the texture
  15966. * @param format defines the format of the texture
  15967. * @param generateMipMaps defines if the engine must generate mip levels
  15968. * @param invertY defines if data must be stored with Y axis inverted
  15969. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15970. * @param compression defines the compressed used (can be null)
  15971. * @param textureType defines the compressed used (can be null)
  15972. * @returns a new raw 3D texture (stored in an InternalTexture)
  15973. */
  15974. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15975. if (compression === void 0) { compression = null; }
  15976. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15977. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15978. texture.baseWidth = width;
  15979. texture.baseHeight = height;
  15980. texture.baseDepth = depth;
  15981. texture.width = width;
  15982. texture.height = height;
  15983. texture.depth = depth;
  15984. texture.format = format;
  15985. texture.type = textureType;
  15986. texture.generateMipMaps = generateMipMaps;
  15987. texture.samplingMode = samplingMode;
  15988. texture.is3D = true;
  15989. if (!this._doNotHandleContextLost) {
  15990. texture._bufferView = data;
  15991. }
  15992. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15993. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15994. // Filters
  15995. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15996. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15997. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15998. if (generateMipMaps) {
  15999. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16000. }
  16001. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16002. this._internalTexturesCache.push(texture);
  16003. return texture;
  16004. };
  16005. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16006. var gl = this._gl;
  16007. if (!gl) {
  16008. return;
  16009. }
  16010. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16012. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16013. if (!noMipmap && !isCompressed) {
  16014. gl.generateMipmap(gl.TEXTURE_2D);
  16015. }
  16016. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16017. // this.resetTextureCache();
  16018. if (scene) {
  16019. scene._removePendingData(texture);
  16020. }
  16021. texture.onLoadedObservable.notifyObservers(texture);
  16022. texture.onLoadedObservable.clear();
  16023. };
  16024. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16025. var _this = this;
  16026. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16027. var maxTextureSize = this.getCaps().maxTextureSize;
  16028. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16029. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16030. var gl = this._gl;
  16031. if (!gl) {
  16032. return;
  16033. }
  16034. if (!texture._webGLTexture) {
  16035. // this.resetTextureCache();
  16036. if (scene) {
  16037. scene._removePendingData(texture);
  16038. }
  16039. return;
  16040. }
  16041. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16042. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16043. texture.baseWidth = width;
  16044. texture.baseHeight = height;
  16045. texture.width = potWidth;
  16046. texture.height = potHeight;
  16047. texture.isReady = true;
  16048. if (processFunction(potWidth, potHeight, function () {
  16049. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16050. })) {
  16051. // Returning as texture needs extra async steps
  16052. return;
  16053. }
  16054. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16055. };
  16056. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16057. // Create new RGBA data container.
  16058. var rgbaData;
  16059. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16060. rgbaData = new Float32Array(width * height * 4);
  16061. }
  16062. else {
  16063. rgbaData = new Uint32Array(width * height * 4);
  16064. }
  16065. // Convert each pixel.
  16066. for (var x = 0; x < width; x++) {
  16067. for (var y = 0; y < height; y++) {
  16068. var index = (y * width + x) * 3;
  16069. var newIndex = (y * width + x) * 4;
  16070. // Map Old Value to new value.
  16071. rgbaData[newIndex + 0] = rgbData[index + 0];
  16072. rgbaData[newIndex + 1] = rgbData[index + 1];
  16073. rgbaData[newIndex + 2] = rgbData[index + 2];
  16074. // Add fully opaque alpha channel.
  16075. rgbaData[newIndex + 3] = 1;
  16076. }
  16077. }
  16078. return rgbaData;
  16079. };
  16080. /** @hidden */
  16081. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16082. var gl = this._gl;
  16083. if (texture._framebuffer) {
  16084. gl.deleteFramebuffer(texture._framebuffer);
  16085. texture._framebuffer = null;
  16086. }
  16087. if (texture._depthStencilBuffer) {
  16088. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16089. texture._depthStencilBuffer = null;
  16090. }
  16091. if (texture._MSAAFramebuffer) {
  16092. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16093. texture._MSAAFramebuffer = null;
  16094. }
  16095. if (texture._MSAARenderBuffer) {
  16096. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16097. texture._MSAARenderBuffer = null;
  16098. }
  16099. };
  16100. /** @hidden */
  16101. Engine.prototype._releaseTexture = function (texture) {
  16102. var gl = this._gl;
  16103. this._releaseFramebufferObjects(texture);
  16104. gl.deleteTexture(texture._webGLTexture);
  16105. // Unbind channels
  16106. this.unbindAllTextures();
  16107. var index = this._internalTexturesCache.indexOf(texture);
  16108. if (index !== -1) {
  16109. this._internalTexturesCache.splice(index, 1);
  16110. }
  16111. // Integrated fixed lod samplers.
  16112. if (texture._lodTextureHigh) {
  16113. texture._lodTextureHigh.dispose();
  16114. }
  16115. if (texture._lodTextureMid) {
  16116. texture._lodTextureMid.dispose();
  16117. }
  16118. if (texture._lodTextureLow) {
  16119. texture._lodTextureLow.dispose();
  16120. }
  16121. // Set output texture of post process to null if the texture has been released/disposed
  16122. this.scenes.forEach(function (scene) {
  16123. scene.postProcesses.forEach(function (postProcess) {
  16124. if (postProcess._outputTexture == texture) {
  16125. postProcess._outputTexture = null;
  16126. }
  16127. });
  16128. scene.cameras.forEach(function (camera) {
  16129. camera._postProcesses.forEach(function (postProcess) {
  16130. if (postProcess) {
  16131. if (postProcess._outputTexture == texture) {
  16132. postProcess._outputTexture = null;
  16133. }
  16134. }
  16135. });
  16136. });
  16137. });
  16138. };
  16139. Engine.prototype.setProgram = function (program) {
  16140. if (this._currentProgram !== program) {
  16141. this._gl.useProgram(program);
  16142. this._currentProgram = program;
  16143. }
  16144. };
  16145. /**
  16146. * Binds an effect to the webGL context
  16147. * @param effect defines the effect to bind
  16148. */
  16149. Engine.prototype.bindSamplers = function (effect) {
  16150. this.setProgram(effect.getProgram());
  16151. var samplers = effect.getSamplers();
  16152. for (var index = 0; index < samplers.length; index++) {
  16153. var uniform = effect.getUniform(samplers[index]);
  16154. if (uniform) {
  16155. this._boundUniforms[index] = uniform;
  16156. }
  16157. }
  16158. this._currentEffect = null;
  16159. };
  16160. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16161. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16162. return;
  16163. }
  16164. // Remove
  16165. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16166. // Bind last to it
  16167. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16168. // Bind to dummy
  16169. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16170. };
  16171. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16172. if (!internalTexture) {
  16173. return -1;
  16174. }
  16175. internalTexture._initialSlot = channel;
  16176. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16177. if (channel !== internalTexture._designatedSlot) {
  16178. this._textureCollisions.addCount(1, false);
  16179. }
  16180. }
  16181. else {
  16182. if (channel !== internalTexture._designatedSlot) {
  16183. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16184. return internalTexture._designatedSlot;
  16185. }
  16186. else {
  16187. // No slot for this texture, let's pick a new one (if we find a free slot)
  16188. if (this._nextFreeTextureSlots.length) {
  16189. return this._nextFreeTextureSlots[0];
  16190. }
  16191. // We need to recycle the oldest bound texture, sorry.
  16192. this._textureCollisions.addCount(1, false);
  16193. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16194. }
  16195. }
  16196. }
  16197. return channel;
  16198. };
  16199. Engine.prototype._linkTrackers = function (previous, next) {
  16200. previous.next = next;
  16201. next.previous = previous;
  16202. };
  16203. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16204. var currentSlot = internalTexture._designatedSlot;
  16205. if (currentSlot === -1) {
  16206. return -1;
  16207. }
  16208. internalTexture._designatedSlot = -1;
  16209. if (this.disableTextureBindingOptimization) {
  16210. return -1;
  16211. }
  16212. // Remove from bound list
  16213. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16214. // Free the slot
  16215. this._boundTexturesCache[currentSlot] = null;
  16216. this._nextFreeTextureSlots.push(currentSlot);
  16217. return currentSlot;
  16218. };
  16219. Engine.prototype._activateCurrentTexture = function () {
  16220. if (this._currentTextureChannel !== this._activeChannel) {
  16221. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16222. this._currentTextureChannel = this._activeChannel;
  16223. }
  16224. };
  16225. /** @hidden */
  16226. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16227. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16228. if (force === void 0) { force = false; }
  16229. var wasPreviouslyBound = false;
  16230. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16231. this._activeChannel = texture._designatedSlot;
  16232. }
  16233. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16234. var isTextureForRendering = texture && texture._initialSlot > -1;
  16235. if (currentTextureBound !== texture || force) {
  16236. if (currentTextureBound) {
  16237. this._removeDesignatedSlot(currentTextureBound);
  16238. }
  16239. this._activateCurrentTexture();
  16240. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16241. this._boundTexturesCache[this._activeChannel] = texture;
  16242. if (texture) {
  16243. if (!this.disableTextureBindingOptimization) {
  16244. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16245. if (slotIndex > -1) {
  16246. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16247. }
  16248. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16249. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16250. }
  16251. texture._designatedSlot = this._activeChannel;
  16252. }
  16253. }
  16254. else if (forTextureDataUpdate) {
  16255. wasPreviouslyBound = true;
  16256. this._activateCurrentTexture();
  16257. }
  16258. if (isTextureForRendering && !forTextureDataUpdate) {
  16259. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16260. }
  16261. return wasPreviouslyBound;
  16262. };
  16263. /** @hidden */
  16264. Engine.prototype._bindTexture = function (channel, texture) {
  16265. if (channel < 0) {
  16266. return;
  16267. }
  16268. if (texture) {
  16269. channel = this._getCorrectTextureChannel(channel, texture);
  16270. }
  16271. this._activeChannel = channel;
  16272. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16273. };
  16274. /**
  16275. * Sets a texture to the webGL context from a postprocess
  16276. * @param channel defines the channel to use
  16277. * @param postProcess defines the source postprocess
  16278. */
  16279. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16280. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16281. };
  16282. /**
  16283. * Binds the output of the passed in post process to the texture channel specified
  16284. * @param channel The channel the texture should be bound to
  16285. * @param postProcess The post process which's output should be bound
  16286. */
  16287. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16288. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16289. };
  16290. /**
  16291. * Unbind all textures from the webGL context
  16292. */
  16293. Engine.prototype.unbindAllTextures = function () {
  16294. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16295. this._activeChannel = channel;
  16296. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16297. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16298. if (this.webGLVersion > 1) {
  16299. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16300. }
  16301. }
  16302. };
  16303. /**
  16304. * Sets a texture to the according uniform.
  16305. * @param channel The texture channel
  16306. * @param uniform The uniform to set
  16307. * @param texture The texture to apply
  16308. */
  16309. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16310. if (channel < 0) {
  16311. return;
  16312. }
  16313. if (uniform) {
  16314. this._boundUniforms[channel] = uniform;
  16315. }
  16316. this._setTexture(channel, texture);
  16317. };
  16318. /**
  16319. * Sets a depth stencil texture from a render target to the according uniform.
  16320. * @param channel The texture channel
  16321. * @param uniform The uniform to set
  16322. * @param texture The render target texture containing the depth stencil texture to apply
  16323. */
  16324. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16325. if (channel < 0) {
  16326. return;
  16327. }
  16328. if (uniform) {
  16329. this._boundUniforms[channel] = uniform;
  16330. }
  16331. if (!texture || !texture.depthStencilTexture) {
  16332. this._setTexture(channel, null);
  16333. }
  16334. else {
  16335. this._setTexture(channel, texture, false, true);
  16336. }
  16337. };
  16338. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16339. var uniform = this._boundUniforms[sourceSlot];
  16340. if (uniform._currentState === destination) {
  16341. return;
  16342. }
  16343. this._gl.uniform1i(uniform, destination);
  16344. uniform._currentState = destination;
  16345. };
  16346. Engine.prototype._getTextureWrapMode = function (mode) {
  16347. switch (mode) {
  16348. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16349. return this._gl.REPEAT;
  16350. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16351. return this._gl.CLAMP_TO_EDGE;
  16352. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16353. return this._gl.MIRRORED_REPEAT;
  16354. }
  16355. return this._gl.REPEAT;
  16356. };
  16357. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16358. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16359. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16360. // Not ready?
  16361. if (!texture) {
  16362. if (this._boundTexturesCache[channel] != null) {
  16363. this._activeChannel = channel;
  16364. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16365. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16366. if (this.webGLVersion > 1) {
  16367. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16368. }
  16369. }
  16370. return false;
  16371. }
  16372. // Video
  16373. if (texture.video) {
  16374. this._activeChannel = channel;
  16375. texture.update();
  16376. }
  16377. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16378. texture.delayLoad();
  16379. return false;
  16380. }
  16381. var internalTexture;
  16382. if (depthStencilTexture) {
  16383. internalTexture = texture.depthStencilTexture;
  16384. }
  16385. else if (texture.isReady()) {
  16386. internalTexture = texture.getInternalTexture();
  16387. }
  16388. else if (texture.isCube) {
  16389. internalTexture = this.emptyCubeTexture;
  16390. }
  16391. else if (texture.is3D) {
  16392. internalTexture = this.emptyTexture3D;
  16393. }
  16394. else {
  16395. internalTexture = this.emptyTexture;
  16396. }
  16397. if (!isPartOfTextureArray) {
  16398. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16399. }
  16400. var needToBind = true;
  16401. if (this._boundTexturesCache[channel] === internalTexture) {
  16402. this._moveBoundTextureOnTop(internalTexture);
  16403. if (!isPartOfTextureArray) {
  16404. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16405. }
  16406. needToBind = false;
  16407. }
  16408. this._activeChannel = channel;
  16409. if (internalTexture && internalTexture.is3D) {
  16410. if (needToBind) {
  16411. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16412. }
  16413. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16414. internalTexture._cachedWrapU = texture.wrapU;
  16415. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16416. }
  16417. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16418. internalTexture._cachedWrapV = texture.wrapV;
  16419. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16420. }
  16421. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16422. internalTexture._cachedWrapR = texture.wrapR;
  16423. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16424. }
  16425. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16426. }
  16427. else if (internalTexture && internalTexture.isCube) {
  16428. if (needToBind) {
  16429. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16430. }
  16431. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16432. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16433. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16434. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16435. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16436. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16437. }
  16438. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16439. }
  16440. else {
  16441. if (needToBind) {
  16442. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16443. }
  16444. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16445. internalTexture._cachedWrapU = texture.wrapU;
  16446. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16447. }
  16448. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16449. internalTexture._cachedWrapV = texture.wrapV;
  16450. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16451. }
  16452. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16453. }
  16454. return true;
  16455. };
  16456. /**
  16457. * Sets an array of texture to the webGL context
  16458. * @param channel defines the channel where the texture array must be set
  16459. * @param uniform defines the associated uniform location
  16460. * @param textures defines the array of textures to bind
  16461. */
  16462. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16463. if (channel < 0 || !uniform) {
  16464. return;
  16465. }
  16466. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16467. this._textureUnits = new Int32Array(textures.length);
  16468. }
  16469. for (var i = 0; i < textures.length; i++) {
  16470. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16471. }
  16472. this._gl.uniform1iv(uniform, this._textureUnits);
  16473. for (var index = 0; index < textures.length; index++) {
  16474. this._setTexture(this._textureUnits[index], textures[index], true);
  16475. }
  16476. };
  16477. /** @hidden */
  16478. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16479. var internalTexture = texture.getInternalTexture();
  16480. if (!internalTexture) {
  16481. return;
  16482. }
  16483. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16484. var value = texture.anisotropicFilteringLevel;
  16485. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16486. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16487. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16488. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16489. }
  16490. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16491. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16492. internalTexture._cachedAnisotropicFilteringLevel = value;
  16493. }
  16494. };
  16495. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16496. this._bindTextureDirectly(target, texture, true, true);
  16497. this._gl.texParameterf(target, parameter, value);
  16498. };
  16499. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16500. if (texture) {
  16501. this._bindTextureDirectly(target, texture, true, true);
  16502. }
  16503. this._gl.texParameteri(target, parameter, value);
  16504. };
  16505. /**
  16506. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16507. * @param x defines the x coordinate of the rectangle where pixels must be read
  16508. * @param y defines the y coordinate of the rectangle where pixels must be read
  16509. * @param width defines the width of the rectangle where pixels must be read
  16510. * @param height defines the height of the rectangle where pixels must be read
  16511. * @returns a Uint8Array containing RGBA colors
  16512. */
  16513. Engine.prototype.readPixels = function (x, y, width, height) {
  16514. var data = new Uint8Array(height * width * 4);
  16515. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16516. return data;
  16517. };
  16518. /**
  16519. * Add an externaly attached data from its key.
  16520. * This method call will fail and return false, if such key already exists.
  16521. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16522. * @param key the unique key that identifies the data
  16523. * @param data the data object to associate to the key for this Engine instance
  16524. * @return true if no such key were already present and the data was added successfully, false otherwise
  16525. */
  16526. Engine.prototype.addExternalData = function (key, data) {
  16527. if (!this._externalData) {
  16528. this._externalData = new BABYLON.StringDictionary();
  16529. }
  16530. return this._externalData.add(key, data);
  16531. };
  16532. /**
  16533. * Get an externaly attached data from its key
  16534. * @param key the unique key that identifies the data
  16535. * @return the associated data, if present (can be null), or undefined if not present
  16536. */
  16537. Engine.prototype.getExternalData = function (key) {
  16538. if (!this._externalData) {
  16539. this._externalData = new BABYLON.StringDictionary();
  16540. }
  16541. return this._externalData.get(key);
  16542. };
  16543. /**
  16544. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16545. * @param key the unique key that identifies the data
  16546. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16547. * @return the associated data, can be null if the factory returned null.
  16548. */
  16549. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16550. if (!this._externalData) {
  16551. this._externalData = new BABYLON.StringDictionary();
  16552. }
  16553. return this._externalData.getOrAddWithFactory(key, factory);
  16554. };
  16555. /**
  16556. * Remove an externaly attached data from the Engine instance
  16557. * @param key the unique key that identifies the data
  16558. * @return true if the data was successfully removed, false if it doesn't exist
  16559. */
  16560. Engine.prototype.removeExternalData = function (key) {
  16561. if (!this._externalData) {
  16562. this._externalData = new BABYLON.StringDictionary();
  16563. }
  16564. return this._externalData.remove(key);
  16565. };
  16566. /**
  16567. * Unbind all vertex attributes from the webGL context
  16568. */
  16569. Engine.prototype.unbindAllAttributes = function () {
  16570. if (this._mustWipeVertexAttributes) {
  16571. this._mustWipeVertexAttributes = false;
  16572. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16573. this._gl.disableVertexAttribArray(i);
  16574. this._vertexAttribArraysEnabled[i] = false;
  16575. this._currentBufferPointers[i].active = false;
  16576. }
  16577. return;
  16578. }
  16579. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16580. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16581. continue;
  16582. }
  16583. this._gl.disableVertexAttribArray(i);
  16584. this._vertexAttribArraysEnabled[i] = false;
  16585. this._currentBufferPointers[i].active = false;
  16586. }
  16587. };
  16588. /**
  16589. * 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
  16590. */
  16591. Engine.prototype.releaseEffects = function () {
  16592. for (var name in this._compiledEffects) {
  16593. this._deleteProgram(this._compiledEffects[name]._program);
  16594. }
  16595. this._compiledEffects = {};
  16596. };
  16597. /**
  16598. * Dispose and release all associated resources
  16599. */
  16600. Engine.prototype.dispose = function () {
  16601. this.hideLoadingUI();
  16602. this.stopRenderLoop();
  16603. // Release postProcesses
  16604. while (this.postProcesses.length) {
  16605. this.postProcesses[0].dispose();
  16606. }
  16607. // Empty texture
  16608. if (this._emptyTexture) {
  16609. this._releaseTexture(this._emptyTexture);
  16610. this._emptyTexture = null;
  16611. }
  16612. if (this._emptyCubeTexture) {
  16613. this._releaseTexture(this._emptyCubeTexture);
  16614. this._emptyCubeTexture = null;
  16615. }
  16616. // Rescale PP
  16617. if (this._rescalePostProcess) {
  16618. this._rescalePostProcess.dispose();
  16619. }
  16620. // Release scenes
  16621. while (this.scenes.length) {
  16622. this.scenes[0].dispose();
  16623. }
  16624. // Release audio engine
  16625. if (Engine.audioEngine) {
  16626. Engine.audioEngine.dispose();
  16627. }
  16628. // Release effects
  16629. this.releaseEffects();
  16630. // Unbind
  16631. this.unbindAllAttributes();
  16632. this._boundUniforms = [];
  16633. if (this._dummyFramebuffer) {
  16634. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16635. }
  16636. //WebVR
  16637. this.disableVR();
  16638. // Events
  16639. if (BABYLON.Tools.IsWindowObjectExist()) {
  16640. window.removeEventListener("blur", this._onBlur);
  16641. window.removeEventListener("focus", this._onFocus);
  16642. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16643. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16644. if (this._renderingCanvas) {
  16645. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16646. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16647. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16648. if (!this._doNotHandleContextLost) {
  16649. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16650. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16651. }
  16652. }
  16653. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16654. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16655. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16656. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16657. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16658. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16659. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16660. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16661. if (this._onVrDisplayConnect) {
  16662. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16663. if (this._onVrDisplayDisconnect) {
  16664. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16665. }
  16666. if (this._onVrDisplayPresentChange) {
  16667. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16668. }
  16669. this._onVrDisplayConnect = null;
  16670. this._onVrDisplayDisconnect = null;
  16671. }
  16672. }
  16673. // Remove from Instances
  16674. var index = Engine.Instances.indexOf(this);
  16675. if (index >= 0) {
  16676. Engine.Instances.splice(index, 1);
  16677. }
  16678. this._workingCanvas = null;
  16679. this._workingContext = null;
  16680. this._currentBufferPointers = [];
  16681. this._renderingCanvas = null;
  16682. this._currentProgram = null;
  16683. this._bindedRenderFunction = null;
  16684. this.onResizeObservable.clear();
  16685. this.onCanvasBlurObservable.clear();
  16686. this.onCanvasFocusObservable.clear();
  16687. this.onCanvasPointerOutObservable.clear();
  16688. this.onBeginFrameObservable.clear();
  16689. this.onEndFrameObservable.clear();
  16690. BABYLON.Effect.ResetCache();
  16691. // Abort active requests
  16692. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16693. var request = _a[_i];
  16694. request.abort();
  16695. }
  16696. };
  16697. // Loading screen
  16698. /**
  16699. * Display the loading screen
  16700. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16701. */
  16702. Engine.prototype.displayLoadingUI = function () {
  16703. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16704. return;
  16705. }
  16706. var loadingScreen = this.loadingScreen;
  16707. if (loadingScreen) {
  16708. loadingScreen.displayLoadingUI();
  16709. }
  16710. };
  16711. /**
  16712. * Hide the loading screen
  16713. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16714. */
  16715. Engine.prototype.hideLoadingUI = function () {
  16716. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16717. return;
  16718. }
  16719. var loadingScreen = this.loadingScreen;
  16720. if (loadingScreen) {
  16721. loadingScreen.hideLoadingUI();
  16722. }
  16723. };
  16724. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16725. /**
  16726. * Gets the current loading screen object
  16727. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16728. */
  16729. get: function () {
  16730. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16731. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16732. return this._loadingScreen;
  16733. },
  16734. /**
  16735. * Sets the current loading screen object
  16736. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16737. */
  16738. set: function (loadingScreen) {
  16739. this._loadingScreen = loadingScreen;
  16740. },
  16741. enumerable: true,
  16742. configurable: true
  16743. });
  16744. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16745. /**
  16746. * Sets the current loading screen text
  16747. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16748. */
  16749. set: function (text) {
  16750. this.loadingScreen.loadingUIText = text;
  16751. },
  16752. enumerable: true,
  16753. configurable: true
  16754. });
  16755. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16756. /**
  16757. * Sets the current loading screen background color
  16758. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16759. */
  16760. set: function (color) {
  16761. this.loadingScreen.loadingUIBackgroundColor = color;
  16762. },
  16763. enumerable: true,
  16764. configurable: true
  16765. });
  16766. /**
  16767. * Attach a new callback raised when context lost event is fired
  16768. * @param callback defines the callback to call
  16769. */
  16770. Engine.prototype.attachContextLostEvent = function (callback) {
  16771. if (this._renderingCanvas) {
  16772. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16773. }
  16774. };
  16775. /**
  16776. * Attach a new callback raised when context restored event is fired
  16777. * @param callback defines the callback to call
  16778. */
  16779. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16780. if (this._renderingCanvas) {
  16781. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16782. }
  16783. };
  16784. /**
  16785. * Gets the source code of the vertex shader associated with a specific webGL program
  16786. * @param program defines the program to use
  16787. * @returns a string containing the source code of the vertex shader associated with the program
  16788. */
  16789. Engine.prototype.getVertexShaderSource = function (program) {
  16790. var shaders = this._gl.getAttachedShaders(program);
  16791. if (!shaders) {
  16792. return null;
  16793. }
  16794. return this._gl.getShaderSource(shaders[0]);
  16795. };
  16796. /**
  16797. * Gets the source code of the fragment shader associated with a specific webGL program
  16798. * @param program defines the program to use
  16799. * @returns a string containing the source code of the fragment shader associated with the program
  16800. */
  16801. Engine.prototype.getFragmentShaderSource = function (program) {
  16802. var shaders = this._gl.getAttachedShaders(program);
  16803. if (!shaders) {
  16804. return null;
  16805. }
  16806. return this._gl.getShaderSource(shaders[1]);
  16807. };
  16808. /**
  16809. * Get the current error code of the webGL context
  16810. * @returns the error code
  16811. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16812. */
  16813. Engine.prototype.getError = function () {
  16814. return this._gl.getError();
  16815. };
  16816. // FPS
  16817. /**
  16818. * Gets the current framerate
  16819. * @returns a number representing the framerate
  16820. */
  16821. Engine.prototype.getFps = function () {
  16822. return this._fps;
  16823. };
  16824. /**
  16825. * Gets the time spent between current and previous frame
  16826. * @returns a number representing the delta time in ms
  16827. */
  16828. Engine.prototype.getDeltaTime = function () {
  16829. return this._deltaTime;
  16830. };
  16831. Engine.prototype._measureFps = function () {
  16832. this._performanceMonitor.sampleFrame();
  16833. this._fps = this._performanceMonitor.averageFPS;
  16834. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16835. };
  16836. /** @hidden */
  16837. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16838. if (faceIndex === void 0) { faceIndex = -1; }
  16839. if (level === void 0) { level = 0; }
  16840. var gl = this._gl;
  16841. if (!this._dummyFramebuffer) {
  16842. var dummy = gl.createFramebuffer();
  16843. if (!dummy) {
  16844. throw new Error("Unable to create dummy framebuffer");
  16845. }
  16846. this._dummyFramebuffer = dummy;
  16847. }
  16848. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16849. if (faceIndex > -1) {
  16850. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16851. }
  16852. else {
  16853. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16854. }
  16855. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16856. var buffer;
  16857. switch (readType) {
  16858. case gl.UNSIGNED_BYTE:
  16859. buffer = new Uint8Array(4 * width * height);
  16860. readType = gl.UNSIGNED_BYTE;
  16861. break;
  16862. default:
  16863. buffer = new Float32Array(4 * width * height);
  16864. readType = gl.FLOAT;
  16865. break;
  16866. }
  16867. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16868. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16869. return buffer;
  16870. };
  16871. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16872. if (this._webGLVersion > 1) {
  16873. return this._caps.colorBufferFloat;
  16874. }
  16875. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16876. };
  16877. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16878. if (this._webGLVersion > 1) {
  16879. return this._caps.colorBufferFloat;
  16880. }
  16881. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16882. };
  16883. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16884. Engine.prototype._canRenderToFramebuffer = function (type) {
  16885. var gl = this._gl;
  16886. //clear existing errors
  16887. while (gl.getError() !== gl.NO_ERROR) { }
  16888. var successful = true;
  16889. var texture = gl.createTexture();
  16890. gl.bindTexture(gl.TEXTURE_2D, texture);
  16891. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16894. var fb = gl.createFramebuffer();
  16895. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16896. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16897. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16898. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16899. successful = successful && (gl.getError() === gl.NO_ERROR);
  16900. //try render by clearing frame buffer's color buffer
  16901. if (successful) {
  16902. gl.clear(gl.COLOR_BUFFER_BIT);
  16903. successful = successful && (gl.getError() === gl.NO_ERROR);
  16904. }
  16905. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16906. if (successful) {
  16907. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16908. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16909. var readFormat = gl.RGBA;
  16910. var readType = gl.UNSIGNED_BYTE;
  16911. var buffer = new Uint8Array(4);
  16912. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16913. successful = successful && (gl.getError() === gl.NO_ERROR);
  16914. }
  16915. //clean up
  16916. gl.deleteTexture(texture);
  16917. gl.deleteFramebuffer(fb);
  16918. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16919. //clear accumulated errors
  16920. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16921. return successful;
  16922. };
  16923. /** @hidden */
  16924. Engine.prototype._getWebGLTextureType = function (type) {
  16925. if (type === Engine.TEXTURETYPE_FLOAT) {
  16926. return this._gl.FLOAT;
  16927. }
  16928. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16929. // Add Half Float Constant.
  16930. return this._gl.HALF_FLOAT_OES;
  16931. }
  16932. return this._gl.UNSIGNED_BYTE;
  16933. };
  16934. ;
  16935. Engine.prototype._getInternalFormat = function (format) {
  16936. var internalFormat = this._gl.RGBA;
  16937. switch (format) {
  16938. case Engine.TEXTUREFORMAT_ALPHA:
  16939. internalFormat = this._gl.ALPHA;
  16940. break;
  16941. case Engine.TEXTUREFORMAT_LUMINANCE:
  16942. internalFormat = this._gl.LUMINANCE;
  16943. break;
  16944. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16945. internalFormat = this._gl.LUMINANCE_ALPHA;
  16946. break;
  16947. case Engine.TEXTUREFORMAT_RGB:
  16948. internalFormat = this._gl.RGB;
  16949. break;
  16950. case Engine.TEXTUREFORMAT_RGBA:
  16951. internalFormat = this._gl.RGBA;
  16952. break;
  16953. case Engine.TEXTUREFORMAT_R:
  16954. internalFormat = this._gl.RED;
  16955. break;
  16956. case Engine.TEXTUREFORMAT_RG:
  16957. internalFormat = this._gl.RG;
  16958. break;
  16959. }
  16960. return internalFormat;
  16961. };
  16962. /** @hidden */
  16963. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16964. if (this._webGLVersion === 1) {
  16965. if (format !== undefined) {
  16966. switch (format) {
  16967. case Engine.TEXTUREFORMAT_LUMINANCE:
  16968. return this._gl.LUMINANCE;
  16969. case Engine.TEXTUREFORMAT_ALPHA:
  16970. return this._gl.ALPHA;
  16971. }
  16972. }
  16973. return this._gl.RGBA;
  16974. }
  16975. if (type === Engine.TEXTURETYPE_FLOAT) {
  16976. if (format !== undefined) {
  16977. switch (format) {
  16978. case Engine.TEXTUREFORMAT_R:
  16979. return this._gl.R32F;
  16980. case Engine.TEXTUREFORMAT_RG:
  16981. return this._gl.RG32F;
  16982. case Engine.TEXTUREFORMAT_RGB:
  16983. return this._gl.RGB32F;
  16984. }
  16985. }
  16986. return this._gl.RGBA32F;
  16987. }
  16988. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16989. if (format) {
  16990. switch (format) {
  16991. case Engine.TEXTUREFORMAT_R:
  16992. return this._gl.R16F;
  16993. case Engine.TEXTUREFORMAT_RG:
  16994. return this._gl.RG16F;
  16995. case Engine.TEXTUREFORMAT_RGB:
  16996. return this._gl.RGB16F;
  16997. }
  16998. }
  16999. return this._gl.RGBA16F;
  17000. }
  17001. if (format !== undefined) {
  17002. switch (format) {
  17003. case Engine.TEXTUREFORMAT_LUMINANCE:
  17004. return this._gl.LUMINANCE;
  17005. case Engine.TEXTUREFORMAT_RGB:
  17006. return this._gl.RGB;
  17007. case Engine.TEXTUREFORMAT_R:
  17008. return this._gl.R8;
  17009. case Engine.TEXTUREFORMAT_RG:
  17010. return this._gl.RG8;
  17011. case Engine.TEXTUREFORMAT_ALPHA:
  17012. return this._gl.ALPHA;
  17013. }
  17014. }
  17015. return this._gl.RGBA;
  17016. };
  17017. ;
  17018. /** @hidden */
  17019. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17020. if (type === Engine.TEXTURETYPE_FLOAT) {
  17021. return this._gl.RGBA32F;
  17022. }
  17023. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17024. return this._gl.RGBA16F;
  17025. }
  17026. return this._gl.RGBA8;
  17027. };
  17028. ;
  17029. /** @hidden */
  17030. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17031. var _this = this;
  17032. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17033. this._activeRequests.push(request);
  17034. request.onCompleteObservable.add(function (request) {
  17035. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17036. });
  17037. return request;
  17038. };
  17039. /** @hidden */
  17040. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17041. var _this = this;
  17042. return new Promise(function (resolve, reject) {
  17043. _this._loadFile(url, function (data) {
  17044. resolve(data);
  17045. }, undefined, database, useArrayBuffer, function (request, exception) {
  17046. reject(exception);
  17047. });
  17048. });
  17049. };
  17050. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17051. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17052. var onload = function (data) {
  17053. loadedFiles[index] = data;
  17054. loadedFiles._internalCount++;
  17055. if (loadedFiles._internalCount === 6) {
  17056. onfinish(loadedFiles);
  17057. }
  17058. };
  17059. var onerror = function (request, exception) {
  17060. if (onErrorCallBack && request) {
  17061. onErrorCallBack(request.status + " " + request.statusText, exception);
  17062. }
  17063. };
  17064. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17065. };
  17066. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17067. if (onError === void 0) { onError = null; }
  17068. var loadedFiles = [];
  17069. loadedFiles._internalCount = 0;
  17070. for (var index = 0; index < 6; index++) {
  17071. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17072. }
  17073. };
  17074. // Statics
  17075. /**
  17076. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17077. * @returns true if the engine can be created
  17078. * @ignorenaming
  17079. */
  17080. Engine.isSupported = function () {
  17081. try {
  17082. var tempcanvas = document.createElement("canvas");
  17083. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17084. return gl != null && !!window.WebGLRenderingContext;
  17085. }
  17086. catch (e) {
  17087. return false;
  17088. }
  17089. };
  17090. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17091. Engine.ExceptionList = [
  17092. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17093. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17094. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17095. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17096. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17097. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17098. ];
  17099. /** Gets the list of created engines */
  17100. Engine.Instances = new Array();
  17101. /**
  17102. * Hidden
  17103. */
  17104. Engine._TextureLoaders = [];
  17105. // Const statics
  17106. /** Defines that alpha blending is disabled */
  17107. Engine.ALPHA_DISABLE = 0;
  17108. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17109. Engine.ALPHA_ADD = 1;
  17110. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17111. Engine.ALPHA_COMBINE = 2;
  17112. /** Defines that alpha blending to DEST - SRC * DEST */
  17113. Engine.ALPHA_SUBTRACT = 3;
  17114. /** Defines that alpha blending to SRC * DEST */
  17115. Engine.ALPHA_MULTIPLY = 4;
  17116. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17117. Engine.ALPHA_MAXIMIZED = 5;
  17118. /** Defines that alpha blending to SRC + DEST */
  17119. Engine.ALPHA_ONEONE = 6;
  17120. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17121. Engine.ALPHA_PREMULTIPLIED = 7;
  17122. /**
  17123. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17124. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17125. */
  17126. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17127. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17128. Engine.ALPHA_INTERPOLATE = 9;
  17129. /**
  17130. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17131. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17132. */
  17133. Engine.ALPHA_SCREENMODE = 10;
  17134. /** Defines that the ressource is not delayed*/
  17135. Engine.DELAYLOADSTATE_NONE = 0;
  17136. /** Defines that the ressource was successfully delay loaded */
  17137. Engine.DELAYLOADSTATE_LOADED = 1;
  17138. /** Defines that the ressource is currently delay loading */
  17139. Engine.DELAYLOADSTATE_LOADING = 2;
  17140. /** Defines that the ressource is delayed and has not started loading */
  17141. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17142. // Depht or Stencil test Constants.
  17143. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17144. Engine.NEVER = 0x0200;
  17145. /** 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 */
  17146. Engine.ALWAYS = 0x0207;
  17147. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17148. Engine.LESS = 0x0201;
  17149. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17150. Engine.EQUAL = 0x0202;
  17151. /** 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 */
  17152. Engine.LEQUAL = 0x0203;
  17153. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17154. Engine.GREATER = 0x0204;
  17155. /** 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 */
  17156. Engine.GEQUAL = 0x0206;
  17157. /** 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 */
  17158. Engine.NOTEQUAL = 0x0205;
  17159. // Stencil Actions Constants.
  17160. /** Passed to stencilOperation to specify that stencil value must be kept */
  17161. Engine.KEEP = 0x1E00;
  17162. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17163. Engine.REPLACE = 0x1E01;
  17164. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17165. Engine.INCR = 0x1E02;
  17166. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17167. Engine.DECR = 0x1E03;
  17168. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17169. Engine.INVERT = 0x150A;
  17170. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17171. Engine.INCR_WRAP = 0x8507;
  17172. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17173. Engine.DECR_WRAP = 0x8508;
  17174. /** Texture is not repeating outside of 0..1 UVs */
  17175. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17176. /** Texture is repeating outside of 0..1 UVs */
  17177. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17178. /** Texture is repeating and mirrored */
  17179. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17180. /** ALPHA */
  17181. Engine.TEXTUREFORMAT_ALPHA = 0;
  17182. /** LUMINANCE */
  17183. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17184. /** LUMINANCE_ALPHA */
  17185. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17186. /** RGB */
  17187. Engine.TEXTUREFORMAT_RGB = 4;
  17188. /** RGBA */
  17189. Engine.TEXTUREFORMAT_RGBA = 5;
  17190. /** R */
  17191. Engine.TEXTUREFORMAT_R = 6;
  17192. /** RG */
  17193. Engine.TEXTUREFORMAT_RG = 7;
  17194. /** UNSIGNED_INT */
  17195. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17196. /** FLOAT */
  17197. Engine.TEXTURETYPE_FLOAT = 1;
  17198. /** HALF_FLOAT */
  17199. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17200. /** nearest is mag = nearest and min = nearest and mip = linear */
  17201. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17202. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17203. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17204. /** Trilinear is mag = linear and min = linear and mip = linear */
  17205. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17206. /** nearest is mag = nearest and min = nearest and mip = linear */
  17207. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17208. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17209. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17210. /** Trilinear is mag = linear and min = linear and mip = linear */
  17211. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17212. /** mag = nearest and min = nearest and mip = nearest */
  17213. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17214. /** mag = nearest and min = linear and mip = nearest */
  17215. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17216. /** mag = nearest and min = linear and mip = linear */
  17217. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17218. /** mag = nearest and min = linear and mip = none */
  17219. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17220. /** mag = nearest and min = nearest and mip = none */
  17221. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17222. /** mag = linear and min = nearest and mip = nearest */
  17223. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17224. /** mag = linear and min = nearest and mip = linear */
  17225. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17226. /** mag = linear and min = linear and mip = none */
  17227. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17228. /** mag = linear and min = nearest and mip = none */
  17229. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17230. /** Explicit coordinates mode */
  17231. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17232. /** Spherical coordinates mode */
  17233. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17234. /** Planar coordinates mode */
  17235. Engine.TEXTURE_PLANAR_MODE = 2;
  17236. /** Cubic coordinates mode */
  17237. Engine.TEXTURE_CUBIC_MODE = 3;
  17238. /** Projection coordinates mode */
  17239. Engine.TEXTURE_PROJECTION_MODE = 4;
  17240. /** Skybox coordinates mode */
  17241. Engine.TEXTURE_SKYBOX_MODE = 5;
  17242. /** Inverse Cubic coordinates mode */
  17243. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17244. /** Equirectangular coordinates mode */
  17245. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17246. /** Equirectangular Fixed coordinates mode */
  17247. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17248. /** Equirectangular Fixed Mirrored coordinates mode */
  17249. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17250. // Texture rescaling mode
  17251. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17252. Engine.SCALEMODE_FLOOR = 1;
  17253. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17254. Engine.SCALEMODE_NEAREST = 2;
  17255. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17256. Engine.SCALEMODE_CEILING = 3;
  17257. // Updatable statics so stick with vars here
  17258. /**
  17259. * Gets or sets the epsilon value used by collision engine
  17260. */
  17261. Engine.CollisionsEpsilon = 0.001;
  17262. /**
  17263. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17264. */
  17265. Engine.CodeRepository = "src/";
  17266. /**
  17267. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17268. */
  17269. Engine.ShadersRepository = "src/Shaders/";
  17270. return Engine;
  17271. }());
  17272. BABYLON.Engine = Engine;
  17273. })(BABYLON || (BABYLON = {}));
  17274. //# sourceMappingURL=babylon.engine.js.map
  17275. var BABYLON;
  17276. (function (BABYLON) {
  17277. /**
  17278. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17279. */
  17280. var Node = /** @class */ (function () {
  17281. /**
  17282. * Creates a new Node
  17283. * @param {string} name - the name and id to be given to this node
  17284. * @param {BABYLON.Scene} the scene this node will be added to
  17285. */
  17286. function Node(name, scene) {
  17287. if (scene === void 0) { scene = null; }
  17288. /**
  17289. * Gets or sets a string used to store user defined state for the node
  17290. */
  17291. this.state = "";
  17292. /**
  17293. * Gets or sets an object used to store user defined information for the node
  17294. */
  17295. this.metadata = null;
  17296. /**
  17297. * Gets or sets a boolean used to define if the node must be serialized
  17298. */
  17299. this.doNotSerialize = false;
  17300. /** @hidden */
  17301. this._isDisposed = false;
  17302. /**
  17303. * Gets a list of Animations associated with the node
  17304. */
  17305. this.animations = new Array();
  17306. this._ranges = {};
  17307. this._isEnabled = true;
  17308. this._isReady = true;
  17309. /** @hidden */
  17310. this._currentRenderId = -1;
  17311. this._parentRenderId = -1;
  17312. this._childRenderId = -1;
  17313. this._animationPropertiesOverride = null;
  17314. /**
  17315. * An event triggered when the mesh is disposed
  17316. */
  17317. this.onDisposeObservable = new BABYLON.Observable();
  17318. // Behaviors
  17319. this._behaviors = new Array();
  17320. this.name = name;
  17321. this.id = name;
  17322. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17323. this.uniqueId = this._scene.getUniqueId();
  17324. this._initCache();
  17325. }
  17326. /**
  17327. * Add a new node constructor
  17328. * @param type defines the type name of the node to construct
  17329. * @param constructorFunc defines the constructor function
  17330. */
  17331. Node.AddNodeConstructor = function (type, constructorFunc) {
  17332. this._NodeConstructors[type] = constructorFunc;
  17333. };
  17334. /**
  17335. * Returns a node constructor based on type name
  17336. * @param type defines the type name
  17337. * @param name defines the new node name
  17338. * @param scene defines the hosting scene
  17339. * @param options defines optional options to transmit to constructors
  17340. * @returns the new constructor or null
  17341. */
  17342. Node.Construct = function (type, name, scene, options) {
  17343. var constructorFunc = this._NodeConstructors[type];
  17344. if (!constructorFunc) {
  17345. return null;
  17346. }
  17347. return constructorFunc(name, scene, options);
  17348. };
  17349. /**
  17350. * Gets a boolean indicating if the node has been disposed
  17351. * @returns true if the node was disposed
  17352. */
  17353. Node.prototype.isDisposed = function () {
  17354. return this._isDisposed;
  17355. };
  17356. Object.defineProperty(Node.prototype, "parent", {
  17357. get: function () {
  17358. return this._parentNode;
  17359. },
  17360. /**
  17361. * Gets or sets the parent of the node
  17362. */
  17363. set: function (parent) {
  17364. if (this._parentNode === parent) {
  17365. return;
  17366. }
  17367. // Remove self from list of children of parent
  17368. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17369. var index = this._parentNode._children.indexOf(this);
  17370. if (index !== -1) {
  17371. this._parentNode._children.splice(index, 1);
  17372. }
  17373. }
  17374. // Store new parent
  17375. this._parentNode = parent;
  17376. // Add as child to new parent
  17377. if (this._parentNode) {
  17378. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17379. this._parentNode._children = new Array();
  17380. }
  17381. this._parentNode._children.push(this);
  17382. }
  17383. },
  17384. enumerable: true,
  17385. configurable: true
  17386. });
  17387. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17388. /**
  17389. * Gets or sets the animation properties override
  17390. */
  17391. get: function () {
  17392. if (!this._animationPropertiesOverride) {
  17393. return this._scene.animationPropertiesOverride;
  17394. }
  17395. return this._animationPropertiesOverride;
  17396. },
  17397. set: function (value) {
  17398. this._animationPropertiesOverride = value;
  17399. },
  17400. enumerable: true,
  17401. configurable: true
  17402. });
  17403. /**
  17404. * Gets a string idenfifying the name of the class
  17405. * @returns "Node" string
  17406. */
  17407. Node.prototype.getClassName = function () {
  17408. return "Node";
  17409. };
  17410. Object.defineProperty(Node.prototype, "onDispose", {
  17411. /**
  17412. * Sets a callback that will be raised when the node will be disposed
  17413. */
  17414. set: function (callback) {
  17415. if (this._onDisposeObserver) {
  17416. this.onDisposeObservable.remove(this._onDisposeObserver);
  17417. }
  17418. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17419. },
  17420. enumerable: true,
  17421. configurable: true
  17422. });
  17423. /**
  17424. * Gets the scene of the node
  17425. * @returns a {BABYLON.Scene}
  17426. */
  17427. Node.prototype.getScene = function () {
  17428. return this._scene;
  17429. };
  17430. /**
  17431. * Gets the engine of the node
  17432. * @returns a {BABYLON.Engine}
  17433. */
  17434. Node.prototype.getEngine = function () {
  17435. return this._scene.getEngine();
  17436. };
  17437. /**
  17438. * Attach a behavior to the node
  17439. * @see http://doc.babylonjs.com/features/behaviour
  17440. * @param behavior defines the behavior to attach
  17441. * @returns the current Node
  17442. */
  17443. Node.prototype.addBehavior = function (behavior) {
  17444. var _this = this;
  17445. var index = this._behaviors.indexOf(behavior);
  17446. if (index !== -1) {
  17447. return this;
  17448. }
  17449. behavior.init();
  17450. if (this._scene.isLoading) {
  17451. // We defer the attach when the scene will be loaded
  17452. this._scene.onDataLoadedObservable.addOnce(function () {
  17453. behavior.attach(_this);
  17454. });
  17455. }
  17456. else {
  17457. behavior.attach(this);
  17458. }
  17459. this._behaviors.push(behavior);
  17460. return this;
  17461. };
  17462. /**
  17463. * Remove an attached behavior
  17464. * @see http://doc.babylonjs.com/features/behaviour
  17465. * @param behavior defines the behavior to attach
  17466. * @returns the current Node
  17467. */
  17468. Node.prototype.removeBehavior = function (behavior) {
  17469. var index = this._behaviors.indexOf(behavior);
  17470. if (index === -1) {
  17471. return this;
  17472. }
  17473. this._behaviors[index].detach();
  17474. this._behaviors.splice(index, 1);
  17475. return this;
  17476. };
  17477. Object.defineProperty(Node.prototype, "behaviors", {
  17478. /**
  17479. * Gets the list of attached behaviors
  17480. * @see http://doc.babylonjs.com/features/behaviour
  17481. */
  17482. get: function () {
  17483. return this._behaviors;
  17484. },
  17485. enumerable: true,
  17486. configurable: true
  17487. });
  17488. /**
  17489. * Gets an attached behavior by name
  17490. * @param name defines the name of the behavior to look for
  17491. * @see http://doc.babylonjs.com/features/behaviour
  17492. * @returns null if behavior was not found else the requested behavior
  17493. */
  17494. Node.prototype.getBehaviorByName = function (name) {
  17495. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17496. var behavior = _a[_i];
  17497. if (behavior.name === name) {
  17498. return behavior;
  17499. }
  17500. }
  17501. return null;
  17502. };
  17503. /**
  17504. * Returns the world matrix of the node
  17505. * @returns a matrix containing the node's world matrix
  17506. */
  17507. Node.prototype.getWorldMatrix = function () {
  17508. return BABYLON.Matrix.Identity();
  17509. };
  17510. /** @hidden */
  17511. Node.prototype._getWorldMatrixDeterminant = function () {
  17512. return 1;
  17513. };
  17514. // override it in derived class if you add new variables to the cache
  17515. // and call the parent class method
  17516. /** @hidden */
  17517. Node.prototype._initCache = function () {
  17518. this._cache = {};
  17519. this._cache.parent = undefined;
  17520. };
  17521. /** @hidden */
  17522. Node.prototype.updateCache = function (force) {
  17523. if (!force && this.isSynchronized())
  17524. return;
  17525. this._cache.parent = this.parent;
  17526. this._updateCache();
  17527. };
  17528. // override it in derived class if you add new variables to the cache
  17529. // and call the parent class method if !ignoreParentClass
  17530. /** @hidden */
  17531. Node.prototype._updateCache = function (ignoreParentClass) {
  17532. };
  17533. // override it in derived class if you add new variables to the cache
  17534. /** @hidden */
  17535. Node.prototype._isSynchronized = function () {
  17536. return true;
  17537. };
  17538. /** @hidden */
  17539. Node.prototype._markSyncedWithParent = function () {
  17540. if (this.parent) {
  17541. this._parentRenderId = this.parent._childRenderId;
  17542. }
  17543. };
  17544. /** @hidden */
  17545. Node.prototype.isSynchronizedWithParent = function () {
  17546. if (!this.parent) {
  17547. return true;
  17548. }
  17549. if (this._parentRenderId !== this.parent._childRenderId) {
  17550. return false;
  17551. }
  17552. return this.parent.isSynchronized();
  17553. };
  17554. /** @hidden */
  17555. Node.prototype.isSynchronized = function (updateCache) {
  17556. var check = this.hasNewParent();
  17557. check = check || !this.isSynchronizedWithParent();
  17558. check = check || !this._isSynchronized();
  17559. if (updateCache)
  17560. this.updateCache(true);
  17561. return !check;
  17562. };
  17563. /** @hidden */
  17564. Node.prototype.hasNewParent = function (update) {
  17565. if (this._cache.parent === this.parent)
  17566. return false;
  17567. if (update)
  17568. this._cache.parent = this.parent;
  17569. return true;
  17570. };
  17571. /**
  17572. * Is this node ready to be used/rendered
  17573. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17574. * @return true if the node is ready
  17575. */
  17576. Node.prototype.isReady = function (completeCheck) {
  17577. if (completeCheck === void 0) { completeCheck = false; }
  17578. return this._isReady;
  17579. };
  17580. /**
  17581. * Is this node enabled?
  17582. * 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
  17583. * @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
  17584. * @return whether this node (and its parent) is enabled
  17585. */
  17586. Node.prototype.isEnabled = function (checkAncestors) {
  17587. if (checkAncestors === void 0) { checkAncestors = true; }
  17588. if (checkAncestors === false) {
  17589. return this._isEnabled;
  17590. }
  17591. if (this._isEnabled === false) {
  17592. return false;
  17593. }
  17594. if (this.parent !== undefined && this.parent !== null) {
  17595. return this.parent.isEnabled(checkAncestors);
  17596. }
  17597. return true;
  17598. };
  17599. /**
  17600. * Set the enabled state of this node
  17601. * @param value defines the new enabled state
  17602. */
  17603. Node.prototype.setEnabled = function (value) {
  17604. this._isEnabled = value;
  17605. };
  17606. /**
  17607. * Is this node a descendant of the given node?
  17608. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17609. * @param ancestor defines the parent node to inspect
  17610. * @returns a boolean indicating if this node is a descendant of the given node
  17611. */
  17612. Node.prototype.isDescendantOf = function (ancestor) {
  17613. if (this.parent) {
  17614. if (this.parent === ancestor) {
  17615. return true;
  17616. }
  17617. return this.parent.isDescendantOf(ancestor);
  17618. }
  17619. return false;
  17620. };
  17621. /** @hidden */
  17622. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17623. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17624. if (!this._children) {
  17625. return;
  17626. }
  17627. for (var index = 0; index < this._children.length; index++) {
  17628. var item = this._children[index];
  17629. if (!predicate || predicate(item)) {
  17630. results.push(item);
  17631. }
  17632. if (!directDescendantsOnly) {
  17633. item._getDescendants(results, false, predicate);
  17634. }
  17635. }
  17636. };
  17637. /**
  17638. * Will return all nodes that have this node as ascendant
  17639. * @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
  17640. * @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
  17641. * @return all children nodes of all types
  17642. */
  17643. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17644. var results = new Array();
  17645. this._getDescendants(results, directDescendantsOnly, predicate);
  17646. return results;
  17647. };
  17648. /**
  17649. * Get all child-meshes of this node
  17650. * @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
  17651. * @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
  17652. * @returns an array of {BABYLON.AbstractMesh}
  17653. */
  17654. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17655. var results = [];
  17656. this._getDescendants(results, directDescendantsOnly, function (node) {
  17657. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17658. });
  17659. return results;
  17660. };
  17661. /**
  17662. * Get all child-transformNodes of this node
  17663. * @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
  17664. * @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
  17665. * @returns an array of {BABYLON.TransformNode}
  17666. */
  17667. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17668. var results = [];
  17669. this._getDescendants(results, directDescendantsOnly, function (node) {
  17670. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17671. });
  17672. return results;
  17673. };
  17674. /**
  17675. * Get all direct children of this node
  17676. * @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
  17677. * @returns an array of {BABYLON.Node}
  17678. */
  17679. Node.prototype.getChildren = function (predicate) {
  17680. return this.getDescendants(true, predicate);
  17681. };
  17682. /** @hidden */
  17683. Node.prototype._setReady = function (state) {
  17684. if (state === this._isReady) {
  17685. return;
  17686. }
  17687. if (!state) {
  17688. this._isReady = false;
  17689. return;
  17690. }
  17691. if (this.onReady) {
  17692. this.onReady(this);
  17693. }
  17694. this._isReady = true;
  17695. };
  17696. /**
  17697. * Get an animation by name
  17698. * @param name defines the name of the animation to look for
  17699. * @returns null if not found else the requested animation
  17700. */
  17701. Node.prototype.getAnimationByName = function (name) {
  17702. for (var i = 0; i < this.animations.length; i++) {
  17703. var animation = this.animations[i];
  17704. if (animation.name === name) {
  17705. return animation;
  17706. }
  17707. }
  17708. return null;
  17709. };
  17710. /**
  17711. * Creates an animation range for this node
  17712. * @param name defines the name of the range
  17713. * @param from defines the starting key
  17714. * @param to defines the end key
  17715. */
  17716. Node.prototype.createAnimationRange = function (name, from, to) {
  17717. // check name not already in use
  17718. if (!this._ranges[name]) {
  17719. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17720. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17721. if (this.animations[i]) {
  17722. this.animations[i].createRange(name, from, to);
  17723. }
  17724. }
  17725. }
  17726. };
  17727. /**
  17728. * Delete a specific animation range
  17729. * @param name defines the name of the range to delete
  17730. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17731. */
  17732. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17733. if (deleteFrames === void 0) { deleteFrames = true; }
  17734. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17735. if (this.animations[i]) {
  17736. this.animations[i].deleteRange(name, deleteFrames);
  17737. }
  17738. }
  17739. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17740. };
  17741. /**
  17742. * Get an animation range by name
  17743. * @param name defines the name of the animation range to look for
  17744. * @returns null if not found else the requested animation range
  17745. */
  17746. Node.prototype.getAnimationRange = function (name) {
  17747. return this._ranges[name];
  17748. };
  17749. /**
  17750. * Will start the animation sequence
  17751. * @param name defines the range frames for animation sequence
  17752. * @param loop defines if the animation should loop (false by default)
  17753. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17754. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17755. * @returns the object created for this animation. If range does not exist, it will return null
  17756. */
  17757. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17758. var range = this.getAnimationRange(name);
  17759. if (!range) {
  17760. return null;
  17761. }
  17762. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17763. };
  17764. /**
  17765. * Serialize animation ranges into a JSON compatible object
  17766. * @returns serialization object
  17767. */
  17768. Node.prototype.serializeAnimationRanges = function () {
  17769. var serializationRanges = [];
  17770. for (var name in this._ranges) {
  17771. var localRange = this._ranges[name];
  17772. if (!localRange) {
  17773. continue;
  17774. }
  17775. var range = {};
  17776. range.name = name;
  17777. range.from = localRange.from;
  17778. range.to = localRange.to;
  17779. serializationRanges.push(range);
  17780. }
  17781. return serializationRanges;
  17782. };
  17783. /**
  17784. * Computes the world matrix of the node
  17785. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17786. * @returns the world matrix
  17787. */
  17788. Node.prototype.computeWorldMatrix = function (force) {
  17789. return BABYLON.Matrix.Identity();
  17790. };
  17791. /**
  17792. * Releases resources associated with this node.
  17793. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17794. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17795. */
  17796. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17797. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17798. if (!doNotRecurse) {
  17799. var nodes = this.getDescendants(true);
  17800. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17801. var node = nodes_1[_i];
  17802. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17803. }
  17804. }
  17805. else {
  17806. var transformNodes = this.getChildTransformNodes(true);
  17807. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17808. var transformNode = transformNodes_1[_a];
  17809. transformNode.parent = null;
  17810. transformNode.computeWorldMatrix(true);
  17811. }
  17812. }
  17813. this.parent = null;
  17814. // Callback
  17815. this.onDisposeObservable.notifyObservers(this);
  17816. this.onDisposeObservable.clear();
  17817. // Behaviors
  17818. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17819. var behavior = _c[_b];
  17820. behavior.detach();
  17821. }
  17822. this._behaviors = [];
  17823. this._isDisposed = true;
  17824. };
  17825. /**
  17826. * Parse animation range data from a serialization object and store them into a given node
  17827. * @param node defines where to store the animation ranges
  17828. * @param parsedNode defines the serialization object to read data from
  17829. * @param scene defines the hosting scene
  17830. */
  17831. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17832. if (parsedNode.ranges) {
  17833. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17834. var data = parsedNode.ranges[index];
  17835. node.createAnimationRange(data.name, data.from, data.to);
  17836. }
  17837. }
  17838. };
  17839. Node._NodeConstructors = {};
  17840. __decorate([
  17841. BABYLON.serialize()
  17842. ], Node.prototype, "name", void 0);
  17843. __decorate([
  17844. BABYLON.serialize()
  17845. ], Node.prototype, "id", void 0);
  17846. __decorate([
  17847. BABYLON.serialize()
  17848. ], Node.prototype, "uniqueId", void 0);
  17849. __decorate([
  17850. BABYLON.serialize()
  17851. ], Node.prototype, "state", void 0);
  17852. __decorate([
  17853. BABYLON.serialize()
  17854. ], Node.prototype, "metadata", void 0);
  17855. return Node;
  17856. }());
  17857. BABYLON.Node = Node;
  17858. })(BABYLON || (BABYLON = {}));
  17859. //# sourceMappingURL=babylon.node.js.map
  17860. var BABYLON;
  17861. (function (BABYLON) {
  17862. var BoundingSphere = /** @class */ (function () {
  17863. /**
  17864. * Creates a new bounding sphere
  17865. * @param min defines the minimum vector (in local space)
  17866. * @param max defines the maximum vector (in local space)
  17867. */
  17868. function BoundingSphere(min, max) {
  17869. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17870. this.reConstruct(min, max);
  17871. }
  17872. /**
  17873. * Recreates the entire bounding sphere from scratch
  17874. * @param min defines the new minimum vector (in local space)
  17875. * @param max defines the new maximum vector (in local space)
  17876. */
  17877. BoundingSphere.prototype.reConstruct = function (min, max) {
  17878. this.minimum = min.clone();
  17879. this.maximum = max.clone();
  17880. var distance = BABYLON.Vector3.Distance(min, max);
  17881. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17882. this.radius = distance * 0.5;
  17883. this.centerWorld = BABYLON.Vector3.Zero();
  17884. this._update(BABYLON.Matrix.Identity());
  17885. };
  17886. /**
  17887. * Scale the current bounding sphere by applying a scale factor
  17888. * @param factor defines the scale factor to apply
  17889. * @returns the current bounding box
  17890. */
  17891. BoundingSphere.prototype.scale = function (factor) {
  17892. var newRadius = this.radius * factor;
  17893. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  17894. var min = this.center.subtract(newRadiusVector);
  17895. var max = this.center.add(newRadiusVector);
  17896. this.reConstruct(min, max);
  17897. return this;
  17898. };
  17899. // Methods
  17900. BoundingSphere.prototype._update = function (world) {
  17901. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17902. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17903. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17904. };
  17905. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17906. for (var i = 0; i < 6; i++) {
  17907. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17908. return false;
  17909. }
  17910. return true;
  17911. };
  17912. BoundingSphere.prototype.intersectsPoint = function (point) {
  17913. var x = this.centerWorld.x - point.x;
  17914. var y = this.centerWorld.y - point.y;
  17915. var z = this.centerWorld.z - point.z;
  17916. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17917. if (this.radiusWorld < distance)
  17918. return false;
  17919. return true;
  17920. };
  17921. // Statics
  17922. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17923. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17924. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17925. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17926. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17927. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17928. return false;
  17929. return true;
  17930. };
  17931. return BoundingSphere;
  17932. }());
  17933. BABYLON.BoundingSphere = BoundingSphere;
  17934. })(BABYLON || (BABYLON = {}));
  17935. //# sourceMappingURL=babylon.boundingSphere.js.map
  17936. var BABYLON;
  17937. (function (BABYLON) {
  17938. var BoundingBox = /** @class */ (function () {
  17939. /**
  17940. * Creates a new bounding box
  17941. * @param min defines the minimum vector (in local space)
  17942. * @param max defines the maximum vector (in local space)
  17943. */
  17944. function BoundingBox(min, max) {
  17945. this.vectorsWorld = new Array();
  17946. this.reConstruct(min, max);
  17947. }
  17948. // Methods
  17949. /**
  17950. * Recreates the entire bounding box from scratch
  17951. * @param min defines the new minimum vector (in local space)
  17952. * @param max defines the new maximum vector (in local space)
  17953. */
  17954. BoundingBox.prototype.reConstruct = function (min, max) {
  17955. this.minimum = min.clone();
  17956. this.maximum = max.clone();
  17957. // Bounding vectors
  17958. this.vectors = new Array();
  17959. this.vectors.push(this.minimum.clone());
  17960. this.vectors.push(this.maximum.clone());
  17961. this.vectors.push(this.minimum.clone());
  17962. this.vectors[2].x = this.maximum.x;
  17963. this.vectors.push(this.minimum.clone());
  17964. this.vectors[3].y = this.maximum.y;
  17965. this.vectors.push(this.minimum.clone());
  17966. this.vectors[4].z = this.maximum.z;
  17967. this.vectors.push(this.maximum.clone());
  17968. this.vectors[5].z = this.minimum.z;
  17969. this.vectors.push(this.maximum.clone());
  17970. this.vectors[6].x = this.minimum.x;
  17971. this.vectors.push(this.maximum.clone());
  17972. this.vectors[7].y = this.minimum.y;
  17973. // OBB
  17974. this.center = this.maximum.add(this.minimum).scale(0.5);
  17975. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17976. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17977. // World
  17978. for (var index = 0; index < this.vectors.length; index++) {
  17979. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17980. }
  17981. this.minimumWorld = BABYLON.Vector3.Zero();
  17982. this.maximumWorld = BABYLON.Vector3.Zero();
  17983. this.centerWorld = BABYLON.Vector3.Zero();
  17984. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17985. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17986. };
  17987. /**
  17988. * Scale the current bounding box by applying a scale factor
  17989. * @param factor defines the scale factor to apply
  17990. * @returns the current bounding box
  17991. */
  17992. BoundingBox.prototype.scale = function (factor) {
  17993. var diff = this.maximum.subtract(this.minimum);
  17994. var distance = diff.length() * factor;
  17995. diff.normalize();
  17996. var newRadius = diff.scale(distance / 2);
  17997. var min = this.center.subtract(newRadius);
  17998. var max = this.center.add(newRadius);
  17999. this.reConstruct(min, max);
  18000. return this;
  18001. };
  18002. BoundingBox.prototype.getWorldMatrix = function () {
  18003. return this._worldMatrix;
  18004. };
  18005. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18006. this._worldMatrix.copyFrom(matrix);
  18007. return this;
  18008. };
  18009. BoundingBox.prototype._update = function (world) {
  18010. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18011. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18012. for (var index = 0; index < this.vectors.length; index++) {
  18013. var v = this.vectorsWorld[index];
  18014. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18015. if (v.x < this.minimumWorld.x)
  18016. this.minimumWorld.x = v.x;
  18017. if (v.y < this.minimumWorld.y)
  18018. this.minimumWorld.y = v.y;
  18019. if (v.z < this.minimumWorld.z)
  18020. this.minimumWorld.z = v.z;
  18021. if (v.x > this.maximumWorld.x)
  18022. this.maximumWorld.x = v.x;
  18023. if (v.y > this.maximumWorld.y)
  18024. this.maximumWorld.y = v.y;
  18025. if (v.z > this.maximumWorld.z)
  18026. this.maximumWorld.z = v.z;
  18027. }
  18028. // Extend
  18029. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18030. this.extendSizeWorld.scaleInPlace(0.5);
  18031. // OBB
  18032. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18033. this.centerWorld.scaleInPlace(0.5);
  18034. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18035. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18036. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18037. this._worldMatrix = world;
  18038. };
  18039. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18040. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18041. };
  18042. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18043. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18044. };
  18045. BoundingBox.prototype.intersectsPoint = function (point) {
  18046. var delta = -BABYLON.Epsilon;
  18047. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18048. return false;
  18049. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18050. return false;
  18051. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18052. return false;
  18053. return true;
  18054. };
  18055. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18056. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18057. };
  18058. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18059. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18060. return false;
  18061. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18062. return false;
  18063. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18064. return false;
  18065. return true;
  18066. };
  18067. // Statics
  18068. BoundingBox.Intersects = function (box0, box1) {
  18069. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18070. return false;
  18071. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18072. return false;
  18073. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18074. return false;
  18075. return true;
  18076. };
  18077. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18078. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18079. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18080. return (num <= (sphereRadius * sphereRadius));
  18081. };
  18082. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18083. for (var p = 0; p < 6; p++) {
  18084. for (var i = 0; i < 8; i++) {
  18085. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18086. return false;
  18087. }
  18088. }
  18089. }
  18090. return true;
  18091. };
  18092. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18093. for (var p = 0; p < 6; p++) {
  18094. var inCount = 8;
  18095. for (var i = 0; i < 8; i++) {
  18096. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18097. --inCount;
  18098. }
  18099. else {
  18100. break;
  18101. }
  18102. }
  18103. if (inCount === 0)
  18104. return false;
  18105. }
  18106. return true;
  18107. };
  18108. return BoundingBox;
  18109. }());
  18110. BABYLON.BoundingBox = BoundingBox;
  18111. })(BABYLON || (BABYLON = {}));
  18112. //# sourceMappingURL=babylon.boundingBox.js.map
  18113. var BABYLON;
  18114. (function (BABYLON) {
  18115. var computeBoxExtents = function (axis, box) {
  18116. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18117. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18118. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18119. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18120. var r = r0 + r1 + r2;
  18121. return {
  18122. min: p - r,
  18123. max: p + r
  18124. };
  18125. };
  18126. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18127. var axisOverlap = function (axis, box0, box1) {
  18128. var result0 = computeBoxExtents(axis, box0);
  18129. var result1 = computeBoxExtents(axis, box1);
  18130. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18131. };
  18132. var BoundingInfo = /** @class */ (function () {
  18133. function BoundingInfo(minimum, maximum) {
  18134. this.minimum = minimum;
  18135. this.maximum = maximum;
  18136. this._isLocked = false;
  18137. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18138. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18139. }
  18140. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18141. get: function () {
  18142. return this._isLocked;
  18143. },
  18144. set: function (value) {
  18145. this._isLocked = value;
  18146. },
  18147. enumerable: true,
  18148. configurable: true
  18149. });
  18150. // Methods
  18151. BoundingInfo.prototype.update = function (world) {
  18152. if (this._isLocked) {
  18153. return;
  18154. }
  18155. this.boundingBox._update(world);
  18156. this.boundingSphere._update(world);
  18157. };
  18158. /**
  18159. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18160. * @param center New center of the bounding info
  18161. * @param extend New extend of the bounding info
  18162. */
  18163. BoundingInfo.prototype.centerOn = function (center, extend) {
  18164. this.minimum = center.subtract(extend);
  18165. this.maximum = center.add(extend);
  18166. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18167. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18168. return this;
  18169. };
  18170. /**
  18171. * Scale the current bounding info by applying a scale factor
  18172. * @param factor defines the scale factor to apply
  18173. * @returns the current bounding info
  18174. */
  18175. BoundingInfo.prototype.scale = function (factor) {
  18176. this.boundingBox.scale(factor);
  18177. this.boundingSphere.scale(factor);
  18178. return this;
  18179. };
  18180. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18181. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18182. return false;
  18183. return this.boundingBox.isInFrustum(frustumPlanes);
  18184. };
  18185. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18186. /**
  18187. * Gets the world distance between the min and max points of the bounding box
  18188. */
  18189. get: function () {
  18190. var boundingBox = this.boundingBox;
  18191. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18192. return size.length();
  18193. },
  18194. enumerable: true,
  18195. configurable: true
  18196. });
  18197. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18198. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18199. };
  18200. BoundingInfo.prototype._checkCollision = function (collider) {
  18201. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18202. };
  18203. BoundingInfo.prototype.intersectsPoint = function (point) {
  18204. if (!this.boundingSphere.centerWorld) {
  18205. return false;
  18206. }
  18207. if (!this.boundingSphere.intersectsPoint(point)) {
  18208. return false;
  18209. }
  18210. if (!this.boundingBox.intersectsPoint(point)) {
  18211. return false;
  18212. }
  18213. return true;
  18214. };
  18215. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18216. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18217. return false;
  18218. }
  18219. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18220. return false;
  18221. }
  18222. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18223. return false;
  18224. }
  18225. if (!precise) {
  18226. return true;
  18227. }
  18228. var box0 = this.boundingBox;
  18229. var box1 = boundingInfo.boundingBox;
  18230. if (!axisOverlap(box0.directions[0], box0, box1))
  18231. return false;
  18232. if (!axisOverlap(box0.directions[1], box0, box1))
  18233. return false;
  18234. if (!axisOverlap(box0.directions[2], box0, box1))
  18235. return false;
  18236. if (!axisOverlap(box1.directions[0], box0, box1))
  18237. return false;
  18238. if (!axisOverlap(box1.directions[1], box0, box1))
  18239. return false;
  18240. if (!axisOverlap(box1.directions[2], box0, box1))
  18241. return false;
  18242. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18243. return false;
  18244. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18245. return false;
  18246. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18247. return false;
  18248. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18249. return false;
  18250. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18251. return false;
  18252. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18253. return false;
  18254. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18255. return false;
  18256. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18257. return false;
  18258. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18259. return false;
  18260. return true;
  18261. };
  18262. return BoundingInfo;
  18263. }());
  18264. BABYLON.BoundingInfo = BoundingInfo;
  18265. })(BABYLON || (BABYLON = {}));
  18266. //# sourceMappingURL=babylon.boundingInfo.js.map
  18267. var BABYLON;
  18268. (function (BABYLON) {
  18269. var TransformNode = /** @class */ (function (_super) {
  18270. __extends(TransformNode, _super);
  18271. function TransformNode(name, scene, isPure) {
  18272. if (scene === void 0) { scene = null; }
  18273. if (isPure === void 0) { isPure = true; }
  18274. var _this = _super.call(this, name, scene) || this;
  18275. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18276. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18277. _this._up = new BABYLON.Vector3(0, 1, 0);
  18278. _this._right = new BABYLON.Vector3(1, 0, 0);
  18279. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18280. // Properties
  18281. _this._rotation = BABYLON.Vector3.Zero();
  18282. _this._scaling = BABYLON.Vector3.One();
  18283. _this._isDirty = false;
  18284. /**
  18285. * Set the billboard mode. Default is 0.
  18286. *
  18287. * | Value | Type | Description |
  18288. * | --- | --- | --- |
  18289. * | 0 | BILLBOARDMODE_NONE | |
  18290. * | 1 | BILLBOARDMODE_X | |
  18291. * | 2 | BILLBOARDMODE_Y | |
  18292. * | 4 | BILLBOARDMODE_Z | |
  18293. * | 7 | BILLBOARDMODE_ALL | |
  18294. *
  18295. */
  18296. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18297. _this.scalingDeterminant = 1;
  18298. _this.infiniteDistance = false;
  18299. /**
  18300. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18301. * By default the system will update normals to compensate
  18302. */
  18303. _this.ignoreNonUniformScaling = false;
  18304. _this.position = BABYLON.Vector3.Zero();
  18305. _this._localWorld = BABYLON.Matrix.Zero();
  18306. _this._worldMatrix = BABYLON.Matrix.Zero();
  18307. _this._worldMatrixDeterminant = 0;
  18308. _this._absolutePosition = BABYLON.Vector3.Zero();
  18309. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18310. _this._postMultiplyPivotMatrix = false;
  18311. _this._isWorldMatrixFrozen = false;
  18312. /**
  18313. * An event triggered after the world matrix is updated
  18314. */
  18315. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18316. _this._nonUniformScaling = false;
  18317. if (isPure) {
  18318. _this.getScene().addTransformNode(_this);
  18319. }
  18320. return _this;
  18321. }
  18322. /**
  18323. * Gets a string identifying the name of the class
  18324. * @returns "TransformNode" string
  18325. */
  18326. TransformNode.prototype.getClassName = function () {
  18327. return "TransformNode";
  18328. };
  18329. Object.defineProperty(TransformNode.prototype, "rotation", {
  18330. /**
  18331. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18332. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18333. * Default : (0.0, 0.0, 0.0)
  18334. */
  18335. get: function () {
  18336. return this._rotation;
  18337. },
  18338. set: function (newRotation) {
  18339. this._rotation = newRotation;
  18340. },
  18341. enumerable: true,
  18342. configurable: true
  18343. });
  18344. Object.defineProperty(TransformNode.prototype, "scaling", {
  18345. /**
  18346. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18347. * Default : (1.0, 1.0, 1.0)
  18348. */
  18349. get: function () {
  18350. return this._scaling;
  18351. },
  18352. /**
  18353. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18354. * Default : (1.0, 1.0, 1.0)
  18355. */
  18356. set: function (newScaling) {
  18357. this._scaling = newScaling;
  18358. },
  18359. enumerable: true,
  18360. configurable: true
  18361. });
  18362. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18363. /**
  18364. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18365. * It's null by default.
  18366. * 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)
  18367. */
  18368. get: function () {
  18369. return this._rotationQuaternion;
  18370. },
  18371. set: function (quaternion) {
  18372. this._rotationQuaternion = quaternion;
  18373. //reset the rotation vector.
  18374. if (quaternion && this.rotation.length()) {
  18375. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18376. }
  18377. },
  18378. enumerable: true,
  18379. configurable: true
  18380. });
  18381. Object.defineProperty(TransformNode.prototype, "forward", {
  18382. /**
  18383. * The forward direction of that transform in world space.
  18384. */
  18385. get: function () {
  18386. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18387. },
  18388. enumerable: true,
  18389. configurable: true
  18390. });
  18391. Object.defineProperty(TransformNode.prototype, "up", {
  18392. /**
  18393. * The up direction of that transform in world space.
  18394. */
  18395. get: function () {
  18396. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18397. },
  18398. enumerable: true,
  18399. configurable: true
  18400. });
  18401. Object.defineProperty(TransformNode.prototype, "right", {
  18402. /**
  18403. * The right direction of that transform in world space.
  18404. */
  18405. get: function () {
  18406. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18407. },
  18408. enumerable: true,
  18409. configurable: true
  18410. });
  18411. /**
  18412. * Returns the latest update of the World matrix
  18413. * Returns a Matrix.
  18414. */
  18415. TransformNode.prototype.getWorldMatrix = function () {
  18416. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18417. this.computeWorldMatrix();
  18418. }
  18419. return this._worldMatrix;
  18420. };
  18421. /** @hidden */
  18422. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18423. return this._worldMatrixDeterminant;
  18424. };
  18425. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18426. /**
  18427. * Returns directly the latest state of the mesh World matrix.
  18428. * A Matrix is returned.
  18429. */
  18430. get: function () {
  18431. return this._worldMatrix;
  18432. },
  18433. enumerable: true,
  18434. configurable: true
  18435. });
  18436. /**
  18437. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18438. * Returns the TransformNode.
  18439. */
  18440. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18441. this._poseMatrix.copyFrom(matrix);
  18442. return this;
  18443. };
  18444. /**
  18445. * Returns the mesh Pose matrix.
  18446. * Returned object : Matrix
  18447. */
  18448. TransformNode.prototype.getPoseMatrix = function () {
  18449. return this._poseMatrix;
  18450. };
  18451. TransformNode.prototype._isSynchronized = function () {
  18452. if (this._isDirty) {
  18453. return false;
  18454. }
  18455. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18456. return false;
  18457. if (this._cache.pivotMatrixUpdated) {
  18458. return false;
  18459. }
  18460. if (this.infiniteDistance) {
  18461. return false;
  18462. }
  18463. if (!this._cache.position.equals(this.position))
  18464. return false;
  18465. if (this.rotationQuaternion) {
  18466. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18467. return false;
  18468. }
  18469. if (!this._cache.rotation.equals(this.rotation))
  18470. return false;
  18471. if (!this._cache.scaling.equals(this.scaling))
  18472. return false;
  18473. return true;
  18474. };
  18475. TransformNode.prototype._initCache = function () {
  18476. _super.prototype._initCache.call(this);
  18477. this._cache.localMatrixUpdated = false;
  18478. this._cache.position = BABYLON.Vector3.Zero();
  18479. this._cache.scaling = BABYLON.Vector3.Zero();
  18480. this._cache.rotation = BABYLON.Vector3.Zero();
  18481. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18482. this._cache.billboardMode = -1;
  18483. };
  18484. TransformNode.prototype.markAsDirty = function (property) {
  18485. if (property === "rotation") {
  18486. this.rotationQuaternion = null;
  18487. }
  18488. this._currentRenderId = Number.MAX_VALUE;
  18489. this._isDirty = true;
  18490. return this;
  18491. };
  18492. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18493. /**
  18494. * Returns the current mesh absolute position.
  18495. * Returns a Vector3.
  18496. */
  18497. get: function () {
  18498. return this._absolutePosition;
  18499. },
  18500. enumerable: true,
  18501. configurable: true
  18502. });
  18503. /**
  18504. * Sets a new matrix to apply before all other transformation
  18505. * @param matrix defines the transform matrix
  18506. * @returns the current TransformNode
  18507. */
  18508. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18509. return this.setPivotMatrix(matrix, false);
  18510. };
  18511. /**
  18512. * Sets a new pivot matrix to the current node
  18513. * @param matrix defines the new pivot matrix to use
  18514. * @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
  18515. * @returns the current TransformNode
  18516. */
  18517. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18518. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18519. this._pivotMatrix = matrix.clone();
  18520. this._cache.pivotMatrixUpdated = true;
  18521. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18522. if (this._postMultiplyPivotMatrix) {
  18523. if (!this._pivotMatrixInverse) {
  18524. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18525. }
  18526. else {
  18527. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18528. }
  18529. }
  18530. return this;
  18531. };
  18532. /**
  18533. * Returns the mesh pivot matrix.
  18534. * Default : Identity.
  18535. * A Matrix is returned.
  18536. */
  18537. TransformNode.prototype.getPivotMatrix = function () {
  18538. return this._pivotMatrix;
  18539. };
  18540. /**
  18541. * Prevents the World matrix to be computed any longer.
  18542. * Returns the TransformNode.
  18543. */
  18544. TransformNode.prototype.freezeWorldMatrix = function () {
  18545. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18546. this.computeWorldMatrix(true);
  18547. this._isWorldMatrixFrozen = true;
  18548. return this;
  18549. };
  18550. /**
  18551. * Allows back the World matrix computation.
  18552. * Returns the TransformNode.
  18553. */
  18554. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18555. this._isWorldMatrixFrozen = false;
  18556. this.computeWorldMatrix(true);
  18557. return this;
  18558. };
  18559. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18560. /**
  18561. * True if the World matrix has been frozen.
  18562. * Returns a boolean.
  18563. */
  18564. get: function () {
  18565. return this._isWorldMatrixFrozen;
  18566. },
  18567. enumerable: true,
  18568. configurable: true
  18569. });
  18570. /**
  18571. * Retuns the mesh absolute position in the World.
  18572. * Returns a Vector3.
  18573. */
  18574. TransformNode.prototype.getAbsolutePosition = function () {
  18575. this.computeWorldMatrix();
  18576. return this._absolutePosition;
  18577. };
  18578. /**
  18579. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18580. * Returns the TransformNode.
  18581. */
  18582. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18583. if (!absolutePosition) {
  18584. return this;
  18585. }
  18586. var absolutePositionX;
  18587. var absolutePositionY;
  18588. var absolutePositionZ;
  18589. if (absolutePosition.x === undefined) {
  18590. if (arguments.length < 3) {
  18591. return this;
  18592. }
  18593. absolutePositionX = arguments[0];
  18594. absolutePositionY = arguments[1];
  18595. absolutePositionZ = arguments[2];
  18596. }
  18597. else {
  18598. absolutePositionX = absolutePosition.x;
  18599. absolutePositionY = absolutePosition.y;
  18600. absolutePositionZ = absolutePosition.z;
  18601. }
  18602. if (this.parent) {
  18603. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18604. invertParentWorldMatrix.invert();
  18605. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18606. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18607. }
  18608. else {
  18609. this.position.x = absolutePositionX;
  18610. this.position.y = absolutePositionY;
  18611. this.position.z = absolutePositionZ;
  18612. }
  18613. return this;
  18614. };
  18615. /**
  18616. * Sets the mesh position in its local space.
  18617. * Returns the TransformNode.
  18618. */
  18619. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18620. this.computeWorldMatrix();
  18621. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18622. return this;
  18623. };
  18624. /**
  18625. * Returns the mesh position in the local space from the current World matrix values.
  18626. * Returns a new Vector3.
  18627. */
  18628. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18629. this.computeWorldMatrix();
  18630. var invLocalWorldMatrix = this._localWorld.clone();
  18631. invLocalWorldMatrix.invert();
  18632. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18633. };
  18634. /**
  18635. * Translates the mesh along the passed Vector3 in its local space.
  18636. * Returns the TransformNode.
  18637. */
  18638. TransformNode.prototype.locallyTranslate = function (vector3) {
  18639. this.computeWorldMatrix(true);
  18640. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18641. return this;
  18642. };
  18643. /**
  18644. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18645. * @param targetPoint the position (must be in same space as current mesh) to look at
  18646. * @param yawCor optional yaw (y-axis) correction in radians
  18647. * @param pitchCor optional pitch (x-axis) correction in radians
  18648. * @param rollCor optional roll (z-axis) correction in radians
  18649. * @param space the choosen space of the target
  18650. * @returns the TransformNode.
  18651. */
  18652. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18653. if (yawCor === void 0) { yawCor = 0; }
  18654. if (pitchCor === void 0) { pitchCor = 0; }
  18655. if (rollCor === void 0) { rollCor = 0; }
  18656. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18657. var dv = TransformNode._lookAtVectorCache;
  18658. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18659. targetPoint.subtractToRef(pos, dv);
  18660. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18661. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18662. var pitch = Math.atan2(dv.y, len);
  18663. if (this.rotationQuaternion) {
  18664. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18665. }
  18666. else {
  18667. this.rotation.x = pitch + pitchCor;
  18668. this.rotation.y = yaw + yawCor;
  18669. this.rotation.z = rollCor;
  18670. }
  18671. return this;
  18672. };
  18673. /**
  18674. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18675. * This Vector3 is expressed in the World space.
  18676. */
  18677. TransformNode.prototype.getDirection = function (localAxis) {
  18678. var result = BABYLON.Vector3.Zero();
  18679. this.getDirectionToRef(localAxis, result);
  18680. return result;
  18681. };
  18682. /**
  18683. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18684. * localAxis is expressed in the mesh local space.
  18685. * result is computed in the Wordl space from the mesh World matrix.
  18686. * Returns the TransformNode.
  18687. */
  18688. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18689. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18690. return this;
  18691. };
  18692. /**
  18693. * Sets a new pivot point to the current node
  18694. * @param point defines the new pivot point to use
  18695. * @param space defines if the point is in world or local space (local by default)
  18696. * @returns the current TransformNode
  18697. */
  18698. TransformNode.prototype.setPivotPoint = function (point, space) {
  18699. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18700. if (this.getScene().getRenderId() == 0) {
  18701. this.computeWorldMatrix(true);
  18702. }
  18703. var wm = this.getWorldMatrix();
  18704. if (space == BABYLON.Space.WORLD) {
  18705. var tmat = BABYLON.Tmp.Matrix[0];
  18706. wm.invertToRef(tmat);
  18707. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18708. }
  18709. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18710. };
  18711. /**
  18712. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18713. */
  18714. TransformNode.prototype.getPivotPoint = function () {
  18715. var point = BABYLON.Vector3.Zero();
  18716. this.getPivotPointToRef(point);
  18717. return point;
  18718. };
  18719. /**
  18720. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18721. * Returns the TransformNode.
  18722. */
  18723. TransformNode.prototype.getPivotPointToRef = function (result) {
  18724. result.x = -this._pivotMatrix.m[12];
  18725. result.y = -this._pivotMatrix.m[13];
  18726. result.z = -this._pivotMatrix.m[14];
  18727. return this;
  18728. };
  18729. /**
  18730. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18731. */
  18732. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18733. var point = BABYLON.Vector3.Zero();
  18734. this.getAbsolutePivotPointToRef(point);
  18735. return point;
  18736. };
  18737. /**
  18738. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18739. * Returns the TransformNode.
  18740. */
  18741. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18742. result.x = this._pivotMatrix.m[12];
  18743. result.y = this._pivotMatrix.m[13];
  18744. result.z = this._pivotMatrix.m[14];
  18745. this.getPivotPointToRef(result);
  18746. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18747. return this;
  18748. };
  18749. /**
  18750. * Defines the passed node as the parent of the current node.
  18751. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18752. * Returns the TransformNode.
  18753. */
  18754. TransformNode.prototype.setParent = function (node) {
  18755. if (!node && !this.parent) {
  18756. return this;
  18757. }
  18758. if (!node) {
  18759. var rotation = BABYLON.Tmp.Quaternion[0];
  18760. var position = BABYLON.Tmp.Vector3[0];
  18761. var scale = BABYLON.Tmp.Vector3[1];
  18762. if (this.parent && this.parent.computeWorldMatrix) {
  18763. this.parent.computeWorldMatrix(true);
  18764. }
  18765. this.computeWorldMatrix(true);
  18766. this.getWorldMatrix().decompose(scale, rotation, position);
  18767. if (this.rotationQuaternion) {
  18768. this.rotationQuaternion.copyFrom(rotation);
  18769. }
  18770. else {
  18771. rotation.toEulerAnglesToRef(this.rotation);
  18772. }
  18773. this.scaling.x = scale.x;
  18774. this.scaling.y = scale.y;
  18775. this.scaling.z = scale.z;
  18776. this.position.x = position.x;
  18777. this.position.y = position.y;
  18778. this.position.z = position.z;
  18779. }
  18780. else {
  18781. var rotation = BABYLON.Tmp.Quaternion[0];
  18782. var position = BABYLON.Tmp.Vector3[0];
  18783. var scale = BABYLON.Tmp.Vector3[1];
  18784. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18785. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18786. this.computeWorldMatrix(true);
  18787. node.computeWorldMatrix(true);
  18788. node.getWorldMatrix().invertToRef(invParentMatrix);
  18789. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18790. diffMatrix.decompose(scale, rotation, position);
  18791. if (this.rotationQuaternion) {
  18792. this.rotationQuaternion.copyFrom(rotation);
  18793. }
  18794. else {
  18795. rotation.toEulerAnglesToRef(this.rotation);
  18796. }
  18797. this.position.x = position.x;
  18798. this.position.y = position.y;
  18799. this.position.z = position.z;
  18800. this.scaling.x = scale.x;
  18801. this.scaling.y = scale.y;
  18802. this.scaling.z = scale.z;
  18803. }
  18804. this.parent = node;
  18805. return this;
  18806. };
  18807. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18808. get: function () {
  18809. return this._nonUniformScaling;
  18810. },
  18811. enumerable: true,
  18812. configurable: true
  18813. });
  18814. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18815. if (this._nonUniformScaling === value) {
  18816. return false;
  18817. }
  18818. this._nonUniformScaling = value;
  18819. return true;
  18820. };
  18821. /**
  18822. * Attach the current TransformNode to another TransformNode associated with a bone
  18823. * @param bone Bone affecting the TransformNode
  18824. * @param affectedTransformNode TransformNode associated with the bone
  18825. */
  18826. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18827. this._transformToBoneReferal = affectedTransformNode;
  18828. this.parent = bone;
  18829. if (bone.getWorldMatrix().determinant() < 0) {
  18830. this.scalingDeterminant *= -1;
  18831. }
  18832. return this;
  18833. };
  18834. TransformNode.prototype.detachFromBone = function () {
  18835. if (!this.parent) {
  18836. return this;
  18837. }
  18838. if (this.parent.getWorldMatrix().determinant() < 0) {
  18839. this.scalingDeterminant *= -1;
  18840. }
  18841. this._transformToBoneReferal = null;
  18842. this.parent = null;
  18843. return this;
  18844. };
  18845. /**
  18846. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18847. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18848. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18849. * The passed axis is also normalized.
  18850. * Returns the TransformNode.
  18851. */
  18852. TransformNode.prototype.rotate = function (axis, amount, space) {
  18853. axis.normalize();
  18854. if (!this.rotationQuaternion) {
  18855. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18856. this.rotation = BABYLON.Vector3.Zero();
  18857. }
  18858. var rotationQuaternion;
  18859. if (!space || space === BABYLON.Space.LOCAL) {
  18860. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18861. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18862. }
  18863. else {
  18864. if (this.parent) {
  18865. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18866. invertParentWorldMatrix.invert();
  18867. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18868. }
  18869. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18870. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18871. }
  18872. return this;
  18873. };
  18874. /**
  18875. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18876. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18877. * The passed axis is also normalized.
  18878. * Returns the TransformNode.
  18879. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18880. */
  18881. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18882. axis.normalize();
  18883. if (!this.rotationQuaternion) {
  18884. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18885. this.rotation.copyFromFloats(0, 0, 0);
  18886. }
  18887. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18888. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18889. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18890. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18891. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18892. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18893. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18894. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18895. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18896. return this;
  18897. };
  18898. /**
  18899. * Translates the mesh along the axis vector for the passed distance in the given space.
  18900. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18901. * Returns the TransformNode.
  18902. */
  18903. TransformNode.prototype.translate = function (axis, distance, space) {
  18904. var displacementVector = axis.scale(distance);
  18905. if (!space || space === BABYLON.Space.LOCAL) {
  18906. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18907. this.setPositionWithLocalVector(tempV3);
  18908. }
  18909. else {
  18910. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18911. }
  18912. return this;
  18913. };
  18914. /**
  18915. * Adds a rotation step to the mesh current rotation.
  18916. * x, y, z are Euler angles expressed in radians.
  18917. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18918. * This means this rotation is made in the mesh local space only.
  18919. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18920. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18921. * ```javascript
  18922. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18923. * ```
  18924. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18925. * 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.
  18926. * Returns the TransformNode.
  18927. */
  18928. TransformNode.prototype.addRotation = function (x, y, z) {
  18929. var rotationQuaternion;
  18930. if (this.rotationQuaternion) {
  18931. rotationQuaternion = this.rotationQuaternion;
  18932. }
  18933. else {
  18934. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18935. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18936. }
  18937. var accumulation = BABYLON.Tmp.Quaternion[0];
  18938. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18939. rotationQuaternion.multiplyInPlace(accumulation);
  18940. if (!this.rotationQuaternion) {
  18941. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18942. }
  18943. return this;
  18944. };
  18945. /**
  18946. * Computes the mesh World matrix and returns it.
  18947. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18948. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18949. * If the parameter `force`is set to `true`, the actual computation is done.
  18950. * Returns the mesh World Matrix.
  18951. */
  18952. TransformNode.prototype.computeWorldMatrix = function (force) {
  18953. if (this._isWorldMatrixFrozen) {
  18954. return this._worldMatrix;
  18955. }
  18956. if (!force && this.isSynchronized(true)) {
  18957. this._currentRenderId = this.getScene().getRenderId();
  18958. return this._worldMatrix;
  18959. }
  18960. this._cache.position.copyFrom(this.position);
  18961. this._cache.scaling.copyFrom(this.scaling);
  18962. this._cache.pivotMatrixUpdated = false;
  18963. this._cache.billboardMode = this.billboardMode;
  18964. this._currentRenderId = this.getScene().getRenderId();
  18965. this._childRenderId = this.getScene().getRenderId();
  18966. this._isDirty = false;
  18967. // Scaling
  18968. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18969. // Rotation
  18970. //rotate, if quaternion is set and rotation was used
  18971. if (this.rotationQuaternion) {
  18972. var len = this.rotation.length();
  18973. if (len) {
  18974. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18975. this.rotation.copyFromFloats(0, 0, 0);
  18976. }
  18977. }
  18978. if (this.rotationQuaternion) {
  18979. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18980. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18981. }
  18982. else {
  18983. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18984. this._cache.rotation.copyFrom(this.rotation);
  18985. }
  18986. // Translation
  18987. var camera = this.getScene().activeCamera;
  18988. if (this.infiniteDistance && !this.parent && camera) {
  18989. var cameraWorldMatrix = camera.getWorldMatrix();
  18990. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18991. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18992. }
  18993. else {
  18994. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18995. }
  18996. // Composing transformations
  18997. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18998. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18999. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19000. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19001. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19002. // Need to decompose each rotation here
  19003. var currentPosition = BABYLON.Tmp.Vector3[3];
  19004. if (this.parent && this.parent.getWorldMatrix) {
  19005. if (this._transformToBoneReferal) {
  19006. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19007. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19008. }
  19009. else {
  19010. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19011. }
  19012. }
  19013. else {
  19014. currentPosition.copyFrom(this.position);
  19015. }
  19016. currentPosition.subtractInPlace(camera.globalPosition);
  19017. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19018. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19019. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19020. }
  19021. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19022. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19023. }
  19024. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19025. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19026. }
  19027. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19028. }
  19029. else {
  19030. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19031. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19032. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19033. }
  19034. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19035. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19036. }
  19037. // Post multiply inverse of pivotMatrix
  19038. if (this._postMultiplyPivotMatrix) {
  19039. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19040. }
  19041. // Local world
  19042. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19043. // Parent
  19044. if (this.parent && this.parent.getWorldMatrix) {
  19045. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19046. if (this._transformToBoneReferal) {
  19047. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19048. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19049. }
  19050. else {
  19051. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19052. }
  19053. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19054. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19055. this._worldMatrix.copyFrom(this._localWorld);
  19056. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19057. }
  19058. else {
  19059. if (this._transformToBoneReferal) {
  19060. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19061. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19062. }
  19063. else {
  19064. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19065. }
  19066. }
  19067. this._markSyncedWithParent();
  19068. }
  19069. else {
  19070. this._worldMatrix.copyFrom(this._localWorld);
  19071. }
  19072. // Normal matrix
  19073. if (!this.ignoreNonUniformScaling) {
  19074. if (this.scaling.isNonUniform) {
  19075. this._updateNonUniformScalingState(true);
  19076. }
  19077. else if (this.parent && this.parent._nonUniformScaling) {
  19078. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19079. }
  19080. else {
  19081. this._updateNonUniformScalingState(false);
  19082. }
  19083. }
  19084. else {
  19085. this._updateNonUniformScalingState(false);
  19086. }
  19087. this._afterComputeWorldMatrix();
  19088. // Absolute position
  19089. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19090. // Callbacks
  19091. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19092. if (!this._poseMatrix) {
  19093. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19094. }
  19095. // Cache the determinant
  19096. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19097. return this._worldMatrix;
  19098. };
  19099. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19100. };
  19101. /**
  19102. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19103. * @param func: callback function to add
  19104. *
  19105. * Returns the TransformNode.
  19106. */
  19107. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19108. this.onAfterWorldMatrixUpdateObservable.add(func);
  19109. return this;
  19110. };
  19111. /**
  19112. * Removes a registered callback function.
  19113. * Returns the TransformNode.
  19114. */
  19115. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19116. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19117. return this;
  19118. };
  19119. /**
  19120. * Clone the current transform node
  19121. * Returns the new transform node
  19122. * @param name Name of the new clone
  19123. * @param newParent New parent for the clone
  19124. * @param doNotCloneChildren Do not clone children hierarchy
  19125. */
  19126. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19127. var _this = this;
  19128. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19129. result.name = name;
  19130. result.id = name;
  19131. if (newParent) {
  19132. result.parent = newParent;
  19133. }
  19134. if (!doNotCloneChildren) {
  19135. // Children
  19136. var directDescendants = this.getDescendants(true);
  19137. for (var index = 0; index < directDescendants.length; index++) {
  19138. var child = directDescendants[index];
  19139. if (child.clone) {
  19140. child.clone(name + "." + child.name, result);
  19141. }
  19142. }
  19143. }
  19144. return result;
  19145. };
  19146. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19147. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19148. serializationObject.type = this.getClassName();
  19149. // Parent
  19150. if (this.parent) {
  19151. serializationObject.parentId = this.parent.id;
  19152. }
  19153. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19154. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19155. }
  19156. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19157. serializationObject.isEnabled = this.isEnabled();
  19158. // Parent
  19159. if (this.parent) {
  19160. serializationObject.parentId = this.parent.id;
  19161. }
  19162. return serializationObject;
  19163. };
  19164. // Statics
  19165. /**
  19166. * Returns a new TransformNode object parsed from the source provided.
  19167. * The parameter `parsedMesh` is the source.
  19168. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19169. */
  19170. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19171. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19172. if (BABYLON.Tags) {
  19173. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19174. }
  19175. if (parsedTransformNode.localMatrix) {
  19176. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19177. }
  19178. else if (parsedTransformNode.pivotMatrix) {
  19179. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19180. }
  19181. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19182. // Parent
  19183. if (parsedTransformNode.parentId) {
  19184. transformNode._waitingParentId = parsedTransformNode.parentId;
  19185. }
  19186. return transformNode;
  19187. };
  19188. /**
  19189. * Releases resources associated with this transform node.
  19190. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19191. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19192. */
  19193. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19194. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19195. // Animations
  19196. this.getScene().stopAnimation(this);
  19197. // Remove from scene
  19198. this.getScene().removeTransformNode(this);
  19199. this.onAfterWorldMatrixUpdateObservable.clear();
  19200. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19201. };
  19202. // Statics
  19203. TransformNode.BILLBOARDMODE_NONE = 0;
  19204. TransformNode.BILLBOARDMODE_X = 1;
  19205. TransformNode.BILLBOARDMODE_Y = 2;
  19206. TransformNode.BILLBOARDMODE_Z = 4;
  19207. TransformNode.BILLBOARDMODE_ALL = 7;
  19208. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19209. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19210. __decorate([
  19211. BABYLON.serializeAsVector3()
  19212. ], TransformNode.prototype, "_rotation", void 0);
  19213. __decorate([
  19214. BABYLON.serializeAsQuaternion()
  19215. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19216. __decorate([
  19217. BABYLON.serializeAsVector3()
  19218. ], TransformNode.prototype, "_scaling", void 0);
  19219. __decorate([
  19220. BABYLON.serialize()
  19221. ], TransformNode.prototype, "billboardMode", void 0);
  19222. __decorate([
  19223. BABYLON.serialize()
  19224. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19225. __decorate([
  19226. BABYLON.serialize()
  19227. ], TransformNode.prototype, "infiniteDistance", void 0);
  19228. __decorate([
  19229. BABYLON.serialize()
  19230. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19231. __decorate([
  19232. BABYLON.serializeAsVector3()
  19233. ], TransformNode.prototype, "position", void 0);
  19234. return TransformNode;
  19235. }(BABYLON.Node));
  19236. BABYLON.TransformNode = TransformNode;
  19237. })(BABYLON || (BABYLON = {}));
  19238. //# sourceMappingURL=babylon.transformNode.js.map
  19239. var BABYLON;
  19240. (function (BABYLON) {
  19241. /**
  19242. * Class used to store all common mesh properties
  19243. */
  19244. var AbstractMesh = /** @class */ (function (_super) {
  19245. __extends(AbstractMesh, _super);
  19246. // Constructor
  19247. /**
  19248. * Creates a new AbstractMesh
  19249. * @param name defines the name of the mesh
  19250. * @param scene defines the hosting scene
  19251. */
  19252. function AbstractMesh(name, scene) {
  19253. if (scene === void 0) { scene = null; }
  19254. var _this = _super.call(this, name, scene, false) || this;
  19255. _this._facetNb = 0; // facet number
  19256. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19257. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19258. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19259. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19260. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19261. _this._subDiv = {
  19262. max: 1,
  19263. X: 1,
  19264. Y: 1,
  19265. Z: 1
  19266. };
  19267. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19268. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19269. // Events
  19270. /**
  19271. * An event triggered when this mesh collides with another one
  19272. */
  19273. _this.onCollideObservable = new BABYLON.Observable();
  19274. /**
  19275. * An event triggered when the collision's position changes
  19276. */
  19277. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19278. /**
  19279. * An event triggered when material is changed
  19280. */
  19281. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19282. // Properties
  19283. /**
  19284. * Gets or sets the orientation for POV movement & rotation
  19285. */
  19286. _this.definedFacingForward = true;
  19287. /**
  19288. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19289. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19290. * * 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.
  19291. * @see http://doc.babylonjs.com/features/occlusionquery
  19292. */
  19293. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19294. /**
  19295. * 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:
  19296. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19297. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19298. * * 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.
  19299. * @see http://doc.babylonjs.com/features/occlusionquery
  19300. */
  19301. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19302. /**
  19303. * 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.
  19304. * The default value is -1 which means don't break the query and wait till the result
  19305. * @see http://doc.babylonjs.com/features/occlusionquery
  19306. */
  19307. _this.occlusionRetryCount = -1;
  19308. /** @hidden */
  19309. _this._occlusionInternalRetryCounter = 0;
  19310. /** @hidden */
  19311. _this._isOccluded = false;
  19312. /** @hidden */
  19313. _this._isOcclusionQueryInProgress = false;
  19314. _this._visibility = 1.0;
  19315. /** Gets or sets the alpha index used to sort transparent meshes
  19316. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19317. */
  19318. _this.alphaIndex = Number.MAX_VALUE;
  19319. /**
  19320. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19321. */
  19322. _this.isVisible = true;
  19323. /**
  19324. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19325. */
  19326. _this.isPickable = true;
  19327. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19328. _this.showSubMeshesBoundingBox = false;
  19329. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19330. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19331. */
  19332. _this.isBlocker = false;
  19333. /**
  19334. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19335. */
  19336. _this.enablePointerMoveEvents = false;
  19337. /**
  19338. * Specifies the rendering group id for this mesh (0 by default)
  19339. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19340. */
  19341. _this.renderingGroupId = 0;
  19342. _this._receiveShadows = false;
  19343. /**
  19344. * Gets or sets a boolean indicating if the outline must be rendered as well
  19345. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19346. */
  19347. _this.renderOutline = false;
  19348. /** Defines color to use when rendering outline */
  19349. _this.outlineColor = BABYLON.Color3.Red();
  19350. /** Define width to use when rendering outline */
  19351. _this.outlineWidth = 0.02;
  19352. /**
  19353. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19354. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19355. */
  19356. _this.renderOverlay = false;
  19357. /** Defines color to use when rendering overlay */
  19358. _this.overlayColor = BABYLON.Color3.Red();
  19359. /** Defines alpha to use when rendering overlay */
  19360. _this.overlayAlpha = 0.5;
  19361. _this._hasVertexAlpha = false;
  19362. _this._useVertexColors = true;
  19363. _this._computeBonesUsingShaders = true;
  19364. _this._numBoneInfluencers = 4;
  19365. _this._applyFog = true;
  19366. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19367. _this.useOctreeForRenderingSelection = true;
  19368. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19369. _this.useOctreeForPicking = true;
  19370. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19371. _this.useOctreeForCollisions = true;
  19372. _this._layerMask = 0x0FFFFFFF;
  19373. /**
  19374. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19375. */
  19376. _this.alwaysSelectAsActiveMesh = false;
  19377. /**
  19378. * Gets or sets the current action manager
  19379. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19380. */
  19381. _this.actionManager = null;
  19382. /**
  19383. * Gets or sets impostor used for physic simulation
  19384. * @see http://doc.babylonjs.com/features/physics_engine
  19385. */
  19386. _this.physicsImpostor = null;
  19387. // Collisions
  19388. _this._checkCollisions = false;
  19389. _this._collisionMask = -1;
  19390. _this._collisionGroup = -1;
  19391. /**
  19392. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19393. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19394. */
  19395. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19396. /**
  19397. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19398. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19399. */
  19400. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19401. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19402. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19403. // Edges
  19404. /**
  19405. * Defines edge width used when edgesRenderer is enabled
  19406. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19407. */
  19408. _this.edgesWidth = 1;
  19409. /**
  19410. * Defines edge color used when edgesRenderer is enabled
  19411. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19412. */
  19413. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19414. // Cache
  19415. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19416. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19417. /** @hidden */
  19418. _this._renderId = 0;
  19419. /** @hidden */
  19420. _this._intersectionsInProgress = new Array();
  19421. /** @hidden */
  19422. _this._unIndexed = false;
  19423. /** @hidden */
  19424. _this._lightSources = new Array();
  19425. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19426. if (collidedMesh === void 0) { collidedMesh = null; }
  19427. //TODO move this to the collision coordinator!
  19428. if (_this.getScene().workerCollisions)
  19429. newPosition.multiplyInPlace(_this._collider._radius);
  19430. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19431. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19432. _this.position.addInPlace(_this._diffPositionForCollisions);
  19433. }
  19434. if (collidedMesh) {
  19435. _this.onCollideObservable.notifyObservers(collidedMesh);
  19436. }
  19437. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19438. };
  19439. _this.getScene().addMesh(_this);
  19440. _this._resyncLightSources();
  19441. return _this;
  19442. }
  19443. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19444. /**
  19445. * No billboard
  19446. */
  19447. get: function () {
  19448. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19449. },
  19450. enumerable: true,
  19451. configurable: true
  19452. });
  19453. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19454. /** Billboard on X axis */
  19455. get: function () {
  19456. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19457. },
  19458. enumerable: true,
  19459. configurable: true
  19460. });
  19461. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19462. /** Billboard on Y axis */
  19463. get: function () {
  19464. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19465. },
  19466. enumerable: true,
  19467. configurable: true
  19468. });
  19469. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19470. /** Billboard on Z axis */
  19471. get: function () {
  19472. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19473. },
  19474. enumerable: true,
  19475. configurable: true
  19476. });
  19477. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19478. /** Billboard on all axes */
  19479. get: function () {
  19480. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19481. },
  19482. enumerable: true,
  19483. configurable: true
  19484. });
  19485. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19486. /**
  19487. * Gets the number of facets in the mesh
  19488. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19489. */
  19490. get: function () {
  19491. return this._facetNb;
  19492. },
  19493. enumerable: true,
  19494. configurable: true
  19495. });
  19496. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19497. /**
  19498. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19499. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19500. */
  19501. get: function () {
  19502. return this._partitioningSubdivisions;
  19503. },
  19504. set: function (nb) {
  19505. this._partitioningSubdivisions = nb;
  19506. },
  19507. enumerable: true,
  19508. configurable: true
  19509. });
  19510. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19511. /**
  19512. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19513. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19514. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19515. */
  19516. get: function () {
  19517. return this._partitioningBBoxRatio;
  19518. },
  19519. set: function (ratio) {
  19520. this._partitioningBBoxRatio = ratio;
  19521. },
  19522. enumerable: true,
  19523. configurable: true
  19524. });
  19525. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19526. /**
  19527. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19528. * Works only for updatable meshes.
  19529. * Doesn't work with multi-materials
  19530. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19531. */
  19532. get: function () {
  19533. return this._facetDepthSort;
  19534. },
  19535. set: function (sort) {
  19536. this._facetDepthSort = sort;
  19537. },
  19538. enumerable: true,
  19539. configurable: true
  19540. });
  19541. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19542. /**
  19543. * The location (Vector3) where the facet depth sort must be computed from.
  19544. * By default, the active camera position.
  19545. * Used only when facet depth sort is enabled
  19546. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19547. */
  19548. get: function () {
  19549. return this._facetDepthSortFrom;
  19550. },
  19551. set: function (location) {
  19552. this._facetDepthSortFrom = location;
  19553. },
  19554. enumerable: true,
  19555. configurable: true
  19556. });
  19557. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19558. /**
  19559. * gets a boolean indicating if facetData is enabled
  19560. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19561. */
  19562. get: function () {
  19563. return this._facetDataEnabled;
  19564. },
  19565. enumerable: true,
  19566. configurable: true
  19567. });
  19568. /** @hidden */
  19569. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19570. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19571. return false;
  19572. }
  19573. this._markSubMeshesAsMiscDirty();
  19574. return true;
  19575. };
  19576. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19577. /** Set a function to call when this mesh collides with another one */
  19578. set: function (callback) {
  19579. if (this._onCollideObserver) {
  19580. this.onCollideObservable.remove(this._onCollideObserver);
  19581. }
  19582. this._onCollideObserver = this.onCollideObservable.add(callback);
  19583. },
  19584. enumerable: true,
  19585. configurable: true
  19586. });
  19587. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19588. /** Set a function to call when the collision's position changes */
  19589. set: function (callback) {
  19590. if (this._onCollisionPositionChangeObserver) {
  19591. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19592. }
  19593. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19594. },
  19595. enumerable: true,
  19596. configurable: true
  19597. });
  19598. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19599. /**
  19600. * 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
  19601. * @see http://doc.babylonjs.com/features/occlusionquery
  19602. */
  19603. get: function () {
  19604. return this._isOccluded;
  19605. },
  19606. set: function (value) {
  19607. this._isOccluded = value;
  19608. },
  19609. enumerable: true,
  19610. configurable: true
  19611. });
  19612. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19613. /**
  19614. * Flag to check the progress status of the query
  19615. * @see http://doc.babylonjs.com/features/occlusionquery
  19616. */
  19617. get: function () {
  19618. return this._isOcclusionQueryInProgress;
  19619. },
  19620. enumerable: true,
  19621. configurable: true
  19622. });
  19623. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19624. /**
  19625. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19626. */
  19627. get: function () {
  19628. return this._visibility;
  19629. },
  19630. /**
  19631. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19632. */
  19633. set: function (value) {
  19634. if (this._visibility === value) {
  19635. return;
  19636. }
  19637. this._visibility = value;
  19638. this._markSubMeshesAsMiscDirty();
  19639. },
  19640. enumerable: true,
  19641. configurable: true
  19642. });
  19643. Object.defineProperty(AbstractMesh.prototype, "material", {
  19644. /** Gets or sets current material */
  19645. get: function () {
  19646. return this._material;
  19647. },
  19648. set: function (value) {
  19649. if (this._material === value) {
  19650. return;
  19651. }
  19652. this._material = value;
  19653. if (this.onMaterialChangedObservable.hasObservers) {
  19654. this.onMaterialChangedObservable.notifyObservers(this);
  19655. }
  19656. if (!this.subMeshes) {
  19657. return;
  19658. }
  19659. this._unBindEffect();
  19660. },
  19661. enumerable: true,
  19662. configurable: true
  19663. });
  19664. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19665. /**
  19666. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19667. * @see http://doc.babylonjs.com/babylon101/shadows
  19668. */
  19669. get: function () {
  19670. return this._receiveShadows;
  19671. },
  19672. set: function (value) {
  19673. if (this._receiveShadows === value) {
  19674. return;
  19675. }
  19676. this._receiveShadows = value;
  19677. this._markSubMeshesAsLightDirty();
  19678. },
  19679. enumerable: true,
  19680. configurable: true
  19681. });
  19682. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19683. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19684. get: function () {
  19685. return this._hasVertexAlpha;
  19686. },
  19687. set: function (value) {
  19688. if (this._hasVertexAlpha === value) {
  19689. return;
  19690. }
  19691. this._hasVertexAlpha = value;
  19692. this._markSubMeshesAsAttributesDirty();
  19693. this._markSubMeshesAsMiscDirty();
  19694. },
  19695. enumerable: true,
  19696. configurable: true
  19697. });
  19698. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19699. /** 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) */
  19700. get: function () {
  19701. return this._useVertexColors;
  19702. },
  19703. set: function (value) {
  19704. if (this._useVertexColors === value) {
  19705. return;
  19706. }
  19707. this._useVertexColors = value;
  19708. this._markSubMeshesAsAttributesDirty();
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19714. /**
  19715. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19716. */
  19717. get: function () {
  19718. return this._computeBonesUsingShaders;
  19719. },
  19720. set: function (value) {
  19721. if (this._computeBonesUsingShaders === value) {
  19722. return;
  19723. }
  19724. this._computeBonesUsingShaders = value;
  19725. this._markSubMeshesAsAttributesDirty();
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19731. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19732. get: function () {
  19733. return this._numBoneInfluencers;
  19734. },
  19735. set: function (value) {
  19736. if (this._numBoneInfluencers === value) {
  19737. return;
  19738. }
  19739. this._numBoneInfluencers = value;
  19740. this._markSubMeshesAsAttributesDirty();
  19741. },
  19742. enumerable: true,
  19743. configurable: true
  19744. });
  19745. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19746. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19747. get: function () {
  19748. return this._applyFog;
  19749. },
  19750. set: function (value) {
  19751. if (this._applyFog === value) {
  19752. return;
  19753. }
  19754. this._applyFog = value;
  19755. this._markSubMeshesAsMiscDirty();
  19756. },
  19757. enumerable: true,
  19758. configurable: true
  19759. });
  19760. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19761. /**
  19762. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19763. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19764. */
  19765. get: function () {
  19766. return this._layerMask;
  19767. },
  19768. set: function (value) {
  19769. if (value === this._layerMask) {
  19770. return;
  19771. }
  19772. this._layerMask = value;
  19773. this._resyncLightSources();
  19774. },
  19775. enumerable: true,
  19776. configurable: true
  19777. });
  19778. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19779. /**
  19780. * Gets or sets a collision mask used to mask collisions (default is -1).
  19781. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19782. */
  19783. get: function () {
  19784. return this._collisionMask;
  19785. },
  19786. set: function (mask) {
  19787. this._collisionMask = !isNaN(mask) ? mask : -1;
  19788. },
  19789. enumerable: true,
  19790. configurable: true
  19791. });
  19792. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19793. /**
  19794. * Gets or sets the current collision group mask (-1 by default).
  19795. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19796. */
  19797. get: function () {
  19798. return this._collisionGroup;
  19799. },
  19800. set: function (mask) {
  19801. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19802. },
  19803. enumerable: true,
  19804. configurable: true
  19805. });
  19806. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19807. /** @hidden */
  19808. get: function () {
  19809. return null;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19815. get: function () {
  19816. return this._skeleton;
  19817. },
  19818. /**
  19819. * Gets or sets a skeleton to apply skining transformations
  19820. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19821. */
  19822. set: function (value) {
  19823. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19824. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19825. }
  19826. if (value && value.needInitialSkinMatrix) {
  19827. value._registerMeshWithPoseMatrix(this);
  19828. }
  19829. this._skeleton = value;
  19830. if (!this._skeleton) {
  19831. this._bonesTransformMatrices = null;
  19832. }
  19833. this._markSubMeshesAsAttributesDirty();
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. /**
  19839. * Returns the string "AbstractMesh"
  19840. * @returns "AbstractMesh"
  19841. */
  19842. AbstractMesh.prototype.getClassName = function () {
  19843. return "AbstractMesh";
  19844. };
  19845. /**
  19846. * Gets a string representation of the current mesh
  19847. * @param fullDetails defines a boolean indicating if full details must be included
  19848. * @returns a string representation of the current mesh
  19849. */
  19850. AbstractMesh.prototype.toString = function (fullDetails) {
  19851. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19852. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19853. if (this._skeleton) {
  19854. ret += ", skeleton: " + this._skeleton.name;
  19855. }
  19856. if (fullDetails) {
  19857. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19858. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19859. }
  19860. return ret;
  19861. };
  19862. /** @hidden */
  19863. AbstractMesh.prototype._rebuild = function () {
  19864. if (this._occlusionQuery) {
  19865. this._occlusionQuery = null;
  19866. }
  19867. if (this._edgesRenderer) {
  19868. this._edgesRenderer._rebuild();
  19869. }
  19870. if (!this.subMeshes) {
  19871. return;
  19872. }
  19873. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19874. var subMesh = _a[_i];
  19875. subMesh._rebuild();
  19876. }
  19877. };
  19878. /** @hidden */
  19879. AbstractMesh.prototype._resyncLightSources = function () {
  19880. this._lightSources.length = 0;
  19881. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19882. var light = _a[_i];
  19883. if (!light.isEnabled()) {
  19884. continue;
  19885. }
  19886. if (light.canAffectMesh(this)) {
  19887. this._lightSources.push(light);
  19888. }
  19889. }
  19890. this._markSubMeshesAsLightDirty();
  19891. };
  19892. /** @hidden */
  19893. AbstractMesh.prototype._resyncLighSource = function (light) {
  19894. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19895. var index = this._lightSources.indexOf(light);
  19896. if (index === -1) {
  19897. if (!isIn) {
  19898. return;
  19899. }
  19900. this._lightSources.push(light);
  19901. }
  19902. else {
  19903. if (isIn) {
  19904. return;
  19905. }
  19906. this._lightSources.splice(index, 1);
  19907. }
  19908. this._markSubMeshesAsLightDirty();
  19909. };
  19910. /** @hidden */
  19911. AbstractMesh.prototype._unBindEffect = function () {
  19912. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19913. var subMesh = _a[_i];
  19914. subMesh.setEffect(null);
  19915. }
  19916. };
  19917. /** @hidden */
  19918. AbstractMesh.prototype._removeLightSource = function (light) {
  19919. var index = this._lightSources.indexOf(light);
  19920. if (index === -1) {
  19921. return;
  19922. }
  19923. this._lightSources.splice(index, 1);
  19924. this._markSubMeshesAsLightDirty();
  19925. };
  19926. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19927. if (!this.subMeshes) {
  19928. return;
  19929. }
  19930. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19931. var subMesh = _a[_i];
  19932. if (subMesh._materialDefines) {
  19933. func(subMesh._materialDefines);
  19934. }
  19935. }
  19936. };
  19937. /** @hidden */
  19938. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19939. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19940. };
  19941. /** @hidden */
  19942. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19943. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19944. };
  19945. /** @hidden */
  19946. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19947. if (!this.subMeshes) {
  19948. return;
  19949. }
  19950. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19951. var subMesh = _a[_i];
  19952. var material = subMesh.getMaterial();
  19953. if (material) {
  19954. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19955. }
  19956. }
  19957. };
  19958. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19959. /**
  19960. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19961. */
  19962. get: function () {
  19963. return this._scaling;
  19964. },
  19965. set: function (newScaling) {
  19966. this._scaling = newScaling;
  19967. if (this.physicsImpostor) {
  19968. this.physicsImpostor.forceUpdate();
  19969. }
  19970. },
  19971. enumerable: true,
  19972. configurable: true
  19973. });
  19974. // Methods
  19975. /**
  19976. * Disables the mesh edge rendering mode
  19977. * @returns the currentAbstractMesh
  19978. */
  19979. AbstractMesh.prototype.disableEdgesRendering = function () {
  19980. if (this._edgesRenderer) {
  19981. this._edgesRenderer.dispose();
  19982. this._edgesRenderer = null;
  19983. }
  19984. return this;
  19985. };
  19986. /**
  19987. * Enables the edge rendering mode on the mesh.
  19988. * This mode makes the mesh edges visible
  19989. * @param epsilon defines the maximal distance between two angles to detect a face
  19990. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19991. * @returns the currentAbstractMesh
  19992. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19993. */
  19994. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19995. if (epsilon === void 0) { epsilon = 0.95; }
  19996. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19997. this.disableEdgesRendering();
  19998. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19999. return this;
  20000. };
  20001. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20002. /**
  20003. * Gets the edgesRenderer associated with the mesh
  20004. */
  20005. get: function () {
  20006. return this._edgesRenderer;
  20007. },
  20008. enumerable: true,
  20009. configurable: true
  20010. });
  20011. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20012. /**
  20013. * Returns true if the mesh is blocked. Implemented by child classes
  20014. */
  20015. get: function () {
  20016. return false;
  20017. },
  20018. enumerable: true,
  20019. configurable: true
  20020. });
  20021. /**
  20022. * Returns the mesh itself by default. Implemented by child classes
  20023. * @param camera defines the camera to use to pick the right LOD level
  20024. * @returns the currentAbstractMesh
  20025. */
  20026. AbstractMesh.prototype.getLOD = function (camera) {
  20027. return this;
  20028. };
  20029. /**
  20030. * Returns 0 by default. Implemented by child classes
  20031. * @returns an integer
  20032. */
  20033. AbstractMesh.prototype.getTotalVertices = function () {
  20034. return 0;
  20035. };
  20036. /**
  20037. * Returns null by default. Implemented by child classes
  20038. * @returns null
  20039. */
  20040. AbstractMesh.prototype.getIndices = function () {
  20041. return null;
  20042. };
  20043. /**
  20044. * Returns the array of the requested vertex data kind. Implemented by child classes
  20045. * @param kind defines the vertex data kind to use
  20046. * @returns null
  20047. */
  20048. AbstractMesh.prototype.getVerticesData = function (kind) {
  20049. return null;
  20050. };
  20051. /**
  20052. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20053. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20054. * Note that a new underlying VertexBuffer object is created each call.
  20055. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20056. * @param kind defines vertex data kind:
  20057. * * BABYLON.VertexBuffer.PositionKind
  20058. * * BABYLON.VertexBuffer.UVKind
  20059. * * BABYLON.VertexBuffer.UV2Kind
  20060. * * BABYLON.VertexBuffer.UV3Kind
  20061. * * BABYLON.VertexBuffer.UV4Kind
  20062. * * BABYLON.VertexBuffer.UV5Kind
  20063. * * BABYLON.VertexBuffer.UV6Kind
  20064. * * BABYLON.VertexBuffer.ColorKind
  20065. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20066. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20067. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20068. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20069. * @param data defines the data source
  20070. * @param updatable defines if the data must be flagged as updatable (or static)
  20071. * @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
  20072. * @returns the current mesh
  20073. */
  20074. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20075. return this;
  20076. };
  20077. /**
  20078. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20079. * If the mesh has no geometry, it is simply returned as it is.
  20080. * @param kind defines vertex data kind:
  20081. * * BABYLON.VertexBuffer.PositionKind
  20082. * * BABYLON.VertexBuffer.UVKind
  20083. * * BABYLON.VertexBuffer.UV2Kind
  20084. * * BABYLON.VertexBuffer.UV3Kind
  20085. * * BABYLON.VertexBuffer.UV4Kind
  20086. * * BABYLON.VertexBuffer.UV5Kind
  20087. * * BABYLON.VertexBuffer.UV6Kind
  20088. * * BABYLON.VertexBuffer.ColorKind
  20089. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20090. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20091. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20092. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20093. * @param data defines the data source
  20094. * @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
  20095. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20096. * @returns the current mesh
  20097. */
  20098. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20099. return this;
  20100. };
  20101. /**
  20102. * Sets the mesh indices,
  20103. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20104. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20105. * @param totalVertices Defines the total number of vertices
  20106. * @returns the current mesh
  20107. */
  20108. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20109. return this;
  20110. };
  20111. /**
  20112. * Gets a boolean indicating if specific vertex data is present
  20113. * @param kind defines the vertex data kind to use
  20114. * @returns true is data kind is present
  20115. */
  20116. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20117. return false;
  20118. };
  20119. /**
  20120. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20121. * @returns a BoundingInfo
  20122. */
  20123. AbstractMesh.prototype.getBoundingInfo = function () {
  20124. if (this._masterMesh) {
  20125. return this._masterMesh.getBoundingInfo();
  20126. }
  20127. if (!this._boundingInfo) {
  20128. // this._boundingInfo is being created here
  20129. this._updateBoundingInfo();
  20130. }
  20131. // cannot be null.
  20132. return this._boundingInfo;
  20133. };
  20134. /**
  20135. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20136. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20137. * @returns the current mesh
  20138. */
  20139. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20140. if (includeDescendants === void 0) { includeDescendants = true; }
  20141. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20142. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20143. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20144. if (maxDimension === 0) {
  20145. return this;
  20146. }
  20147. var scale = 1 / maxDimension;
  20148. this.scaling.scaleInPlace(scale);
  20149. return this;
  20150. };
  20151. /**
  20152. * Overwrite the current bounding info
  20153. * @param boundingInfo defines the new bounding info
  20154. * @returns the current mesh
  20155. */
  20156. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20157. this._boundingInfo = boundingInfo;
  20158. return this;
  20159. };
  20160. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20161. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20162. get: function () {
  20163. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20164. },
  20165. enumerable: true,
  20166. configurable: true
  20167. });
  20168. /** @hidden */
  20169. AbstractMesh.prototype._preActivate = function () {
  20170. };
  20171. /** @hidden */
  20172. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20173. };
  20174. /** @hidden */
  20175. AbstractMesh.prototype._activate = function (renderId) {
  20176. this._renderId = renderId;
  20177. };
  20178. /**
  20179. * Gets the current world matrix
  20180. * @returns a Matrix
  20181. */
  20182. AbstractMesh.prototype.getWorldMatrix = function () {
  20183. if (this._masterMesh) {
  20184. return this._masterMesh.getWorldMatrix();
  20185. }
  20186. return _super.prototype.getWorldMatrix.call(this);
  20187. };
  20188. /** @hidden */
  20189. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20190. if (this._masterMesh) {
  20191. return this._masterMesh._getWorldMatrixDeterminant();
  20192. }
  20193. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20194. };
  20195. // ================================== Point of View Movement =================================
  20196. /**
  20197. * Perform relative position change from the point of view of behind the front of the mesh.
  20198. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20199. * Supports definition of mesh facing forward or backward
  20200. * @param amountRight defines the distance on the right axis
  20201. * @param amountUp defines the distance on the up axis
  20202. * @param amountForward defines the distance on the forward axis
  20203. * @returns the current mesh
  20204. */
  20205. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20206. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20207. return this;
  20208. };
  20209. /**
  20210. * Calculate relative position change from the point of view of behind the front of the mesh.
  20211. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20212. * Supports definition of mesh facing forward or backward
  20213. * @param amountRight defines the distance on the right axis
  20214. * @param amountUp defines the distance on the up axis
  20215. * @param amountForward defines the distance on the forward axis
  20216. * @returns the new displacement vector
  20217. */
  20218. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20219. var rotMatrix = new BABYLON.Matrix();
  20220. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20221. rotQuaternion.toRotationMatrix(rotMatrix);
  20222. var translationDelta = BABYLON.Vector3.Zero();
  20223. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20224. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20225. return translationDelta;
  20226. };
  20227. // ================================== Point of View Rotation =================================
  20228. /**
  20229. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20230. * Supports definition of mesh facing forward or backward
  20231. * @param flipBack defines the flip
  20232. * @param twirlClockwise defines the twirl
  20233. * @param tiltRight defines the tilt
  20234. * @returns the current mesh
  20235. */
  20236. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20237. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20238. return this;
  20239. };
  20240. /**
  20241. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20242. * Supports definition of mesh facing forward or backward.
  20243. * @param flipBack defines the flip
  20244. * @param twirlClockwise defines the twirl
  20245. * @param tiltRight defines the tilt
  20246. * @returns the new rotation vector
  20247. */
  20248. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20249. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20250. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20251. };
  20252. /**
  20253. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20254. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20255. * @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
  20256. * @returns the new bounding vectors
  20257. */
  20258. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20259. if (includeDescendants === void 0) { includeDescendants = true; }
  20260. if (predicate === void 0) { predicate = null; }
  20261. // Ensures that all world matrix will be recomputed.
  20262. this.getScene().incrementRenderId();
  20263. this.computeWorldMatrix(true);
  20264. var min;
  20265. var max;
  20266. var boundingInfo = this.getBoundingInfo();
  20267. if (!this.subMeshes) {
  20268. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20269. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20270. }
  20271. else {
  20272. min = boundingInfo.boundingBox.minimumWorld;
  20273. max = boundingInfo.boundingBox.maximumWorld;
  20274. }
  20275. if (includeDescendants) {
  20276. var descendants = this.getDescendants(false);
  20277. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20278. var descendant = descendants_1[_i];
  20279. var childMesh = descendant;
  20280. childMesh.computeWorldMatrix(true);
  20281. // Filters meshes based on custom predicate function.
  20282. if (predicate && !predicate(childMesh)) {
  20283. continue;
  20284. }
  20285. //make sure we have the needed params to get mix and max
  20286. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20287. continue;
  20288. }
  20289. var childBoundingInfo = childMesh.getBoundingInfo();
  20290. var boundingBox = childBoundingInfo.boundingBox;
  20291. var minBox = boundingBox.minimumWorld;
  20292. var maxBox = boundingBox.maximumWorld;
  20293. BABYLON.Tools.CheckExtends(minBox, min, max);
  20294. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20295. }
  20296. }
  20297. return {
  20298. min: min,
  20299. max: max
  20300. };
  20301. };
  20302. /** @hidden */
  20303. AbstractMesh.prototype._updateBoundingInfo = function () {
  20304. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20305. this._boundingInfo.update(this.worldMatrixFromCache);
  20306. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20307. return this;
  20308. };
  20309. /** @hidden */
  20310. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20311. if (!this.subMeshes) {
  20312. return this;
  20313. }
  20314. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20315. var subMesh = this.subMeshes[subIndex];
  20316. if (!subMesh.IsGlobal) {
  20317. subMesh.updateBoundingInfo(matrix);
  20318. }
  20319. }
  20320. return this;
  20321. };
  20322. /** @hidden */
  20323. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20324. // Bounding info
  20325. this._updateBoundingInfo();
  20326. };
  20327. /**
  20328. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20329. * A mesh is in the frustum if its bounding box intersects the frustum
  20330. * @param frustumPlanes defines the frustum to test
  20331. * @returns true if the mesh is in the frustum planes
  20332. */
  20333. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20334. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20335. };
  20336. /**
  20337. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20338. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20339. * @param frustumPlanes defines the frustum to test
  20340. * @returns true if the mesh is completely in the frustum planes
  20341. */
  20342. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20343. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20344. };
  20345. /**
  20346. * True if the mesh intersects another mesh or a SolidParticle object
  20347. * @param mesh defines a target mesh or SolidParticle to test
  20348. * @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)
  20349. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20350. * @returns true if there is an intersection
  20351. */
  20352. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20353. if (precise === void 0) { precise = false; }
  20354. if (!this._boundingInfo || !mesh._boundingInfo) {
  20355. return false;
  20356. }
  20357. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20358. return true;
  20359. }
  20360. if (includeDescendants) {
  20361. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20362. var child = _a[_i];
  20363. if (child.intersectsMesh(mesh, precise, true)) {
  20364. return true;
  20365. }
  20366. }
  20367. }
  20368. return false;
  20369. };
  20370. /**
  20371. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20372. * @param point defines the point to test
  20373. * @returns true if there is an intersection
  20374. */
  20375. AbstractMesh.prototype.intersectsPoint = function (point) {
  20376. if (!this._boundingInfo) {
  20377. return false;
  20378. }
  20379. return this._boundingInfo.intersectsPoint(point);
  20380. };
  20381. /**
  20382. * Gets the current physics impostor
  20383. * @see http://doc.babylonjs.com/features/physics_engine
  20384. * @returns a physics impostor or null
  20385. */
  20386. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20387. return this.physicsImpostor;
  20388. };
  20389. /**
  20390. * Gets the position of the current mesh in camera space
  20391. * @param camera defines the camera to use
  20392. * @returns a position
  20393. */
  20394. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20395. if (camera === void 0) { camera = null; }
  20396. if (!camera) {
  20397. camera = this.getScene().activeCamera;
  20398. }
  20399. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20400. };
  20401. /**
  20402. * Returns the distance from the mesh to the active camera
  20403. * @param camera defines the camera to use
  20404. * @returns the distance
  20405. */
  20406. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20407. if (camera === void 0) { camera = null; }
  20408. if (!camera) {
  20409. camera = this.getScene().activeCamera;
  20410. }
  20411. return this.absolutePosition.subtract(camera.position).length();
  20412. };
  20413. /**
  20414. * Apply a physic impulse to the mesh
  20415. * @param force defines the force to apply
  20416. * @param contactPoint defines where to apply the force
  20417. * @returns the current mesh
  20418. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20419. */
  20420. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20421. if (!this.physicsImpostor) {
  20422. return this;
  20423. }
  20424. this.physicsImpostor.applyImpulse(force, contactPoint);
  20425. return this;
  20426. };
  20427. /**
  20428. * Creates a physic joint between two meshes
  20429. * @param otherMesh defines the other mesh to use
  20430. * @param pivot1 defines the pivot to use on this mesh
  20431. * @param pivot2 defines the pivot to use on the other mesh
  20432. * @param options defines additional options (can be plugin dependent)
  20433. * @returns the current mesh
  20434. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20435. */
  20436. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20437. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20438. return this;
  20439. }
  20440. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20441. mainPivot: pivot1,
  20442. connectedPivot: pivot2,
  20443. nativeParams: options
  20444. });
  20445. return this;
  20446. };
  20447. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20448. // Collisions
  20449. /**
  20450. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20451. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20452. */
  20453. get: function () {
  20454. return this._checkCollisions;
  20455. },
  20456. set: function (collisionEnabled) {
  20457. this._checkCollisions = collisionEnabled;
  20458. if (this.getScene().workerCollisions) {
  20459. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20460. }
  20461. },
  20462. enumerable: true,
  20463. configurable: true
  20464. });
  20465. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20466. /**
  20467. * Gets Collider object used to compute collisions (not physics)
  20468. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20469. */
  20470. get: function () {
  20471. return this._collider;
  20472. },
  20473. enumerable: true,
  20474. configurable: true
  20475. });
  20476. /**
  20477. * Move the mesh using collision engine
  20478. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20479. * @param displacement defines the requested displacement vector
  20480. * @returns the current mesh
  20481. */
  20482. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20483. var globalPosition = this.getAbsolutePosition();
  20484. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20485. if (!this._collider) {
  20486. this._collider = new BABYLON.Collider();
  20487. }
  20488. this._collider._radius = this.ellipsoid;
  20489. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20490. return this;
  20491. };
  20492. // Submeshes octree
  20493. /**
  20494. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20495. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20496. * @param maxCapacity defines the maximum size of each block (64 by default)
  20497. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20498. * @returns the new octree
  20499. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20500. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20501. */
  20502. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20503. if (maxCapacity === void 0) { maxCapacity = 64; }
  20504. if (maxDepth === void 0) { maxDepth = 2; }
  20505. if (!this._submeshesOctree) {
  20506. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20507. }
  20508. this.computeWorldMatrix(true);
  20509. var boundingInfo = this.getBoundingInfo();
  20510. // Update octree
  20511. var bbox = boundingInfo.boundingBox;
  20512. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20513. return this._submeshesOctree;
  20514. };
  20515. // Collisions
  20516. /** @hidden */
  20517. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20518. this._generatePointsArray();
  20519. if (!this._positions) {
  20520. return this;
  20521. }
  20522. // Transformation
  20523. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20524. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20525. subMesh._lastColliderWorldVertices = [];
  20526. subMesh._trianglePlanes = [];
  20527. var start = subMesh.verticesStart;
  20528. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20529. for (var i = start; i < end; i++) {
  20530. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20531. }
  20532. }
  20533. // Collide
  20534. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20535. if (collider.collisionFound) {
  20536. collider.collidedMesh = this;
  20537. }
  20538. return this;
  20539. };
  20540. /** @hidden */
  20541. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20542. var subMeshes;
  20543. var len;
  20544. // Octrees
  20545. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20546. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20547. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20548. len = intersections.length;
  20549. subMeshes = intersections.data;
  20550. }
  20551. else {
  20552. subMeshes = this.subMeshes;
  20553. len = subMeshes.length;
  20554. }
  20555. for (var index = 0; index < len; index++) {
  20556. var subMesh = subMeshes[index];
  20557. // Bounding test
  20558. if (len > 1 && !subMesh._checkCollision(collider))
  20559. continue;
  20560. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20561. }
  20562. return this;
  20563. };
  20564. /** @hidden */
  20565. AbstractMesh.prototype._checkCollision = function (collider) {
  20566. // Bounding box test
  20567. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20568. return this;
  20569. // Transformation matrix
  20570. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20571. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20572. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20573. return this;
  20574. };
  20575. // Picking
  20576. /** @hidden */
  20577. AbstractMesh.prototype._generatePointsArray = function () {
  20578. return false;
  20579. };
  20580. /**
  20581. * Checks if the passed Ray intersects with the mesh
  20582. * @param ray defines the ray to use
  20583. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20584. * @returns the picking info
  20585. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20586. */
  20587. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20588. var pickingInfo = new BABYLON.PickingInfo();
  20589. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20590. return pickingInfo;
  20591. }
  20592. if (!this._generatePointsArray()) {
  20593. return pickingInfo;
  20594. }
  20595. var intersectInfo = null;
  20596. // Octrees
  20597. var subMeshes;
  20598. var len;
  20599. if (this._submeshesOctree && this.useOctreeForPicking) {
  20600. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20601. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20602. len = intersections.length;
  20603. subMeshes = intersections.data;
  20604. }
  20605. else {
  20606. subMeshes = this.subMeshes;
  20607. len = subMeshes.length;
  20608. }
  20609. for (var index = 0; index < len; index++) {
  20610. var subMesh = subMeshes[index];
  20611. // Bounding test
  20612. if (len > 1 && !subMesh.canIntersects(ray))
  20613. continue;
  20614. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20615. if (currentIntersectInfo) {
  20616. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20617. intersectInfo = currentIntersectInfo;
  20618. intersectInfo.subMeshId = index;
  20619. if (fastCheck) {
  20620. break;
  20621. }
  20622. }
  20623. }
  20624. }
  20625. if (intersectInfo) {
  20626. // Get picked point
  20627. var world = this.getWorldMatrix();
  20628. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20629. var direction = ray.direction.clone();
  20630. direction = direction.scale(intersectInfo.distance);
  20631. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20632. var pickedPoint = worldOrigin.add(worldDirection);
  20633. // Return result
  20634. pickingInfo.hit = true;
  20635. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20636. pickingInfo.pickedPoint = pickedPoint;
  20637. pickingInfo.pickedMesh = this;
  20638. pickingInfo.bu = intersectInfo.bu || 0;
  20639. pickingInfo.bv = intersectInfo.bv || 0;
  20640. pickingInfo.faceId = intersectInfo.faceId;
  20641. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20642. return pickingInfo;
  20643. }
  20644. return pickingInfo;
  20645. };
  20646. /**
  20647. * Clones the current mesh
  20648. * @param name defines the mesh name
  20649. * @param newParent defines the new mesh parent
  20650. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20651. * @returns the new mesh
  20652. */
  20653. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20654. return null;
  20655. };
  20656. /**
  20657. * Disposes all the submeshes of the current meshnp
  20658. * @returns the current mesh
  20659. */
  20660. AbstractMesh.prototype.releaseSubMeshes = function () {
  20661. if (this.subMeshes) {
  20662. while (this.subMeshes.length) {
  20663. this.subMeshes[0].dispose();
  20664. }
  20665. }
  20666. else {
  20667. this.subMeshes = new Array();
  20668. }
  20669. return this;
  20670. };
  20671. /**
  20672. * Releases resources associated with this abstract mesh.
  20673. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20674. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20675. */
  20676. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20677. var _this = this;
  20678. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20679. var index;
  20680. // Smart Array Retainers.
  20681. this.getScene().freeActiveMeshes();
  20682. this.getScene().freeRenderingGroups();
  20683. // Action manager
  20684. if (this.actionManager !== undefined && this.actionManager !== null) {
  20685. this.actionManager.dispose();
  20686. this.actionManager = null;
  20687. }
  20688. // Skeleton
  20689. this._skeleton = null;
  20690. // Physics
  20691. if (this.physicsImpostor) {
  20692. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20693. }
  20694. // Intersections in progress
  20695. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20696. var other = this._intersectionsInProgress[index];
  20697. var pos = other._intersectionsInProgress.indexOf(this);
  20698. other._intersectionsInProgress.splice(pos, 1);
  20699. }
  20700. this._intersectionsInProgress = [];
  20701. // Lights
  20702. var lights = this.getScene().lights;
  20703. lights.forEach(function (light) {
  20704. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20705. if (meshIndex !== -1) {
  20706. light.includedOnlyMeshes.splice(meshIndex, 1);
  20707. }
  20708. meshIndex = light.excludedMeshes.indexOf(_this);
  20709. if (meshIndex !== -1) {
  20710. light.excludedMeshes.splice(meshIndex, 1);
  20711. }
  20712. // Shadow generators
  20713. var generator = light.getShadowGenerator();
  20714. if (generator) {
  20715. var shadowMap = generator.getShadowMap();
  20716. if (shadowMap && shadowMap.renderList) {
  20717. meshIndex = shadowMap.renderList.indexOf(_this);
  20718. if (meshIndex !== -1) {
  20719. shadowMap.renderList.splice(meshIndex, 1);
  20720. }
  20721. }
  20722. }
  20723. });
  20724. // Edges
  20725. if (this._edgesRenderer) {
  20726. this._edgesRenderer.dispose();
  20727. this._edgesRenderer = null;
  20728. }
  20729. // SubMeshes
  20730. if (this.getClassName() !== "InstancedMesh") {
  20731. this.releaseSubMeshes();
  20732. }
  20733. // Octree
  20734. var sceneOctree = this.getScene().selectionOctree;
  20735. if (sceneOctree !== undefined && sceneOctree !== null) {
  20736. var index = sceneOctree.dynamicContent.indexOf(this);
  20737. if (index !== -1) {
  20738. sceneOctree.dynamicContent.splice(index, 1);
  20739. }
  20740. }
  20741. // Query
  20742. var engine = this.getScene().getEngine();
  20743. if (this._occlusionQuery) {
  20744. this._isOcclusionQueryInProgress = false;
  20745. engine.deleteQuery(this._occlusionQuery);
  20746. this._occlusionQuery = null;
  20747. }
  20748. // Engine
  20749. engine.wipeCaches();
  20750. // Remove from scene
  20751. this.getScene().removeMesh(this);
  20752. if (disposeMaterialAndTextures) {
  20753. if (this.material) {
  20754. this.material.dispose(false, true);
  20755. }
  20756. }
  20757. if (!doNotRecurse) {
  20758. // Particles
  20759. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20760. if (this.getScene().particleSystems[index].emitter === this) {
  20761. this.getScene().particleSystems[index].dispose();
  20762. index--;
  20763. }
  20764. }
  20765. }
  20766. // facet data
  20767. if (this._facetDataEnabled) {
  20768. this.disableFacetData();
  20769. }
  20770. this.onAfterWorldMatrixUpdateObservable.clear();
  20771. this.onCollideObservable.clear();
  20772. this.onCollisionPositionChangeObservable.clear();
  20773. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20774. };
  20775. /**
  20776. * Adds the passed mesh as a child to the current mesh
  20777. * @param mesh defines the child mesh
  20778. * @returns the current mesh
  20779. */
  20780. AbstractMesh.prototype.addChild = function (mesh) {
  20781. mesh.setParent(this);
  20782. return this;
  20783. };
  20784. /**
  20785. * Removes the passed mesh from the current mesh children list
  20786. * @param mesh defines the child mesh
  20787. * @returns the current mesh
  20788. */
  20789. AbstractMesh.prototype.removeChild = function (mesh) {
  20790. mesh.setParent(null);
  20791. return this;
  20792. };
  20793. // Facet data
  20794. /** @hidden */
  20795. AbstractMesh.prototype._initFacetData = function () {
  20796. if (!this._facetNormals) {
  20797. this._facetNormals = new Array();
  20798. }
  20799. if (!this._facetPositions) {
  20800. this._facetPositions = new Array();
  20801. }
  20802. if (!this._facetPartitioning) {
  20803. this._facetPartitioning = new Array();
  20804. }
  20805. this._facetNb = (this.getIndices().length / 3) | 0;
  20806. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20807. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20808. for (var f = 0; f < this._facetNb; f++) {
  20809. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20810. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20811. }
  20812. this._facetDataEnabled = true;
  20813. return this;
  20814. };
  20815. /**
  20816. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20817. * This method can be called within the render loop.
  20818. * 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
  20819. * @returns the current mesh
  20820. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20821. */
  20822. AbstractMesh.prototype.updateFacetData = function () {
  20823. if (!this._facetDataEnabled) {
  20824. this._initFacetData();
  20825. }
  20826. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20827. var indices = this.getIndices();
  20828. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20829. var bInfo = this.getBoundingInfo();
  20830. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20831. // init arrays, matrix and sort function on first call
  20832. this._facetDepthSortEnabled = true;
  20833. if (indices instanceof Uint16Array) {
  20834. this._depthSortedIndices = new Uint16Array(indices);
  20835. }
  20836. else if (indices instanceof Uint32Array) {
  20837. this._depthSortedIndices = new Uint32Array(indices);
  20838. }
  20839. else {
  20840. var needs32bits = false;
  20841. for (var i = 0; i < indices.length; i++) {
  20842. if (indices[i] > 65535) {
  20843. needs32bits = true;
  20844. break;
  20845. }
  20846. }
  20847. if (needs32bits) {
  20848. this._depthSortedIndices = new Uint32Array(indices);
  20849. }
  20850. else {
  20851. this._depthSortedIndices = new Uint16Array(indices);
  20852. }
  20853. }
  20854. this._facetDepthSortFunction = function (f1, f2) {
  20855. return (f2.sqDistance - f1.sqDistance);
  20856. };
  20857. if (!this._facetDepthSortFrom) {
  20858. var camera = this.getScene().activeCamera;
  20859. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20860. }
  20861. this._depthSortedFacets = [];
  20862. for (var f = 0; f < this._facetNb; f++) {
  20863. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20864. this._depthSortedFacets.push(depthSortedFacet);
  20865. }
  20866. this._invertedMatrix = BABYLON.Matrix.Identity();
  20867. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20868. }
  20869. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20870. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20871. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20872. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20873. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20874. this._subDiv.max = this._partitioningSubdivisions;
  20875. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20876. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20877. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20878. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20879. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20880. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20881. // set the parameters for ComputeNormals()
  20882. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20883. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20884. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20885. this._facetParameters.bInfo = bInfo;
  20886. this._facetParameters.bbSize = this._bbSize;
  20887. this._facetParameters.subDiv = this._subDiv;
  20888. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20889. this._facetParameters.depthSort = this._facetDepthSort;
  20890. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20891. this.computeWorldMatrix(true);
  20892. this._worldMatrix.invertToRef(this._invertedMatrix);
  20893. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20894. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20895. }
  20896. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20897. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20898. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20899. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20900. var l = (this._depthSortedIndices.length / 3) | 0;
  20901. for (var f = 0; f < l; f++) {
  20902. var sind = this._depthSortedFacets[f].ind;
  20903. this._depthSortedIndices[f * 3] = indices[sind];
  20904. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20905. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20906. }
  20907. this.updateIndices(this._depthSortedIndices);
  20908. }
  20909. return this;
  20910. };
  20911. /**
  20912. * Returns the facetLocalNormals array.
  20913. * The normals are expressed in the mesh local spac
  20914. * @returns an array of Vector3
  20915. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20916. */
  20917. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20918. if (!this._facetNormals) {
  20919. this.updateFacetData();
  20920. }
  20921. return this._facetNormals;
  20922. };
  20923. /**
  20924. * Returns the facetLocalPositions array.
  20925. * The facet positions are expressed in the mesh local space
  20926. * @returns an array of Vector3
  20927. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20928. */
  20929. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20930. if (!this._facetPositions) {
  20931. this.updateFacetData();
  20932. }
  20933. return this._facetPositions;
  20934. };
  20935. /**
  20936. * Returns the facetLocalPartioning array
  20937. * @returns an array of array of numbers
  20938. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20939. */
  20940. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20941. if (!this._facetPartitioning) {
  20942. this.updateFacetData();
  20943. }
  20944. return this._facetPartitioning;
  20945. };
  20946. /**
  20947. * Returns the i-th facet position in the world system.
  20948. * This method allocates a new Vector3 per call
  20949. * @param i defines the facet index
  20950. * @returns a new Vector3
  20951. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20952. */
  20953. AbstractMesh.prototype.getFacetPosition = function (i) {
  20954. var pos = BABYLON.Vector3.Zero();
  20955. this.getFacetPositionToRef(i, pos);
  20956. return pos;
  20957. };
  20958. /**
  20959. * Sets the reference Vector3 with the i-th facet position in the world system
  20960. * @param i defines the facet index
  20961. * @param ref defines the target vector
  20962. * @returns the current mesh
  20963. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20964. */
  20965. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20966. var localPos = (this.getFacetLocalPositions())[i];
  20967. var world = this.getWorldMatrix();
  20968. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20969. return this;
  20970. };
  20971. /**
  20972. * Returns the i-th facet normal in the world system.
  20973. * This method allocates a new Vector3 per call
  20974. * @param i defines the facet index
  20975. * @returns a new Vector3
  20976. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20977. */
  20978. AbstractMesh.prototype.getFacetNormal = function (i) {
  20979. var norm = BABYLON.Vector3.Zero();
  20980. this.getFacetNormalToRef(i, norm);
  20981. return norm;
  20982. };
  20983. /**
  20984. * Sets the reference Vector3 with the i-th facet normal in the world system
  20985. * @param i defines the facet index
  20986. * @param ref defines the target vector
  20987. * @returns the current mesh
  20988. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20989. */
  20990. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20991. var localNorm = (this.getFacetLocalNormals())[i];
  20992. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20993. return this;
  20994. };
  20995. /**
  20996. * 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)
  20997. * @param x defines x coordinate
  20998. * @param y defines y coordinate
  20999. * @param z defines z coordinate
  21000. * @returns the array of facet indexes
  21001. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21002. */
  21003. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21004. var bInfo = this.getBoundingInfo();
  21005. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21006. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21007. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21008. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21009. return null;
  21010. }
  21011. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21012. };
  21013. /**
  21014. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21015. * @param projected sets as the (x,y,z) world projection on the facet
  21016. * @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
  21017. * @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
  21018. * @param x defines x coordinate
  21019. * @param y defines y coordinate
  21020. * @param z defines z coordinate
  21021. * @returns the face index if found (or null instead)
  21022. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21023. */
  21024. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21025. if (checkFace === void 0) { checkFace = false; }
  21026. if (facing === void 0) { facing = true; }
  21027. var world = this.getWorldMatrix();
  21028. var invMat = BABYLON.Tmp.Matrix[5];
  21029. world.invertToRef(invMat);
  21030. var invVect = BABYLON.Tmp.Vector3[8];
  21031. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21032. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21033. if (projected) {
  21034. // tranform the local computed projected vector to world coordinates
  21035. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21036. }
  21037. return closest;
  21038. };
  21039. /**
  21040. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21041. * @param projected sets as the (x,y,z) local projection on the facet
  21042. * @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
  21043. * @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
  21044. * @param x defines x coordinate
  21045. * @param y defines y coordinate
  21046. * @param z defines z coordinate
  21047. * @returns the face index if found (or null instead)
  21048. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21049. */
  21050. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21051. if (checkFace === void 0) { checkFace = false; }
  21052. if (facing === void 0) { facing = true; }
  21053. var closest = null;
  21054. var tmpx = 0.0;
  21055. var tmpy = 0.0;
  21056. var tmpz = 0.0;
  21057. var d = 0.0; // tmp dot facet normal * facet position
  21058. var t0 = 0.0;
  21059. var projx = 0.0;
  21060. var projy = 0.0;
  21061. var projz = 0.0;
  21062. // Get all the facets in the same partitioning block than (x, y, z)
  21063. var facetPositions = this.getFacetLocalPositions();
  21064. var facetNormals = this.getFacetLocalNormals();
  21065. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21066. if (!facetsInBlock) {
  21067. return null;
  21068. }
  21069. // Get the closest facet to (x, y, z)
  21070. var shortest = Number.MAX_VALUE; // init distance vars
  21071. var tmpDistance = shortest;
  21072. var fib; // current facet in the block
  21073. var norm; // current facet normal
  21074. var p0; // current facet barycenter position
  21075. // loop on all the facets in the current partitioning block
  21076. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21077. fib = facetsInBlock[idx];
  21078. norm = facetNormals[fib];
  21079. p0 = facetPositions[fib];
  21080. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21081. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21082. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21083. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21084. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21085. projx = x + norm.x * t0;
  21086. projy = y + norm.y * t0;
  21087. projz = z + norm.z * t0;
  21088. tmpx = projx - x;
  21089. tmpy = projy - y;
  21090. tmpz = projz - z;
  21091. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21092. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21093. shortest = tmpDistance;
  21094. closest = fib;
  21095. if (projected) {
  21096. projected.x = projx;
  21097. projected.y = projy;
  21098. projected.z = projz;
  21099. }
  21100. }
  21101. }
  21102. }
  21103. return closest;
  21104. };
  21105. /**
  21106. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21107. * @returns the parameters
  21108. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21109. */
  21110. AbstractMesh.prototype.getFacetDataParameters = function () {
  21111. return this._facetParameters;
  21112. };
  21113. /**
  21114. * Disables the feature FacetData and frees the related memory
  21115. * @returns the current mesh
  21116. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21117. */
  21118. AbstractMesh.prototype.disableFacetData = function () {
  21119. if (this._facetDataEnabled) {
  21120. this._facetDataEnabled = false;
  21121. this._facetPositions = new Array();
  21122. this._facetNormals = new Array();
  21123. this._facetPartitioning = new Array();
  21124. this._facetParameters = null;
  21125. this._depthSortedIndices = new Uint32Array(0);
  21126. }
  21127. return this;
  21128. };
  21129. /**
  21130. * Updates the AbstractMesh indices array
  21131. * @param indices defines the data source
  21132. * @returns the current mesh
  21133. */
  21134. AbstractMesh.prototype.updateIndices = function (indices) {
  21135. return this;
  21136. };
  21137. /**
  21138. * Creates new normals data for the mesh
  21139. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21140. * @returns the current mesh
  21141. */
  21142. AbstractMesh.prototype.createNormals = function (updatable) {
  21143. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21144. var indices = this.getIndices();
  21145. var normals;
  21146. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21147. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21148. }
  21149. else {
  21150. normals = [];
  21151. }
  21152. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21153. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21154. return this;
  21155. };
  21156. /**
  21157. * Align the mesh with a normal
  21158. * @param normal defines the normal to use
  21159. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21160. * @returns the current mesh
  21161. */
  21162. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21163. if (!upDirection) {
  21164. upDirection = BABYLON.Axis.Y;
  21165. }
  21166. var axisX = BABYLON.Tmp.Vector3[0];
  21167. var axisZ = BABYLON.Tmp.Vector3[1];
  21168. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21169. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21170. if (this.rotationQuaternion) {
  21171. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21172. }
  21173. else {
  21174. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21175. }
  21176. return this;
  21177. };
  21178. /** @hidden */
  21179. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21180. this._isOccluded = false;
  21181. };
  21182. /** No occlusion */
  21183. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21184. /** Occlusion set to optimisitic */
  21185. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21186. /** Occlusion set to strict */
  21187. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21188. /** Use an accurante occlusion algorithm */
  21189. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21190. /** Use a conservative occlusion algorithm */
  21191. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21192. return AbstractMesh;
  21193. }(BABYLON.TransformNode));
  21194. BABYLON.AbstractMesh = AbstractMesh;
  21195. })(BABYLON || (BABYLON = {}));
  21196. //# sourceMappingURL=babylon.abstractMesh.js.map
  21197. var BABYLON;
  21198. (function (BABYLON) {
  21199. /**
  21200. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21201. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21202. * 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.
  21203. */
  21204. var Light = /** @class */ (function (_super) {
  21205. __extends(Light, _super);
  21206. /**
  21207. * Creates a Light object in the scene.
  21208. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21209. * @param name The firendly name of the light
  21210. * @param scene The scene the light belongs too
  21211. */
  21212. function Light(name, scene) {
  21213. var _this = _super.call(this, name, scene) || this;
  21214. /**
  21215. * Diffuse gives the basic color to an object.
  21216. */
  21217. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21218. /**
  21219. * Specular produces a highlight color on an object.
  21220. * Note: This is note affecting PBR materials.
  21221. */
  21222. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21223. /**
  21224. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21225. * falling off base on range or angle.
  21226. * This can be set to any values in Light.FALLOFF_x.
  21227. *
  21228. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21229. * other types of materials.
  21230. */
  21231. _this.falloffType = Light.FALLOFF_DEFAULT;
  21232. /**
  21233. * Strength of the light.
  21234. * Note: By default it is define in the framework own unit.
  21235. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21236. */
  21237. _this.intensity = 1.0;
  21238. _this._range = Number.MAX_VALUE;
  21239. _this._inverseSquaredRange = 0;
  21240. /**
  21241. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21242. * of light.
  21243. */
  21244. _this._photometricScale = 1.0;
  21245. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21246. _this._radius = 0.00001;
  21247. /**
  21248. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21249. * exceeding the number allowed of the materials.
  21250. */
  21251. _this.renderPriority = 0;
  21252. _this._shadowEnabled = true;
  21253. _this._excludeWithLayerMask = 0;
  21254. _this._includeOnlyWithLayerMask = 0;
  21255. _this._lightmapMode = 0;
  21256. /**
  21257. * @hidden Internal use only.
  21258. */
  21259. _this._excludedMeshesIds = new Array();
  21260. /**
  21261. * @hidden Internal use only.
  21262. */
  21263. _this._includedOnlyMeshesIds = new Array();
  21264. _this.getScene().addLight(_this);
  21265. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21266. _this._buildUniformLayout();
  21267. _this.includedOnlyMeshes = new Array();
  21268. _this.excludedMeshes = new Array();
  21269. _this._resyncMeshes();
  21270. return _this;
  21271. }
  21272. Object.defineProperty(Light.prototype, "range", {
  21273. /**
  21274. * Defines how far from the source the light is impacting in scene units.
  21275. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21276. */
  21277. get: function () {
  21278. return this._range;
  21279. },
  21280. /**
  21281. * Defines how far from the source the light is impacting in scene units.
  21282. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21283. */
  21284. set: function (value) {
  21285. this._range = value;
  21286. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21287. },
  21288. enumerable: true,
  21289. configurable: true
  21290. });
  21291. Object.defineProperty(Light.prototype, "intensityMode", {
  21292. /**
  21293. * Gets the photometric scale used to interpret the intensity.
  21294. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21295. */
  21296. get: function () {
  21297. return this._intensityMode;
  21298. },
  21299. /**
  21300. * Sets the photometric scale used to interpret the intensity.
  21301. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21302. */
  21303. set: function (value) {
  21304. this._intensityMode = value;
  21305. this._computePhotometricScale();
  21306. },
  21307. enumerable: true,
  21308. configurable: true
  21309. });
  21310. ;
  21311. ;
  21312. Object.defineProperty(Light.prototype, "radius", {
  21313. /**
  21314. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21315. */
  21316. get: function () {
  21317. return this._radius;
  21318. },
  21319. /**
  21320. * sets the light radius used by PBR Materials to simulate soft area lights.
  21321. */
  21322. set: function (value) {
  21323. this._radius = value;
  21324. this._computePhotometricScale();
  21325. },
  21326. enumerable: true,
  21327. configurable: true
  21328. });
  21329. ;
  21330. ;
  21331. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21332. /**
  21333. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21334. * the current shadow generator.
  21335. */
  21336. get: function () {
  21337. return this._shadowEnabled;
  21338. },
  21339. /**
  21340. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21341. * the current shadow generator.
  21342. */
  21343. set: function (value) {
  21344. if (this._shadowEnabled === value) {
  21345. return;
  21346. }
  21347. this._shadowEnabled = value;
  21348. this._markMeshesAsLightDirty();
  21349. },
  21350. enumerable: true,
  21351. configurable: true
  21352. });
  21353. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21354. /**
  21355. * Gets the only meshes impacted by this light.
  21356. */
  21357. get: function () {
  21358. return this._includedOnlyMeshes;
  21359. },
  21360. /**
  21361. * Sets the only meshes impacted by this light.
  21362. */
  21363. set: function (value) {
  21364. this._includedOnlyMeshes = value;
  21365. this._hookArrayForIncludedOnly(value);
  21366. },
  21367. enumerable: true,
  21368. configurable: true
  21369. });
  21370. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21371. /**
  21372. * Gets the meshes not impacted by this light.
  21373. */
  21374. get: function () {
  21375. return this._excludedMeshes;
  21376. },
  21377. /**
  21378. * Sets the meshes not impacted by this light.
  21379. */
  21380. set: function (value) {
  21381. this._excludedMeshes = value;
  21382. this._hookArrayForExcluded(value);
  21383. },
  21384. enumerable: true,
  21385. configurable: true
  21386. });
  21387. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21388. /**
  21389. * Gets the layer id use to find what meshes are not impacted by the light.
  21390. * Inactive if 0
  21391. */
  21392. get: function () {
  21393. return this._excludeWithLayerMask;
  21394. },
  21395. /**
  21396. * Sets the layer id use to find what meshes are not impacted by the light.
  21397. * Inactive if 0
  21398. */
  21399. set: function (value) {
  21400. this._excludeWithLayerMask = value;
  21401. this._resyncMeshes();
  21402. },
  21403. enumerable: true,
  21404. configurable: true
  21405. });
  21406. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21407. /**
  21408. * Gets the layer id use to find what meshes are impacted by the light.
  21409. * Inactive if 0
  21410. */
  21411. get: function () {
  21412. return this._includeOnlyWithLayerMask;
  21413. },
  21414. /**
  21415. * Sets the layer id use to find what meshes are impacted by the light.
  21416. * Inactive if 0
  21417. */
  21418. set: function (value) {
  21419. this._includeOnlyWithLayerMask = value;
  21420. this._resyncMeshes();
  21421. },
  21422. enumerable: true,
  21423. configurable: true
  21424. });
  21425. Object.defineProperty(Light.prototype, "lightmapMode", {
  21426. /**
  21427. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21428. */
  21429. get: function () {
  21430. return this._lightmapMode;
  21431. },
  21432. /**
  21433. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21434. */
  21435. set: function (value) {
  21436. if (this._lightmapMode === value) {
  21437. return;
  21438. }
  21439. this._lightmapMode = value;
  21440. this._markMeshesAsLightDirty();
  21441. },
  21442. enumerable: true,
  21443. configurable: true
  21444. });
  21445. /**
  21446. * Returns the string "Light".
  21447. * @returns the class name
  21448. */
  21449. Light.prototype.getClassName = function () {
  21450. return "Light";
  21451. };
  21452. /**
  21453. * Converts the light information to a readable string for debug purpose.
  21454. * @param fullDetails Supports for multiple levels of logging within scene loading
  21455. * @returns the human readable light info
  21456. */
  21457. Light.prototype.toString = function (fullDetails) {
  21458. var ret = "Name: " + this.name;
  21459. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21460. if (this.animations) {
  21461. for (var i = 0; i < this.animations.length; i++) {
  21462. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21463. }
  21464. }
  21465. if (fullDetails) {
  21466. }
  21467. return ret;
  21468. };
  21469. /**
  21470. * Set the enabled state of this node.
  21471. * @param value - the new enabled state
  21472. */
  21473. Light.prototype.setEnabled = function (value) {
  21474. _super.prototype.setEnabled.call(this, value);
  21475. this._resyncMeshes();
  21476. };
  21477. /**
  21478. * Returns the Light associated shadow generator if any.
  21479. * @return the associated shadow generator.
  21480. */
  21481. Light.prototype.getShadowGenerator = function () {
  21482. return this._shadowGenerator;
  21483. };
  21484. /**
  21485. * Returns a Vector3, the absolute light position in the World.
  21486. * @returns the world space position of the light
  21487. */
  21488. Light.prototype.getAbsolutePosition = function () {
  21489. return BABYLON.Vector3.Zero();
  21490. };
  21491. /**
  21492. * Specifies if the light will affect the passed mesh.
  21493. * @param mesh The mesh to test against the light
  21494. * @return true the mesh is affected otherwise, false.
  21495. */
  21496. Light.prototype.canAffectMesh = function (mesh) {
  21497. if (!mesh) {
  21498. return true;
  21499. }
  21500. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21501. return false;
  21502. }
  21503. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21504. return false;
  21505. }
  21506. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21507. return false;
  21508. }
  21509. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21510. return false;
  21511. }
  21512. return true;
  21513. };
  21514. /**
  21515. * Computes and Returns the light World matrix.
  21516. * @returns the world matrix
  21517. */
  21518. Light.prototype.getWorldMatrix = function () {
  21519. this._currentRenderId = this.getScene().getRenderId();
  21520. this._childRenderId = this._currentRenderId;
  21521. var worldMatrix = this._getWorldMatrix();
  21522. if (this.parent && this.parent.getWorldMatrix) {
  21523. if (!this._parentedWorldMatrix) {
  21524. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21525. }
  21526. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21527. this._markSyncedWithParent();
  21528. return this._parentedWorldMatrix;
  21529. }
  21530. return worldMatrix;
  21531. };
  21532. /**
  21533. * Sort function to order lights for rendering.
  21534. * @param a First Light object to compare to second.
  21535. * @param b Second Light object to compare first.
  21536. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21537. */
  21538. Light.CompareLightsPriority = function (a, b) {
  21539. //shadow-casting lights have priority over non-shadow-casting lights
  21540. //the renderPrioirty is a secondary sort criterion
  21541. if (a.shadowEnabled !== b.shadowEnabled) {
  21542. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21543. }
  21544. return b.renderPriority - a.renderPriority;
  21545. };
  21546. /**
  21547. * Releases resources associated with this node.
  21548. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21549. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21550. */
  21551. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21552. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21553. if (this._shadowGenerator) {
  21554. this._shadowGenerator.dispose();
  21555. this._shadowGenerator = null;
  21556. }
  21557. // Animations
  21558. this.getScene().stopAnimation(this);
  21559. // Remove from meshes
  21560. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21561. var mesh = _a[_i];
  21562. mesh._removeLightSource(this);
  21563. }
  21564. this._uniformBuffer.dispose();
  21565. // Remove from scene
  21566. this.getScene().removeLight(this);
  21567. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21568. };
  21569. /**
  21570. * Returns the light type ID (integer).
  21571. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21572. */
  21573. Light.prototype.getTypeID = function () {
  21574. return 0;
  21575. };
  21576. /**
  21577. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21578. * @returns the scaled intensity in intensity mode unit
  21579. */
  21580. Light.prototype.getScaledIntensity = function () {
  21581. return this._photometricScale * this.intensity;
  21582. };
  21583. /**
  21584. * Returns a new Light object, named "name", from the current one.
  21585. * @param name The name of the cloned light
  21586. * @returns the new created light
  21587. */
  21588. Light.prototype.clone = function (name) {
  21589. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21590. if (!constructor) {
  21591. return null;
  21592. }
  21593. return BABYLON.SerializationHelper.Clone(constructor, this);
  21594. };
  21595. /**
  21596. * Serializes the current light into a Serialization object.
  21597. * @returns the serialized object.
  21598. */
  21599. Light.prototype.serialize = function () {
  21600. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21601. // Type
  21602. serializationObject.type = this.getTypeID();
  21603. // Parent
  21604. if (this.parent) {
  21605. serializationObject.parentId = this.parent.id;
  21606. }
  21607. // Inclusion / exclusions
  21608. if (this.excludedMeshes.length > 0) {
  21609. serializationObject.excludedMeshesIds = [];
  21610. this.excludedMeshes.forEach(function (mesh) {
  21611. serializationObject.excludedMeshesIds.push(mesh.id);
  21612. });
  21613. }
  21614. if (this.includedOnlyMeshes.length > 0) {
  21615. serializationObject.includedOnlyMeshesIds = [];
  21616. this.includedOnlyMeshes.forEach(function (mesh) {
  21617. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21618. });
  21619. }
  21620. // Animations
  21621. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21622. serializationObject.ranges = this.serializeAnimationRanges();
  21623. return serializationObject;
  21624. };
  21625. /**
  21626. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21627. * This new light is named "name" and added to the passed scene.
  21628. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21629. * @param name The friendly name of the light
  21630. * @param scene The scene the new light will belong to
  21631. * @returns the constructor function
  21632. */
  21633. Light.GetConstructorFromName = function (type, name, scene) {
  21634. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21635. if (constructorFunc) {
  21636. return constructorFunc;
  21637. }
  21638. // Default to no light for none present once.
  21639. return null;
  21640. };
  21641. /**
  21642. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21643. * @param parsedLight The JSON representation of the light
  21644. * @param scene The scene to create the parsed light in
  21645. * @returns the created light after parsing
  21646. */
  21647. Light.Parse = function (parsedLight, scene) {
  21648. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21649. if (!constructor) {
  21650. return null;
  21651. }
  21652. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21653. // Inclusion / exclusions
  21654. if (parsedLight.excludedMeshesIds) {
  21655. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21656. }
  21657. if (parsedLight.includedOnlyMeshesIds) {
  21658. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21659. }
  21660. // Parent
  21661. if (parsedLight.parentId) {
  21662. light._waitingParentId = parsedLight.parentId;
  21663. }
  21664. // Animations
  21665. if (parsedLight.animations) {
  21666. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21667. var parsedAnimation = parsedLight.animations[animationIndex];
  21668. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21669. }
  21670. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21671. }
  21672. if (parsedLight.autoAnimate) {
  21673. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21674. }
  21675. return light;
  21676. };
  21677. Light.prototype._hookArrayForExcluded = function (array) {
  21678. var _this = this;
  21679. var oldPush = array.push;
  21680. array.push = function () {
  21681. var items = [];
  21682. for (var _i = 0; _i < arguments.length; _i++) {
  21683. items[_i] = arguments[_i];
  21684. }
  21685. var result = oldPush.apply(array, items);
  21686. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21687. var item = items_1[_a];
  21688. item._resyncLighSource(_this);
  21689. }
  21690. return result;
  21691. };
  21692. var oldSplice = array.splice;
  21693. array.splice = function (index, deleteCount) {
  21694. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21695. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21696. var item = deleted_1[_i];
  21697. item._resyncLighSource(_this);
  21698. }
  21699. return deleted;
  21700. };
  21701. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21702. var item = array_1[_i];
  21703. item._resyncLighSource(this);
  21704. }
  21705. };
  21706. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21707. var _this = this;
  21708. var oldPush = array.push;
  21709. array.push = function () {
  21710. var items = [];
  21711. for (var _i = 0; _i < arguments.length; _i++) {
  21712. items[_i] = arguments[_i];
  21713. }
  21714. var result = oldPush.apply(array, items);
  21715. _this._resyncMeshes();
  21716. return result;
  21717. };
  21718. var oldSplice = array.splice;
  21719. array.splice = function (index, deleteCount) {
  21720. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21721. _this._resyncMeshes();
  21722. return deleted;
  21723. };
  21724. this._resyncMeshes();
  21725. };
  21726. Light.prototype._resyncMeshes = function () {
  21727. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21728. var mesh = _a[_i];
  21729. mesh._resyncLighSource(this);
  21730. }
  21731. };
  21732. /**
  21733. * Forces the meshes to update their light related information in their rendering used effects
  21734. * @hidden Internal Use Only
  21735. */
  21736. Light.prototype._markMeshesAsLightDirty = function () {
  21737. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21738. var mesh = _a[_i];
  21739. if (mesh._lightSources.indexOf(this) !== -1) {
  21740. mesh._markSubMeshesAsLightDirty();
  21741. }
  21742. }
  21743. };
  21744. /**
  21745. * Recomputes the cached photometric scale if needed.
  21746. */
  21747. Light.prototype._computePhotometricScale = function () {
  21748. this._photometricScale = this._getPhotometricScale();
  21749. this.getScene().resetCachedMaterial();
  21750. };
  21751. /**
  21752. * Returns the Photometric Scale according to the light type and intensity mode.
  21753. */
  21754. Light.prototype._getPhotometricScale = function () {
  21755. var photometricScale = 0.0;
  21756. var lightTypeID = this.getTypeID();
  21757. //get photometric mode
  21758. var photometricMode = this.intensityMode;
  21759. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21760. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21761. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21762. }
  21763. else {
  21764. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21765. }
  21766. }
  21767. //compute photometric scale
  21768. switch (lightTypeID) {
  21769. case Light.LIGHTTYPEID_POINTLIGHT:
  21770. case Light.LIGHTTYPEID_SPOTLIGHT:
  21771. switch (photometricMode) {
  21772. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21773. photometricScale = 1.0 / (4.0 * Math.PI);
  21774. break;
  21775. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21776. photometricScale = 1.0;
  21777. break;
  21778. case Light.INTENSITYMODE_LUMINANCE:
  21779. photometricScale = this.radius * this.radius;
  21780. break;
  21781. }
  21782. break;
  21783. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21784. switch (photometricMode) {
  21785. case Light.INTENSITYMODE_ILLUMINANCE:
  21786. photometricScale = 1.0;
  21787. break;
  21788. case Light.INTENSITYMODE_LUMINANCE:
  21789. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21790. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21791. var apexAngleRadians = this.radius;
  21792. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21793. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21794. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21795. photometricScale = solidAngle;
  21796. break;
  21797. }
  21798. break;
  21799. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21800. // No fall off in hemisperic light.
  21801. photometricScale = 1.0;
  21802. break;
  21803. }
  21804. return photometricScale;
  21805. };
  21806. /**
  21807. * Reorder the light in the scene according to their defined priority.
  21808. * @hidden Internal Use Only
  21809. */
  21810. Light.prototype._reorderLightsInScene = function () {
  21811. var scene = this.getScene();
  21812. if (this._renderPriority != 0) {
  21813. scene.requireLightSorting = true;
  21814. }
  21815. this.getScene().sortLightsByPriority();
  21816. };
  21817. /**
  21818. * Falloff Default: light is falling off following the material specification:
  21819. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  21820. */
  21821. Light.FALLOFF_DEFAULT = 0;
  21822. /**
  21823. * Falloff Physical: light is falling off following the inverse squared distance law.
  21824. */
  21825. Light.FALLOFF_PHYSICAL = 1;
  21826. /**
  21827. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  21828. * to enhance interoperability with other engines.
  21829. */
  21830. Light.FALLOFF_GLTF = 2;
  21831. /**
  21832. * Falloff Standard: light is falling off like in the standard material
  21833. * to enhance interoperability with other materials.
  21834. */
  21835. Light.FALLOFF_STANDARD = 3;
  21836. //lightmapMode Consts
  21837. /**
  21838. * If every light affecting the material is in this lightmapMode,
  21839. * material.lightmapTexture adds or multiplies
  21840. * (depends on material.useLightmapAsShadowmap)
  21841. * after every other light calculations.
  21842. */
  21843. Light.LIGHTMAP_DEFAULT = 0;
  21844. /**
  21845. * material.lightmapTexture as only diffuse lighting from this light
  21846. * adds only specular lighting from this light
  21847. * adds dynamic shadows
  21848. */
  21849. Light.LIGHTMAP_SPECULAR = 1;
  21850. /**
  21851. * material.lightmapTexture as only lighting
  21852. * no light calculation from this light
  21853. * only adds dynamic shadows from this light
  21854. */
  21855. Light.LIGHTMAP_SHADOWSONLY = 2;
  21856. // Intensity Mode Consts
  21857. /**
  21858. * Each light type uses the default quantity according to its type:
  21859. * point/spot lights use luminous intensity
  21860. * directional lights use illuminance
  21861. */
  21862. Light.INTENSITYMODE_AUTOMATIC = 0;
  21863. /**
  21864. * lumen (lm)
  21865. */
  21866. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  21867. /**
  21868. * candela (lm/sr)
  21869. */
  21870. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21871. /**
  21872. * lux (lm/m^2)
  21873. */
  21874. Light.INTENSITYMODE_ILLUMINANCE = 3;
  21875. /**
  21876. * nit (cd/m^2)
  21877. */
  21878. Light.INTENSITYMODE_LUMINANCE = 4;
  21879. // Light types ids const.
  21880. /**
  21881. * Light type const id of the point light.
  21882. */
  21883. Light.LIGHTTYPEID_POINTLIGHT = 0;
  21884. /**
  21885. * Light type const id of the directional light.
  21886. */
  21887. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21888. /**
  21889. * Light type const id of the spot light.
  21890. */
  21891. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  21892. /**
  21893. * Light type const id of the hemispheric light.
  21894. */
  21895. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21896. __decorate([
  21897. BABYLON.serializeAsColor3()
  21898. ], Light.prototype, "diffuse", void 0);
  21899. __decorate([
  21900. BABYLON.serializeAsColor3()
  21901. ], Light.prototype, "specular", void 0);
  21902. __decorate([
  21903. BABYLON.serialize()
  21904. ], Light.prototype, "falloffType", void 0);
  21905. __decorate([
  21906. BABYLON.serialize()
  21907. ], Light.prototype, "intensity", void 0);
  21908. __decorate([
  21909. BABYLON.serialize()
  21910. ], Light.prototype, "range", null);
  21911. __decorate([
  21912. BABYLON.serialize()
  21913. ], Light.prototype, "intensityMode", null);
  21914. __decorate([
  21915. BABYLON.serialize()
  21916. ], Light.prototype, "radius", null);
  21917. __decorate([
  21918. BABYLON.serialize()
  21919. ], Light.prototype, "_renderPriority", void 0);
  21920. __decorate([
  21921. BABYLON.expandToProperty("_reorderLightsInScene")
  21922. ], Light.prototype, "renderPriority", void 0);
  21923. __decorate([
  21924. BABYLON.serialize("shadowEnabled")
  21925. ], Light.prototype, "_shadowEnabled", void 0);
  21926. __decorate([
  21927. BABYLON.serialize("excludeWithLayerMask")
  21928. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21929. __decorate([
  21930. BABYLON.serialize("includeOnlyWithLayerMask")
  21931. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21932. __decorate([
  21933. BABYLON.serialize("lightmapMode")
  21934. ], Light.prototype, "_lightmapMode", void 0);
  21935. return Light;
  21936. }(BABYLON.Node));
  21937. BABYLON.Light = Light;
  21938. })(BABYLON || (BABYLON = {}));
  21939. //# sourceMappingURL=babylon.light.js.map
  21940. var BABYLON;
  21941. (function (BABYLON) {
  21942. var Camera = /** @class */ (function (_super) {
  21943. __extends(Camera, _super);
  21944. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21945. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21946. var _this = _super.call(this, name, scene) || this;
  21947. /**
  21948. * The vector the camera should consider as up.
  21949. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21950. */
  21951. _this.upVector = BABYLON.Vector3.Up();
  21952. _this.orthoLeft = null;
  21953. _this.orthoRight = null;
  21954. _this.orthoBottom = null;
  21955. _this.orthoTop = null;
  21956. /**
  21957. * FOV is set in Radians. (default is 0.8)
  21958. */
  21959. _this.fov = 0.8;
  21960. _this.minZ = 1;
  21961. _this.maxZ = 10000.0;
  21962. _this.inertia = 0.9;
  21963. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21964. _this.isIntermediate = false;
  21965. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21966. /**
  21967. * Restricts the camera to viewing objects with the same layerMask.
  21968. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21969. */
  21970. _this.layerMask = 0x0FFFFFFF;
  21971. /**
  21972. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21973. */
  21974. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21975. // Camera rig members
  21976. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21977. _this._rigCameras = new Array();
  21978. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21979. _this._skipRendering = false;
  21980. _this.customRenderTargets = new Array();
  21981. // Observables
  21982. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21983. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21984. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21985. _this.onRestoreStateObservable = new BABYLON.Observable();
  21986. // Cache
  21987. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21988. _this._projectionMatrix = new BABYLON.Matrix();
  21989. _this._doNotComputeProjectionMatrix = false;
  21990. _this._worldMatrix = BABYLON.Matrix.Identity();
  21991. _this._postProcesses = new Array();
  21992. _this._transformMatrix = BABYLON.Matrix.Zero();
  21993. _this._activeMeshes = new BABYLON.SmartArray(256);
  21994. _this._globalPosition = BABYLON.Vector3.Zero();
  21995. _this._refreshFrustumPlanes = true;
  21996. _this.getScene().addCamera(_this);
  21997. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  21998. _this.getScene().activeCamera = _this;
  21999. }
  22000. _this.position = position;
  22001. return _this;
  22002. }
  22003. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22004. get: function () {
  22005. return Camera._PERSPECTIVE_CAMERA;
  22006. },
  22007. enumerable: true,
  22008. configurable: true
  22009. });
  22010. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22011. get: function () {
  22012. return Camera._ORTHOGRAPHIC_CAMERA;
  22013. },
  22014. enumerable: true,
  22015. configurable: true
  22016. });
  22017. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22018. /**
  22019. * This is the default FOV mode for perspective cameras.
  22020. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22021. *
  22022. */
  22023. get: function () {
  22024. return Camera._FOVMODE_VERTICAL_FIXED;
  22025. },
  22026. enumerable: true,
  22027. configurable: true
  22028. });
  22029. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22030. /**
  22031. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22032. *
  22033. */
  22034. get: function () {
  22035. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22036. },
  22037. enumerable: true,
  22038. configurable: true
  22039. });
  22040. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22041. get: function () {
  22042. return Camera._RIG_MODE_NONE;
  22043. },
  22044. enumerable: true,
  22045. configurable: true
  22046. });
  22047. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22048. get: function () {
  22049. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22050. },
  22051. enumerable: true,
  22052. configurable: true
  22053. });
  22054. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22055. get: function () {
  22056. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22057. },
  22058. enumerable: true,
  22059. configurable: true
  22060. });
  22061. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22062. get: function () {
  22063. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22064. },
  22065. enumerable: true,
  22066. configurable: true
  22067. });
  22068. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22069. get: function () {
  22070. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22071. },
  22072. enumerable: true,
  22073. configurable: true
  22074. });
  22075. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22076. get: function () {
  22077. return Camera._RIG_MODE_VR;
  22078. },
  22079. enumerable: true,
  22080. configurable: true
  22081. });
  22082. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22083. get: function () {
  22084. return Camera._RIG_MODE_WEBVR;
  22085. },
  22086. enumerable: true,
  22087. configurable: true
  22088. });
  22089. /**
  22090. * Store current camera state (fov, position, etc..)
  22091. */
  22092. Camera.prototype.storeState = function () {
  22093. this._stateStored = true;
  22094. this._storedFov = this.fov;
  22095. return this;
  22096. };
  22097. /**
  22098. * Restores the camera state values if it has been stored. You must call storeState() first
  22099. */
  22100. Camera.prototype._restoreStateValues = function () {
  22101. if (!this._stateStored) {
  22102. return false;
  22103. }
  22104. this.fov = this._storedFov;
  22105. return true;
  22106. };
  22107. /**
  22108. * Restored camera state. You must call storeState() first
  22109. */
  22110. Camera.prototype.restoreState = function () {
  22111. if (this._restoreStateValues()) {
  22112. this.onRestoreStateObservable.notifyObservers(this);
  22113. return true;
  22114. }
  22115. return false;
  22116. };
  22117. Camera.prototype.getClassName = function () {
  22118. return "Camera";
  22119. };
  22120. /**
  22121. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22122. */
  22123. Camera.prototype.toString = function (fullDetails) {
  22124. var ret = "Name: " + this.name;
  22125. ret += ", type: " + this.getClassName();
  22126. if (this.animations) {
  22127. for (var i = 0; i < this.animations.length; i++) {
  22128. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22129. }
  22130. }
  22131. if (fullDetails) {
  22132. }
  22133. return ret;
  22134. };
  22135. Object.defineProperty(Camera.prototype, "globalPosition", {
  22136. get: function () {
  22137. return this._globalPosition;
  22138. },
  22139. enumerable: true,
  22140. configurable: true
  22141. });
  22142. Camera.prototype.getActiveMeshes = function () {
  22143. return this._activeMeshes;
  22144. };
  22145. Camera.prototype.isActiveMesh = function (mesh) {
  22146. return (this._activeMeshes.indexOf(mesh) !== -1);
  22147. };
  22148. /**
  22149. * Is this camera ready to be used/rendered
  22150. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22151. * @return true if the camera is ready
  22152. */
  22153. Camera.prototype.isReady = function (completeCheck) {
  22154. if (completeCheck === void 0) { completeCheck = false; }
  22155. if (completeCheck) {
  22156. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22157. var pp = _a[_i];
  22158. if (pp && !pp.isReady()) {
  22159. return false;
  22160. }
  22161. }
  22162. }
  22163. return _super.prototype.isReady.call(this, completeCheck);
  22164. };
  22165. //Cache
  22166. Camera.prototype._initCache = function () {
  22167. _super.prototype._initCache.call(this);
  22168. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22169. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22170. this._cache.mode = undefined;
  22171. this._cache.minZ = undefined;
  22172. this._cache.maxZ = undefined;
  22173. this._cache.fov = undefined;
  22174. this._cache.fovMode = undefined;
  22175. this._cache.aspectRatio = undefined;
  22176. this._cache.orthoLeft = undefined;
  22177. this._cache.orthoRight = undefined;
  22178. this._cache.orthoBottom = undefined;
  22179. this._cache.orthoTop = undefined;
  22180. this._cache.renderWidth = undefined;
  22181. this._cache.renderHeight = undefined;
  22182. };
  22183. Camera.prototype._updateCache = function (ignoreParentClass) {
  22184. if (!ignoreParentClass) {
  22185. _super.prototype._updateCache.call(this);
  22186. }
  22187. this._cache.position.copyFrom(this.position);
  22188. this._cache.upVector.copyFrom(this.upVector);
  22189. };
  22190. // Synchronized
  22191. Camera.prototype._isSynchronized = function () {
  22192. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22193. };
  22194. Camera.prototype._isSynchronizedViewMatrix = function () {
  22195. if (!_super.prototype._isSynchronized.call(this))
  22196. return false;
  22197. return this._cache.position.equals(this.position)
  22198. && this._cache.upVector.equals(this.upVector)
  22199. && this.isSynchronizedWithParent();
  22200. };
  22201. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22202. var check = this._cache.mode === this.mode
  22203. && this._cache.minZ === this.minZ
  22204. && this._cache.maxZ === this.maxZ;
  22205. if (!check) {
  22206. return false;
  22207. }
  22208. var engine = this.getEngine();
  22209. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22210. check = this._cache.fov === this.fov
  22211. && this._cache.fovMode === this.fovMode
  22212. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22213. }
  22214. else {
  22215. check = this._cache.orthoLeft === this.orthoLeft
  22216. && this._cache.orthoRight === this.orthoRight
  22217. && this._cache.orthoBottom === this.orthoBottom
  22218. && this._cache.orthoTop === this.orthoTop
  22219. && this._cache.renderWidth === engine.getRenderWidth()
  22220. && this._cache.renderHeight === engine.getRenderHeight();
  22221. }
  22222. return check;
  22223. };
  22224. // Controls
  22225. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22226. };
  22227. Camera.prototype.detachControl = function (element) {
  22228. };
  22229. Camera.prototype.update = function () {
  22230. this._checkInputs();
  22231. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22232. this._updateRigCameras();
  22233. }
  22234. };
  22235. Camera.prototype._checkInputs = function () {
  22236. this.onAfterCheckInputsObservable.notifyObservers(this);
  22237. };
  22238. Object.defineProperty(Camera.prototype, "rigCameras", {
  22239. get: function () {
  22240. return this._rigCameras;
  22241. },
  22242. enumerable: true,
  22243. configurable: true
  22244. });
  22245. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22246. get: function () {
  22247. return this._rigPostProcess;
  22248. },
  22249. enumerable: true,
  22250. configurable: true
  22251. });
  22252. /**
  22253. * Internal, gets the first post proces.
  22254. * @returns the first post process to be run on this camera.
  22255. */
  22256. Camera.prototype._getFirstPostProcess = function () {
  22257. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22258. if (this._postProcesses[ppIndex] !== null) {
  22259. return this._postProcesses[ppIndex];
  22260. }
  22261. }
  22262. return null;
  22263. };
  22264. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22265. // invalidate framebuffer
  22266. var firstPostProcess = this._getFirstPostProcess();
  22267. if (firstPostProcess) {
  22268. firstPostProcess.markTextureDirty();
  22269. }
  22270. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22271. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22272. var cam = this._rigCameras[i];
  22273. var rigPostProcess = cam._rigPostProcess;
  22274. // for VR rig, there does not have to be a post process
  22275. if (rigPostProcess) {
  22276. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22277. if (isPass) {
  22278. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22279. cam.isIntermediate = this._postProcesses.length === 0;
  22280. }
  22281. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22282. rigPostProcess.markTextureDirty();
  22283. }
  22284. else {
  22285. cam._postProcesses = this._postProcesses.slice(0);
  22286. }
  22287. }
  22288. };
  22289. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22290. if (insertAt === void 0) { insertAt = null; }
  22291. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22292. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22293. return 0;
  22294. }
  22295. if (insertAt == null || insertAt < 0) {
  22296. this._postProcesses.push(postProcess);
  22297. }
  22298. else if (this._postProcesses[insertAt] === null) {
  22299. this._postProcesses[insertAt] = postProcess;
  22300. }
  22301. else {
  22302. this._postProcesses.splice(insertAt, 0, postProcess);
  22303. }
  22304. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22305. return this._postProcesses.indexOf(postProcess);
  22306. };
  22307. Camera.prototype.detachPostProcess = function (postProcess) {
  22308. var idx = this._postProcesses.indexOf(postProcess);
  22309. if (idx !== -1) {
  22310. this._postProcesses[idx] = null;
  22311. }
  22312. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22313. };
  22314. Camera.prototype.getWorldMatrix = function () {
  22315. if (this._isSynchronizedViewMatrix()) {
  22316. return this._worldMatrix;
  22317. }
  22318. // Getting the the view matrix will also compute the world matrix.
  22319. this.getViewMatrix();
  22320. return this._worldMatrix;
  22321. };
  22322. Camera.prototype._getViewMatrix = function () {
  22323. return BABYLON.Matrix.Identity();
  22324. };
  22325. Camera.prototype.getViewMatrix = function (force) {
  22326. if (!force && this._isSynchronizedViewMatrix()) {
  22327. return this._computedViewMatrix;
  22328. }
  22329. this.updateCache();
  22330. this._computedViewMatrix = this._getViewMatrix();
  22331. this._currentRenderId = this.getScene().getRenderId();
  22332. this._childRenderId = this._currentRenderId;
  22333. this._refreshFrustumPlanes = true;
  22334. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22335. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22336. }
  22337. this.onViewMatrixChangedObservable.notifyObservers(this);
  22338. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22339. return this._computedViewMatrix;
  22340. };
  22341. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22342. this._doNotComputeProjectionMatrix = true;
  22343. if (projection !== undefined) {
  22344. this._projectionMatrix = projection;
  22345. }
  22346. };
  22347. ;
  22348. Camera.prototype.unfreezeProjectionMatrix = function () {
  22349. this._doNotComputeProjectionMatrix = false;
  22350. };
  22351. ;
  22352. Camera.prototype.getProjectionMatrix = function (force) {
  22353. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22354. return this._projectionMatrix;
  22355. }
  22356. // Cache
  22357. this._cache.mode = this.mode;
  22358. this._cache.minZ = this.minZ;
  22359. this._cache.maxZ = this.maxZ;
  22360. // Matrix
  22361. this._refreshFrustumPlanes = true;
  22362. var engine = this.getEngine();
  22363. var scene = this.getScene();
  22364. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22365. this._cache.fov = this.fov;
  22366. this._cache.fovMode = this.fovMode;
  22367. this._cache.aspectRatio = engine.getAspectRatio(this);
  22368. if (this.minZ <= 0) {
  22369. this.minZ = 0.1;
  22370. }
  22371. if (scene.useRightHandedSystem) {
  22372. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22373. }
  22374. else {
  22375. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22376. }
  22377. }
  22378. else {
  22379. var halfWidth = engine.getRenderWidth() / 2.0;
  22380. var halfHeight = engine.getRenderHeight() / 2.0;
  22381. if (scene.useRightHandedSystem) {
  22382. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22383. }
  22384. else {
  22385. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22386. }
  22387. this._cache.orthoLeft = this.orthoLeft;
  22388. this._cache.orthoRight = this.orthoRight;
  22389. this._cache.orthoBottom = this.orthoBottom;
  22390. this._cache.orthoTop = this.orthoTop;
  22391. this._cache.renderWidth = engine.getRenderWidth();
  22392. this._cache.renderHeight = engine.getRenderHeight();
  22393. }
  22394. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22395. return this._projectionMatrix;
  22396. };
  22397. /**
  22398. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22399. * @returns a Matrix
  22400. */
  22401. Camera.prototype.getTransformationMatrix = function () {
  22402. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22403. return this._transformMatrix;
  22404. };
  22405. Camera.prototype.updateFrustumPlanes = function () {
  22406. if (!this._refreshFrustumPlanes) {
  22407. return;
  22408. }
  22409. this.getTransformationMatrix();
  22410. if (!this._frustumPlanes) {
  22411. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22412. }
  22413. else {
  22414. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22415. }
  22416. this._refreshFrustumPlanes = false;
  22417. };
  22418. Camera.prototype.isInFrustum = function (target) {
  22419. this.updateFrustumPlanes();
  22420. return target.isInFrustum(this._frustumPlanes);
  22421. };
  22422. Camera.prototype.isCompletelyInFrustum = function (target) {
  22423. this.updateFrustumPlanes();
  22424. return target.isCompletelyInFrustum(this._frustumPlanes);
  22425. };
  22426. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22427. if (length === void 0) { length = 100; }
  22428. if (!transform) {
  22429. transform = this.getWorldMatrix();
  22430. }
  22431. if (!origin) {
  22432. origin = this.position;
  22433. }
  22434. var forward = new BABYLON.Vector3(0, 0, 1);
  22435. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22436. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22437. return new BABYLON.Ray(origin, direction, length);
  22438. };
  22439. /**
  22440. * Releases resources associated with this node.
  22441. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22442. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22443. */
  22444. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22445. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22446. // Observables
  22447. this.onViewMatrixChangedObservable.clear();
  22448. this.onProjectionMatrixChangedObservable.clear();
  22449. this.onAfterCheckInputsObservable.clear();
  22450. this.onRestoreStateObservable.clear();
  22451. // Inputs
  22452. if (this.inputs) {
  22453. this.inputs.clear();
  22454. }
  22455. // Animations
  22456. this.getScene().stopAnimation(this);
  22457. // Remove from scene
  22458. this.getScene().removeCamera(this);
  22459. while (this._rigCameras.length > 0) {
  22460. var camera = this._rigCameras.pop();
  22461. if (camera) {
  22462. camera.dispose();
  22463. }
  22464. }
  22465. // Postprocesses
  22466. if (this._rigPostProcess) {
  22467. this._rigPostProcess.dispose(this);
  22468. this._rigPostProcess = null;
  22469. this._postProcesses = [];
  22470. }
  22471. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22472. this._rigPostProcess = null;
  22473. this._postProcesses = [];
  22474. }
  22475. else {
  22476. var i = this._postProcesses.length;
  22477. while (--i >= 0) {
  22478. var postProcess = this._postProcesses[i];
  22479. if (postProcess) {
  22480. postProcess.dispose(this);
  22481. }
  22482. }
  22483. }
  22484. // Render targets
  22485. var i = this.customRenderTargets.length;
  22486. while (--i >= 0) {
  22487. this.customRenderTargets[i].dispose();
  22488. }
  22489. this.customRenderTargets = [];
  22490. // Active Meshes
  22491. this._activeMeshes.dispose();
  22492. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22493. };
  22494. Object.defineProperty(Camera.prototype, "leftCamera", {
  22495. // ---- Camera rigs section ----
  22496. get: function () {
  22497. if (this._rigCameras.length < 1) {
  22498. return null;
  22499. }
  22500. return this._rigCameras[0];
  22501. },
  22502. enumerable: true,
  22503. configurable: true
  22504. });
  22505. Object.defineProperty(Camera.prototype, "rightCamera", {
  22506. get: function () {
  22507. if (this._rigCameras.length < 2) {
  22508. return null;
  22509. }
  22510. return this._rigCameras[1];
  22511. },
  22512. enumerable: true,
  22513. configurable: true
  22514. });
  22515. Camera.prototype.getLeftTarget = function () {
  22516. if (this._rigCameras.length < 1) {
  22517. return null;
  22518. }
  22519. return this._rigCameras[0].getTarget();
  22520. };
  22521. Camera.prototype.getRightTarget = function () {
  22522. if (this._rigCameras.length < 2) {
  22523. return null;
  22524. }
  22525. return this._rigCameras[1].getTarget();
  22526. };
  22527. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22528. if (this.cameraRigMode === mode) {
  22529. return;
  22530. }
  22531. while (this._rigCameras.length > 0) {
  22532. var camera = this._rigCameras.pop();
  22533. if (camera) {
  22534. camera.dispose();
  22535. }
  22536. }
  22537. this.cameraRigMode = mode;
  22538. this._cameraRigParams = {};
  22539. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22540. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22541. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22542. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22543. // create the rig cameras, unless none
  22544. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22545. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22546. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22547. if (leftCamera && rightCamera) {
  22548. this._rigCameras.push(leftCamera);
  22549. this._rigCameras.push(rightCamera);
  22550. }
  22551. }
  22552. switch (this.cameraRigMode) {
  22553. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22554. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22555. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22556. break;
  22557. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22558. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22559. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22560. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22561. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22562. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22563. break;
  22564. case Camera.RIG_MODE_VR:
  22565. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22566. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22567. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22568. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22569. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22570. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22571. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22572. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22573. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22574. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22575. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22576. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22577. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22578. if (metrics.compensateDistortion) {
  22579. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22580. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22581. }
  22582. break;
  22583. case Camera.RIG_MODE_WEBVR:
  22584. if (rigParams.vrDisplay) {
  22585. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22586. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22587. //Left eye
  22588. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22589. this._rigCameras[0].setCameraRigParameter("left", true);
  22590. //leaving this for future reference
  22591. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22592. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22593. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22594. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22595. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22596. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22597. this._rigCameras[0].parent = this;
  22598. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22599. //Right eye
  22600. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22601. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22602. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22603. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22604. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22605. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22606. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22607. this._rigCameras[1].parent = this;
  22608. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22609. if (Camera.UseAlternateWebVRRendering) {
  22610. this._rigCameras[1]._skipRendering = true;
  22611. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22612. }
  22613. }
  22614. break;
  22615. }
  22616. this._cascadePostProcessesToRigCams();
  22617. this.update();
  22618. };
  22619. Camera.prototype._getVRProjectionMatrix = function () {
  22620. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22621. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22622. return this._projectionMatrix;
  22623. };
  22624. Camera.prototype._updateCameraRotationMatrix = function () {
  22625. //Here for WebVR
  22626. };
  22627. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22628. //Here for WebVR
  22629. };
  22630. /**
  22631. * This function MUST be overwritten by the different WebVR cameras available.
  22632. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22633. */
  22634. Camera.prototype._getWebVRProjectionMatrix = function () {
  22635. return BABYLON.Matrix.Identity();
  22636. };
  22637. /**
  22638. * This function MUST be overwritten by the different WebVR cameras available.
  22639. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22640. */
  22641. Camera.prototype._getWebVRViewMatrix = function () {
  22642. return BABYLON.Matrix.Identity();
  22643. };
  22644. Camera.prototype.setCameraRigParameter = function (name, value) {
  22645. if (!this._cameraRigParams) {
  22646. this._cameraRigParams = {};
  22647. }
  22648. this._cameraRigParams[name] = value;
  22649. //provisionnally:
  22650. if (name === "interaxialDistance") {
  22651. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22652. }
  22653. };
  22654. /**
  22655. * needs to be overridden by children so sub has required properties to be copied
  22656. */
  22657. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22658. return null;
  22659. };
  22660. /**
  22661. * May need to be overridden by children
  22662. */
  22663. Camera.prototype._updateRigCameras = function () {
  22664. for (var i = 0; i < this._rigCameras.length; i++) {
  22665. this._rigCameras[i].minZ = this.minZ;
  22666. this._rigCameras[i].maxZ = this.maxZ;
  22667. this._rigCameras[i].fov = this.fov;
  22668. }
  22669. // only update viewport when ANAGLYPH
  22670. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22671. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22672. }
  22673. };
  22674. Camera.prototype._setupInputs = function () {
  22675. };
  22676. Camera.prototype.serialize = function () {
  22677. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22678. // Type
  22679. serializationObject.type = this.getClassName();
  22680. // Parent
  22681. if (this.parent) {
  22682. serializationObject.parentId = this.parent.id;
  22683. }
  22684. if (this.inputs) {
  22685. this.inputs.serialize(serializationObject);
  22686. }
  22687. // Animations
  22688. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22689. serializationObject.ranges = this.serializeAnimationRanges();
  22690. return serializationObject;
  22691. };
  22692. Camera.prototype.clone = function (name) {
  22693. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22694. };
  22695. Camera.prototype.getDirection = function (localAxis) {
  22696. var result = BABYLON.Vector3.Zero();
  22697. this.getDirectionToRef(localAxis, result);
  22698. return result;
  22699. };
  22700. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22701. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22702. };
  22703. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22704. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22705. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22706. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22707. interaxial_distance: interaxial_distance,
  22708. isStereoscopicSideBySide: isStereoscopicSideBySide
  22709. });
  22710. if (constructorFunc) {
  22711. return constructorFunc;
  22712. }
  22713. // Default to universal camera
  22714. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22715. };
  22716. Camera.prototype.computeWorldMatrix = function () {
  22717. return this.getWorldMatrix();
  22718. };
  22719. Camera.Parse = function (parsedCamera, scene) {
  22720. var type = parsedCamera.type;
  22721. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22722. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22723. // Parent
  22724. if (parsedCamera.parentId) {
  22725. camera._waitingParentId = parsedCamera.parentId;
  22726. }
  22727. //If camera has an input manager, let it parse inputs settings
  22728. if (camera.inputs) {
  22729. camera.inputs.parse(parsedCamera);
  22730. camera._setupInputs();
  22731. }
  22732. if (camera.setPosition) { // need to force position
  22733. camera.position.copyFromFloats(0, 0, 0);
  22734. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22735. }
  22736. // Target
  22737. if (parsedCamera.target) {
  22738. if (camera.setTarget) {
  22739. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22740. }
  22741. }
  22742. // Apply 3d rig, when found
  22743. if (parsedCamera.cameraRigMode) {
  22744. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22745. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22746. }
  22747. // Animations
  22748. if (parsedCamera.animations) {
  22749. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22750. var parsedAnimation = parsedCamera.animations[animationIndex];
  22751. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22752. }
  22753. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22754. }
  22755. if (parsedCamera.autoAnimate) {
  22756. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22757. }
  22758. return camera;
  22759. };
  22760. // Statics
  22761. Camera._PERSPECTIVE_CAMERA = 0;
  22762. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22763. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22764. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22765. Camera._RIG_MODE_NONE = 0;
  22766. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22767. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22768. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22769. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22770. Camera._RIG_MODE_VR = 20;
  22771. Camera._RIG_MODE_WEBVR = 21;
  22772. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22773. Camera.UseAlternateWebVRRendering = false;
  22774. __decorate([
  22775. BABYLON.serializeAsVector3()
  22776. ], Camera.prototype, "position", void 0);
  22777. __decorate([
  22778. BABYLON.serializeAsVector3()
  22779. ], Camera.prototype, "upVector", void 0);
  22780. __decorate([
  22781. BABYLON.serialize()
  22782. ], Camera.prototype, "orthoLeft", void 0);
  22783. __decorate([
  22784. BABYLON.serialize()
  22785. ], Camera.prototype, "orthoRight", void 0);
  22786. __decorate([
  22787. BABYLON.serialize()
  22788. ], Camera.prototype, "orthoBottom", void 0);
  22789. __decorate([
  22790. BABYLON.serialize()
  22791. ], Camera.prototype, "orthoTop", void 0);
  22792. __decorate([
  22793. BABYLON.serialize()
  22794. ], Camera.prototype, "fov", void 0);
  22795. __decorate([
  22796. BABYLON.serialize()
  22797. ], Camera.prototype, "minZ", void 0);
  22798. __decorate([
  22799. BABYLON.serialize()
  22800. ], Camera.prototype, "maxZ", void 0);
  22801. __decorate([
  22802. BABYLON.serialize()
  22803. ], Camera.prototype, "inertia", void 0);
  22804. __decorate([
  22805. BABYLON.serialize()
  22806. ], Camera.prototype, "mode", void 0);
  22807. __decorate([
  22808. BABYLON.serialize()
  22809. ], Camera.prototype, "layerMask", void 0);
  22810. __decorate([
  22811. BABYLON.serialize()
  22812. ], Camera.prototype, "fovMode", void 0);
  22813. __decorate([
  22814. BABYLON.serialize()
  22815. ], Camera.prototype, "cameraRigMode", void 0);
  22816. __decorate([
  22817. BABYLON.serialize()
  22818. ], Camera.prototype, "interaxialDistance", void 0);
  22819. __decorate([
  22820. BABYLON.serialize()
  22821. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22822. return Camera;
  22823. }(BABYLON.Node));
  22824. BABYLON.Camera = Camera;
  22825. })(BABYLON || (BABYLON = {}));
  22826. //# sourceMappingURL=babylon.camera.js.map
  22827. var BABYLON;
  22828. (function (BABYLON) {
  22829. var RenderingManager = /** @class */ (function () {
  22830. function RenderingManager(scene) {
  22831. /**
  22832. * Hidden
  22833. */
  22834. this._useSceneAutoClearSetup = false;
  22835. this._renderingGroups = new Array();
  22836. this._autoClearDepthStencil = {};
  22837. this._customOpaqueSortCompareFn = {};
  22838. this._customAlphaTestSortCompareFn = {};
  22839. this._customTransparentSortCompareFn = {};
  22840. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  22841. this._scene = scene;
  22842. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22843. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22844. }
  22845. }
  22846. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22847. if (depth === void 0) { depth = true; }
  22848. if (stencil === void 0) { stencil = true; }
  22849. if (this._depthStencilBufferAlreadyCleaned) {
  22850. return;
  22851. }
  22852. this._scene.getEngine().clear(null, false, depth, stencil);
  22853. this._depthStencilBufferAlreadyCleaned = true;
  22854. };
  22855. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22856. // Update the observable context (not null as it only goes away on dispose)
  22857. var info = this._renderingGroupInfo;
  22858. info.scene = this._scene;
  22859. info.camera = this._scene.activeCamera;
  22860. // Dispatch sprites
  22861. if (renderSprites) {
  22862. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22863. var manager = this._scene.spriteManagers[index];
  22864. this.dispatchSprites(manager);
  22865. }
  22866. }
  22867. // Render
  22868. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22869. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22870. var renderingGroup = this._renderingGroups[index];
  22871. if (!renderingGroup)
  22872. continue;
  22873. var renderingGroupMask = Math.pow(2, index);
  22874. info.renderingGroupId = index;
  22875. // Before Observable
  22876. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22877. // Clear depth/stencil if needed
  22878. if (RenderingManager.AUTOCLEAR) {
  22879. var autoClear = this._useSceneAutoClearSetup ?
  22880. this._scene.getAutoClearDepthStencilSetup(index) :
  22881. this._autoClearDepthStencil[index];
  22882. if (autoClear && autoClear.autoClear) {
  22883. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22884. }
  22885. }
  22886. // Render
  22887. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  22888. var step = _a[_i];
  22889. step.action(index);
  22890. }
  22891. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22892. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  22893. var step = _c[_b];
  22894. step.action(index);
  22895. }
  22896. // After Observable
  22897. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22898. }
  22899. };
  22900. RenderingManager.prototype.reset = function () {
  22901. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22902. var renderingGroup = this._renderingGroups[index];
  22903. if (renderingGroup) {
  22904. renderingGroup.prepare();
  22905. }
  22906. }
  22907. };
  22908. RenderingManager.prototype.dispose = function () {
  22909. this.freeRenderingGroups();
  22910. this._renderingGroups.length = 0;
  22911. this._renderingGroupInfo = null;
  22912. };
  22913. /**
  22914. * Clear the info related to rendering groups preventing retention points during dispose.
  22915. */
  22916. RenderingManager.prototype.freeRenderingGroups = function () {
  22917. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22918. var renderingGroup = this._renderingGroups[index];
  22919. if (renderingGroup) {
  22920. renderingGroup.dispose();
  22921. }
  22922. }
  22923. };
  22924. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22925. if (this._renderingGroups[renderingGroupId] === undefined) {
  22926. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22927. }
  22928. };
  22929. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22930. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22931. this._prepareRenderingGroup(renderingGroupId);
  22932. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22933. };
  22934. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22935. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22936. this._prepareRenderingGroup(renderingGroupId);
  22937. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22938. };
  22939. /**
  22940. * @param subMesh The submesh to dispatch
  22941. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22942. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22943. */
  22944. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22945. if (mesh === undefined) {
  22946. mesh = subMesh.getMesh();
  22947. }
  22948. var renderingGroupId = mesh.renderingGroupId || 0;
  22949. this._prepareRenderingGroup(renderingGroupId);
  22950. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22951. };
  22952. /**
  22953. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22954. * This allowed control for front to back rendering or reversly depending of the special needs.
  22955. *
  22956. * @param renderingGroupId The rendering group id corresponding to its index
  22957. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22958. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22959. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22960. */
  22961. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22962. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22963. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22964. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22965. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22966. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22967. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22968. if (this._renderingGroups[renderingGroupId]) {
  22969. var group = this._renderingGroups[renderingGroupId];
  22970. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22971. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22972. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22973. }
  22974. };
  22975. /**
  22976. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22977. *
  22978. * @param renderingGroupId The rendering group id corresponding to its index
  22979. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22980. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22981. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22982. */
  22983. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22984. if (depth === void 0) { depth = true; }
  22985. if (stencil === void 0) { stencil = true; }
  22986. this._autoClearDepthStencil[renderingGroupId] = {
  22987. autoClear: autoClearDepthStencil,
  22988. depth: depth,
  22989. stencil: stencil
  22990. };
  22991. };
  22992. /**
  22993. * Gets the current auto clear configuration for one rendering group of the rendering
  22994. * manager.
  22995. * @param index the rendering group index to get the information for
  22996. * @returns The auto clear setup for the requested rendering group
  22997. */
  22998. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  22999. return this._autoClearDepthStencil[index];
  23000. };
  23001. /**
  23002. * The max id used for rendering groups (not included)
  23003. */
  23004. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23005. /**
  23006. * The min id used for rendering groups (included)
  23007. */
  23008. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23009. /**
  23010. * Used to globally prevent autoclearing scenes.
  23011. */
  23012. RenderingManager.AUTOCLEAR = true;
  23013. return RenderingManager;
  23014. }());
  23015. BABYLON.RenderingManager = RenderingManager;
  23016. })(BABYLON || (BABYLON = {}));
  23017. //# sourceMappingURL=babylon.renderingManager.js.map
  23018. var BABYLON;
  23019. (function (BABYLON) {
  23020. var RenderingGroup = /** @class */ (function () {
  23021. /**
  23022. * Creates a new rendering group.
  23023. * @param index The rendering group index
  23024. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23025. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23026. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23027. */
  23028. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23029. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23030. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23031. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23032. this.index = index;
  23033. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23034. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23035. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23036. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23037. this._particleSystems = new BABYLON.SmartArray(256);
  23038. this._spriteManagers = new BABYLON.SmartArray(256);
  23039. this._edgesRenderers = new BABYLON.SmartArray(16);
  23040. this._scene = scene;
  23041. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23042. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23043. this.transparentSortCompareFn = transparentSortCompareFn;
  23044. }
  23045. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23046. /**
  23047. * Set the opaque sort comparison function.
  23048. * If null the sub meshes will be render in the order they were created
  23049. */
  23050. set: function (value) {
  23051. this._opaqueSortCompareFn = value;
  23052. if (value) {
  23053. this._renderOpaque = this.renderOpaqueSorted;
  23054. }
  23055. else {
  23056. this._renderOpaque = RenderingGroup.renderUnsorted;
  23057. }
  23058. },
  23059. enumerable: true,
  23060. configurable: true
  23061. });
  23062. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23063. /**
  23064. * Set the alpha test sort comparison function.
  23065. * If null the sub meshes will be render in the order they were created
  23066. */
  23067. set: function (value) {
  23068. this._alphaTestSortCompareFn = value;
  23069. if (value) {
  23070. this._renderAlphaTest = this.renderAlphaTestSorted;
  23071. }
  23072. else {
  23073. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23074. }
  23075. },
  23076. enumerable: true,
  23077. configurable: true
  23078. });
  23079. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23080. /**
  23081. * Set the transparent sort comparison function.
  23082. * If null the sub meshes will be render in the order they were created
  23083. */
  23084. set: function (value) {
  23085. if (value) {
  23086. this._transparentSortCompareFn = value;
  23087. }
  23088. else {
  23089. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23090. }
  23091. this._renderTransparent = this.renderTransparentSorted;
  23092. },
  23093. enumerable: true,
  23094. configurable: true
  23095. });
  23096. /**
  23097. * Render all the sub meshes contained in the group.
  23098. * @param customRenderFunction Used to override the default render behaviour of the group.
  23099. * @returns true if rendered some submeshes.
  23100. */
  23101. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23102. if (customRenderFunction) {
  23103. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23104. return;
  23105. }
  23106. var engine = this._scene.getEngine();
  23107. // Depth only
  23108. if (this._depthOnlySubMeshes.length !== 0) {
  23109. engine.setColorWrite(false);
  23110. this._renderAlphaTest(this._depthOnlySubMeshes);
  23111. engine.setColorWrite(true);
  23112. }
  23113. // Opaque
  23114. if (this._opaqueSubMeshes.length !== 0) {
  23115. this._renderOpaque(this._opaqueSubMeshes);
  23116. }
  23117. // Alpha test
  23118. if (this._alphaTestSubMeshes.length !== 0) {
  23119. this._renderAlphaTest(this._alphaTestSubMeshes);
  23120. }
  23121. var stencilState = engine.getStencilBuffer();
  23122. engine.setStencilBuffer(false);
  23123. // Sprites
  23124. if (renderSprites) {
  23125. this._renderSprites();
  23126. }
  23127. // Particles
  23128. if (renderParticles) {
  23129. this._renderParticles(activeMeshes);
  23130. }
  23131. if (this.onBeforeTransparentRendering) {
  23132. this.onBeforeTransparentRendering();
  23133. }
  23134. // Transparent
  23135. if (this._transparentSubMeshes.length !== 0) {
  23136. this._renderTransparent(this._transparentSubMeshes);
  23137. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23138. }
  23139. // Set back stencil to false in case it changes before the edge renderer.
  23140. engine.setStencilBuffer(false);
  23141. // Edges
  23142. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23143. this._edgesRenderers.data[edgesRendererIndex].render();
  23144. }
  23145. // Restore Stencil state.
  23146. engine.setStencilBuffer(stencilState);
  23147. };
  23148. /**
  23149. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23150. * @param subMeshes The submeshes to render
  23151. */
  23152. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23153. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23154. };
  23155. /**
  23156. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23157. * @param subMeshes The submeshes to render
  23158. */
  23159. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23160. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23161. };
  23162. /**
  23163. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23164. * @param subMeshes The submeshes to render
  23165. */
  23166. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23167. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23168. };
  23169. /**
  23170. * Renders the submeshes in a specified order.
  23171. * @param subMeshes The submeshes to sort before render
  23172. * @param sortCompareFn The comparison function use to sort
  23173. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23174. * @param transparent Specifies to activate blending if true
  23175. */
  23176. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23177. var subIndex = 0;
  23178. var subMesh;
  23179. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23180. for (; subIndex < subMeshes.length; subIndex++) {
  23181. subMesh = subMeshes.data[subIndex];
  23182. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23183. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23184. }
  23185. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23186. if (sortCompareFn) {
  23187. sortedArray.sort(sortCompareFn);
  23188. }
  23189. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23190. subMesh = sortedArray[subIndex];
  23191. if (transparent) {
  23192. var material = subMesh.getMaterial();
  23193. if (material && material.needDepthPrePass) {
  23194. var engine = material.getScene().getEngine();
  23195. engine.setColorWrite(false);
  23196. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23197. subMesh.render(false);
  23198. engine.setColorWrite(true);
  23199. }
  23200. }
  23201. subMesh.render(transparent);
  23202. }
  23203. };
  23204. /**
  23205. * Renders the submeshes in the order they were dispatched (no sort applied).
  23206. * @param subMeshes The submeshes to render
  23207. */
  23208. RenderingGroup.renderUnsorted = function (subMeshes) {
  23209. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23210. var submesh = subMeshes.data[subIndex];
  23211. submesh.render(false);
  23212. }
  23213. };
  23214. /**
  23215. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23216. * are rendered back to front if in the same alpha index.
  23217. *
  23218. * @param a The first submesh
  23219. * @param b The second submesh
  23220. * @returns The result of the comparison
  23221. */
  23222. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23223. // Alpha index first
  23224. if (a._alphaIndex > b._alphaIndex) {
  23225. return 1;
  23226. }
  23227. if (a._alphaIndex < b._alphaIndex) {
  23228. return -1;
  23229. }
  23230. // Then distance to camera
  23231. return RenderingGroup.backToFrontSortCompare(a, b);
  23232. };
  23233. /**
  23234. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23235. * are rendered back to front.
  23236. *
  23237. * @param a The first submesh
  23238. * @param b The second submesh
  23239. * @returns The result of the comparison
  23240. */
  23241. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23242. // Then distance to camera
  23243. if (a._distanceToCamera < b._distanceToCamera) {
  23244. return 1;
  23245. }
  23246. if (a._distanceToCamera > b._distanceToCamera) {
  23247. return -1;
  23248. }
  23249. return 0;
  23250. };
  23251. /**
  23252. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23253. * are rendered front to back (prevent overdraw).
  23254. *
  23255. * @param a The first submesh
  23256. * @param b The second submesh
  23257. * @returns The result of the comparison
  23258. */
  23259. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23260. // Then distance to camera
  23261. if (a._distanceToCamera < b._distanceToCamera) {
  23262. return -1;
  23263. }
  23264. if (a._distanceToCamera > b._distanceToCamera) {
  23265. return 1;
  23266. }
  23267. return 0;
  23268. };
  23269. /**
  23270. * Resets the different lists of submeshes to prepare a new frame.
  23271. */
  23272. RenderingGroup.prototype.prepare = function () {
  23273. this._opaqueSubMeshes.reset();
  23274. this._transparentSubMeshes.reset();
  23275. this._alphaTestSubMeshes.reset();
  23276. this._depthOnlySubMeshes.reset();
  23277. this._particleSystems.reset();
  23278. this._spriteManagers.reset();
  23279. this._edgesRenderers.reset();
  23280. };
  23281. RenderingGroup.prototype.dispose = function () {
  23282. this._opaqueSubMeshes.dispose();
  23283. this._transparentSubMeshes.dispose();
  23284. this._alphaTestSubMeshes.dispose();
  23285. this._depthOnlySubMeshes.dispose();
  23286. this._particleSystems.dispose();
  23287. this._spriteManagers.dispose();
  23288. this._edgesRenderers.dispose();
  23289. };
  23290. /**
  23291. * Inserts the submesh in its correct queue depending on its material.
  23292. * @param subMesh The submesh to dispatch
  23293. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23294. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23295. */
  23296. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23297. // Get mesh and materials if not provided
  23298. if (mesh === undefined) {
  23299. mesh = subMesh.getMesh();
  23300. }
  23301. if (material === undefined) {
  23302. material = subMesh.getMaterial();
  23303. }
  23304. if (material === null || material === undefined) {
  23305. return;
  23306. }
  23307. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23308. this._transparentSubMeshes.push(subMesh);
  23309. }
  23310. else if (material.needAlphaTesting()) { // Alpha test
  23311. if (material.needDepthPrePass) {
  23312. this._depthOnlySubMeshes.push(subMesh);
  23313. }
  23314. this._alphaTestSubMeshes.push(subMesh);
  23315. }
  23316. else {
  23317. if (material.needDepthPrePass) {
  23318. this._depthOnlySubMeshes.push(subMesh);
  23319. }
  23320. this._opaqueSubMeshes.push(subMesh); // Opaque
  23321. }
  23322. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23323. this._edgesRenderers.push(mesh._edgesRenderer);
  23324. }
  23325. };
  23326. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23327. this._spriteManagers.push(spriteManager);
  23328. };
  23329. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23330. this._particleSystems.push(particleSystem);
  23331. };
  23332. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23333. if (this._particleSystems.length === 0) {
  23334. return;
  23335. }
  23336. // Particles
  23337. var activeCamera = this._scene.activeCamera;
  23338. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23339. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23340. var particleSystem = this._particleSystems.data[particleIndex];
  23341. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23342. continue;
  23343. }
  23344. var emitter = particleSystem.emitter;
  23345. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23346. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23347. }
  23348. }
  23349. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23350. };
  23351. RenderingGroup.prototype._renderSprites = function () {
  23352. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23353. return;
  23354. }
  23355. // Sprites
  23356. var activeCamera = this._scene.activeCamera;
  23357. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23358. for (var id = 0; id < this._spriteManagers.length; id++) {
  23359. var spriteManager = this._spriteManagers.data[id];
  23360. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23361. spriteManager.render();
  23362. }
  23363. }
  23364. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23365. };
  23366. return RenderingGroup;
  23367. }());
  23368. BABYLON.RenderingGroup = RenderingGroup;
  23369. })(BABYLON || (BABYLON = {}));
  23370. //# sourceMappingURL=babylon.renderingGroup.js.map
  23371. var BABYLON;
  23372. (function (BABYLON) {
  23373. /**
  23374. * Groups all the scene component constants in one place to ease maintenance.
  23375. * @hidden
  23376. */
  23377. var SceneComponentConstants = /** @class */ (function () {
  23378. function SceneComponentConstants() {
  23379. }
  23380. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23381. SceneComponentConstants.NAME_LAYER = "Layer";
  23382. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23383. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23384. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23385. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23386. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23387. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23388. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23389. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23390. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23391. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23392. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23393. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23394. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23395. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23396. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23397. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23398. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23399. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23400. return SceneComponentConstants;
  23401. }());
  23402. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23403. /**
  23404. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23405. * @hidden
  23406. */
  23407. var Stage = /** @class */ (function (_super) {
  23408. __extends(Stage, _super);
  23409. /**
  23410. * Hide ctor from the rest of the world.
  23411. * @param items The items to add.
  23412. */
  23413. function Stage(items) {
  23414. return _super.apply(this, items) || this;
  23415. }
  23416. /**
  23417. * Creates a new Stage.
  23418. * @returns A new instance of a Stage
  23419. */
  23420. Stage.Create = function () {
  23421. return Object.create(Stage.prototype);
  23422. };
  23423. /**
  23424. * Registers a step in an ordered way in the targeted stage.
  23425. * @param index Defines the position to register the step in
  23426. * @param component Defines the component attached to the step
  23427. * @param action Defines the action to launch during the step
  23428. */
  23429. Stage.prototype.registerStep = function (index, component, action) {
  23430. var i = 0;
  23431. var maxIndex = Number.MAX_VALUE;
  23432. for (; i < this.length && i < maxIndex; i++) {
  23433. var step = this[i];
  23434. maxIndex = step.index;
  23435. }
  23436. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23437. };
  23438. /**
  23439. * Clears all the steps from the stage.
  23440. */
  23441. Stage.prototype.clear = function () {
  23442. this.length = 0;
  23443. };
  23444. return Stage;
  23445. }(Array));
  23446. BABYLON.Stage = Stage;
  23447. })(BABYLON || (BABYLON = {}));
  23448. //# sourceMappingURL=babylon.sceneComponent.js.map
  23449. var BABYLON;
  23450. (function (BABYLON) {
  23451. /**
  23452. * Base class of the scene acting as a container for the different elements composing a scene.
  23453. * This class is dynamically extended by the different components of the scene increasing
  23454. * flexibility and reducing coupling
  23455. */
  23456. var AbstractScene = /** @class */ (function () {
  23457. function AbstractScene() {
  23458. /** All of the cameras added to this scene
  23459. * @see http://doc.babylonjs.com/babylon101/cameras
  23460. */
  23461. this.cameras = new Array();
  23462. /**
  23463. * All of the lights added to this scene
  23464. * @see http://doc.babylonjs.com/babylon101/lights
  23465. */
  23466. this.lights = new Array();
  23467. /**
  23468. * All of the (abstract) meshes added to this scene
  23469. */
  23470. this.meshes = new Array();
  23471. /**
  23472. * The list of skeletons added to the scene
  23473. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23474. */
  23475. this.skeletons = new Array();
  23476. /**
  23477. * All of the particle systems added to this scene
  23478. * @see http://doc.babylonjs.com/babylon101/particles
  23479. */
  23480. this.particleSystems = new Array();
  23481. /**
  23482. * Gets a list of Animations associated with the scene
  23483. */
  23484. this.animations = [];
  23485. /**
  23486. * All of the animation groups added to this scene
  23487. * @see http://doc.babylonjs.com/how_to/group
  23488. */
  23489. this.animationGroups = new Array();
  23490. /**
  23491. * All of the multi-materials added to this scene
  23492. * @see http://doc.babylonjs.com/how_to/multi_materials
  23493. */
  23494. this.multiMaterials = new Array();
  23495. /**
  23496. * All of the materials added to this scene
  23497. * @see http://doc.babylonjs.com/babylon101/materials
  23498. */
  23499. this.materials = new Array();
  23500. /**
  23501. * The list of morph target managers added to the scene
  23502. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23503. */
  23504. this.morphTargetManagers = new Array();
  23505. /**
  23506. * The list of geometries used in the scene.
  23507. */
  23508. this.geometries = new Array();
  23509. /**
  23510. * All of the tranform nodes added to this scene
  23511. * @see http://doc.babylonjs.com/how_to/transformnode
  23512. */
  23513. this.transformNodes = new Array();
  23514. /**
  23515. * ActionManagers available on the scene.
  23516. */
  23517. this.actionManagers = new Array();
  23518. /**
  23519. * Sounds to keep.
  23520. */
  23521. this.sounds = new Array();
  23522. /**
  23523. * Textures to keep.
  23524. */
  23525. this.textures = new Array();
  23526. }
  23527. /**
  23528. * Adds a parser in the list of available ones
  23529. * @param name Defines the name of the parser
  23530. * @param parser Defines the parser to add
  23531. */
  23532. AbstractScene.AddParser = function (name, parser) {
  23533. this._BabylonFileParsers[name] = parser;
  23534. };
  23535. /**
  23536. * Gets a general parser from the list of avaialble ones
  23537. * @param name Defines the name of the parser
  23538. * @returns the requested parser or null
  23539. */
  23540. AbstractScene.GetParser = function (name) {
  23541. if (this._BabylonFileParsers[name]) {
  23542. return this._BabylonFileParsers[name];
  23543. }
  23544. return null;
  23545. };
  23546. /**
  23547. * Adds n individual parser in the list of available ones
  23548. * @param name Defines the name of the parser
  23549. * @param parser Defines the parser to add
  23550. */
  23551. AbstractScene.AddIndividualParser = function (name, parser) {
  23552. this._IndividualBabylonFileParsers[name] = parser;
  23553. };
  23554. /**
  23555. * Gets an individual parser from the list of avaialble ones
  23556. * @param name Defines the name of the parser
  23557. * @returns the requested parser or null
  23558. */
  23559. AbstractScene.GetIndividualParser = function (name) {
  23560. if (this._IndividualBabylonFileParsers[name]) {
  23561. return this._IndividualBabylonFileParsers[name];
  23562. }
  23563. return null;
  23564. };
  23565. /**
  23566. * Parser json data and populate both a scene and its associated container object
  23567. * @param jsonData Defines the data to parse
  23568. * @param scene Defines the scene to parse the data for
  23569. * @param container Defines the container attached to the parsing sequence
  23570. * @param rootUrl Defines the root url of the data
  23571. */
  23572. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23573. for (var parserName in this._BabylonFileParsers) {
  23574. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23575. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23576. }
  23577. }
  23578. };
  23579. /**
  23580. * Stores the list of available parsers in the application.
  23581. */
  23582. AbstractScene._BabylonFileParsers = {};
  23583. /**
  23584. * Stores the list of available individual parsers in the application.
  23585. */
  23586. AbstractScene._IndividualBabylonFileParsers = {};
  23587. return AbstractScene;
  23588. }());
  23589. BABYLON.AbstractScene = AbstractScene;
  23590. })(BABYLON || (BABYLON = {}));
  23591. //# sourceMappingURL=babylon.abstractScene.js.map
  23592. var BABYLON;
  23593. (function (BABYLON) {
  23594. /** @hidden */
  23595. var ClickInfo = /** @class */ (function () {
  23596. function ClickInfo() {
  23597. this._singleClick = false;
  23598. this._doubleClick = false;
  23599. this._hasSwiped = false;
  23600. this._ignore = false;
  23601. }
  23602. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23603. get: function () {
  23604. return this._singleClick;
  23605. },
  23606. set: function (b) {
  23607. this._singleClick = b;
  23608. },
  23609. enumerable: true,
  23610. configurable: true
  23611. });
  23612. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23613. get: function () {
  23614. return this._doubleClick;
  23615. },
  23616. set: function (b) {
  23617. this._doubleClick = b;
  23618. },
  23619. enumerable: true,
  23620. configurable: true
  23621. });
  23622. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23623. get: function () {
  23624. return this._hasSwiped;
  23625. },
  23626. set: function (b) {
  23627. this._hasSwiped = b;
  23628. },
  23629. enumerable: true,
  23630. configurable: true
  23631. });
  23632. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23633. get: function () {
  23634. return this._ignore;
  23635. },
  23636. set: function (b) {
  23637. this._ignore = b;
  23638. },
  23639. enumerable: true,
  23640. configurable: true
  23641. });
  23642. return ClickInfo;
  23643. }());
  23644. /**
  23645. * This class is used by the onRenderingGroupObservable
  23646. */
  23647. var RenderingGroupInfo = /** @class */ (function () {
  23648. function RenderingGroupInfo() {
  23649. }
  23650. return RenderingGroupInfo;
  23651. }());
  23652. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23653. /**
  23654. * Represents a scene to be rendered by the engine.
  23655. * @see http://doc.babylonjs.com/features/scene
  23656. */
  23657. var Scene = /** @class */ (function (_super) {
  23658. __extends(Scene, _super);
  23659. /**
  23660. * Creates a new Scene
  23661. * @param engine defines the engine to use to render this scene
  23662. */
  23663. function Scene(engine) {
  23664. var _this = _super.call(this) || this;
  23665. // Members
  23666. /**
  23667. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23668. */
  23669. _this.autoClear = true;
  23670. /**
  23671. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23672. */
  23673. _this.autoClearDepthAndStencil = true;
  23674. /**
  23675. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23676. */
  23677. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23678. /**
  23679. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23680. */
  23681. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23682. _this._forceWireframe = false;
  23683. _this._forcePointsCloud = false;
  23684. /**
  23685. * Gets or sets a boolean indicating if animations are enabled
  23686. */
  23687. _this.animationsEnabled = true;
  23688. _this._animationPropertiesOverride = null;
  23689. /**
  23690. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23691. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23692. */
  23693. _this.useConstantAnimationDeltaTime = false;
  23694. /**
  23695. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23696. * Please note that it requires to run a ray cast through the scene on every frame
  23697. */
  23698. _this.constantlyUpdateMeshUnderPointer = false;
  23699. /**
  23700. * Defines the HTML cursor to use when hovering over interactive elements
  23701. */
  23702. _this.hoverCursor = "pointer";
  23703. /**
  23704. * Defines the HTML default cursor to use (empty by default)
  23705. */
  23706. _this.defaultCursor = "";
  23707. /**
  23708. * This is used to call preventDefault() on pointer down
  23709. * in order to block unwanted artifacts like system double clicks
  23710. */
  23711. _this.preventDefaultOnPointerDown = true;
  23712. // Metadata
  23713. /**
  23714. * Gets or sets user defined metadata
  23715. */
  23716. _this.metadata = null;
  23717. /**
  23718. * Use this array to add regular expressions used to disable offline support for specific urls
  23719. */
  23720. _this.disableOfflineSupportExceptionRules = new Array();
  23721. /**
  23722. * An event triggered when the scene is disposed.
  23723. */
  23724. _this.onDisposeObservable = new BABYLON.Observable();
  23725. _this._onDisposeObserver = null;
  23726. /**
  23727. * An event triggered before rendering the scene (right after animations and physics)
  23728. */
  23729. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23730. _this._onBeforeRenderObserver = null;
  23731. /**
  23732. * An event triggered after rendering the scene
  23733. */
  23734. _this.onAfterRenderObservable = new BABYLON.Observable();
  23735. _this._onAfterRenderObserver = null;
  23736. /**
  23737. * An event triggered before animating the scene
  23738. */
  23739. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23740. /**
  23741. * An event triggered after animations processing
  23742. */
  23743. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23744. /**
  23745. * An event triggered before draw calls are ready to be sent
  23746. */
  23747. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23748. /**
  23749. * An event triggered after draw calls have been sent
  23750. */
  23751. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23752. /**
  23753. * An event triggered when physic simulation is about to be run
  23754. */
  23755. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23756. /**
  23757. * An event triggered when physic simulation has been done
  23758. */
  23759. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23760. /**
  23761. * An event triggered when the scene is ready
  23762. */
  23763. _this.onReadyObservable = new BABYLON.Observable();
  23764. /**
  23765. * An event triggered before rendering a camera
  23766. */
  23767. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23768. _this._onBeforeCameraRenderObserver = null;
  23769. /**
  23770. * An event triggered after rendering a camera
  23771. */
  23772. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23773. _this._onAfterCameraRenderObserver = null;
  23774. /**
  23775. * An event triggered when active meshes evaluation is about to start
  23776. */
  23777. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23778. /**
  23779. * An event triggered when active meshes evaluation is done
  23780. */
  23781. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23782. /**
  23783. * An event triggered when particles rendering is about to start
  23784. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23785. */
  23786. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23787. /**
  23788. * An event triggered when particles rendering is done
  23789. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23790. */
  23791. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23792. /**
  23793. * An event triggered when sprites rendering is about to start
  23794. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23795. */
  23796. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23797. /**
  23798. * An event triggered when sprites rendering is done
  23799. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23800. */
  23801. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23802. /**
  23803. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23804. */
  23805. _this.onDataLoadedObservable = new BABYLON.Observable();
  23806. /**
  23807. * An event triggered when a camera is created
  23808. */
  23809. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  23810. /**
  23811. * An event triggered when a camera is removed
  23812. */
  23813. _this.onCameraRemovedObservable = new BABYLON.Observable();
  23814. /**
  23815. * An event triggered when a light is created
  23816. */
  23817. _this.onNewLightAddedObservable = new BABYLON.Observable();
  23818. /**
  23819. * An event triggered when a light is removed
  23820. */
  23821. _this.onLightRemovedObservable = new BABYLON.Observable();
  23822. /**
  23823. * An event triggered when a geometry is created
  23824. */
  23825. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23826. /**
  23827. * An event triggered when a geometry is removed
  23828. */
  23829. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  23830. /**
  23831. * An event triggered when a transform node is created
  23832. */
  23833. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23834. /**
  23835. * An event triggered when a transform node is removed
  23836. */
  23837. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23838. /**
  23839. * An event triggered when a mesh is created
  23840. */
  23841. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  23842. /**
  23843. * An event triggered when a mesh is removed
  23844. */
  23845. _this.onMeshRemovedObservable = new BABYLON.Observable();
  23846. /**
  23847. * An event triggered when render targets are about to be rendered
  23848. * Can happen multiple times per frame.
  23849. */
  23850. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23851. /**
  23852. * An event triggered when render targets were rendered.
  23853. * Can happen multiple times per frame.
  23854. */
  23855. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23856. /**
  23857. * An event triggered before calculating deterministic simulation step
  23858. */
  23859. _this.onBeforeStepObservable = new BABYLON.Observable();
  23860. /**
  23861. * An event triggered after calculating deterministic simulation step
  23862. */
  23863. _this.onAfterStepObservable = new BABYLON.Observable();
  23864. /**
  23865. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  23866. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23867. * 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)
  23868. */
  23869. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  23870. /**
  23871. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  23872. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23873. * 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)
  23874. */
  23875. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  23876. // Animations
  23877. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23878. /**
  23879. * 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).
  23880. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23881. */
  23882. _this.onPrePointerObservable = new BABYLON.Observable();
  23883. /**
  23884. * Observable event triggered each time an input event is received from the rendering canvas
  23885. */
  23886. _this.onPointerObservable = new BABYLON.Observable();
  23887. _this._meshPickProceed = false;
  23888. _this._currentPickResult = null;
  23889. _this._previousPickResult = null;
  23890. _this._totalPointersPressed = 0;
  23891. _this._doubleClickOccured = false;
  23892. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23893. _this.cameraToUseForPointers = null;
  23894. _this._pointerX = 0;
  23895. _this._pointerY = 0;
  23896. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23897. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23898. _this._startingPointerTime = 0;
  23899. _this._previousStartingPointerTime = 0;
  23900. _this._pointerCaptures = {};
  23901. // Deterministic lockstep
  23902. _this._timeAccumulator = 0;
  23903. _this._currentStepId = 0;
  23904. _this._currentInternalStep = 0;
  23905. // Keyboard
  23906. /**
  23907. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23908. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23909. */
  23910. _this.onPreKeyboardObservable = new BABYLON.Observable();
  23911. /**
  23912. * Observable event triggered each time an keyboard event is received from the hosting window
  23913. */
  23914. _this.onKeyboardObservable = new BABYLON.Observable();
  23915. // Coordinates system
  23916. _this._useRightHandedSystem = false;
  23917. // Fog
  23918. _this._fogEnabled = true;
  23919. _this._fogMode = Scene.FOGMODE_NONE;
  23920. /**
  23921. * Gets or sets the fog color to use
  23922. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23923. */
  23924. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23925. /**
  23926. * Gets or sets the fog density to use
  23927. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23928. */
  23929. _this.fogDensity = 0.1;
  23930. /**
  23931. * Gets or sets the fog start distance to use
  23932. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23933. */
  23934. _this.fogStart = 0;
  23935. /**
  23936. * Gets or sets the fog end distance to use
  23937. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23938. */
  23939. _this.fogEnd = 1000.0;
  23940. // Lights
  23941. _this._shadowsEnabled = true;
  23942. _this._lightsEnabled = true;
  23943. /** All of the active cameras added to this scene. */
  23944. _this.activeCameras = new Array();
  23945. // Textures
  23946. _this._texturesEnabled = true;
  23947. // Particles
  23948. /**
  23949. * Gets or sets a boolean indicating if particles are enabled on this scene
  23950. */
  23951. _this.particlesEnabled = true;
  23952. // Sprites
  23953. /**
  23954. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23955. */
  23956. _this.spritesEnabled = true;
  23957. /**
  23958. * All of the sprite managers added to this scene
  23959. * @see http://doc.babylonjs.com/babylon101/sprites
  23960. */
  23961. _this.spriteManagers = new Array();
  23962. // Skeletons
  23963. _this._skeletonsEnabled = true;
  23964. // Lens flares
  23965. /**
  23966. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23967. */
  23968. _this.lensFlaresEnabled = true;
  23969. // Collisions
  23970. /**
  23971. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23972. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23973. */
  23974. _this.collisionsEnabled = true;
  23975. /**
  23976. * Defines the gravity applied to this scene (used only for collisions)
  23977. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23978. */
  23979. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23980. // Postprocesses
  23981. /**
  23982. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23983. */
  23984. _this.postProcessesEnabled = true;
  23985. /**
  23986. * The list of postprocesses added to the scene
  23987. */
  23988. _this.postProcesses = new Array();
  23989. // Customs render targets
  23990. /**
  23991. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23992. */
  23993. _this.renderTargetsEnabled = true;
  23994. /**
  23995. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23996. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23997. */
  23998. _this.dumpNextRenderTargets = false;
  23999. /**
  24000. * The list of user defined render targets added to the scene
  24001. */
  24002. _this.customRenderTargets = new Array();
  24003. /**
  24004. * Gets the list of meshes imported to the scene through SceneLoader
  24005. */
  24006. _this.importedMeshesFiles = new Array();
  24007. // Probes
  24008. /**
  24009. * Gets or sets a boolean indicating if probes are enabled on this scene
  24010. */
  24011. _this.probesEnabled = true;
  24012. /**
  24013. * The list of reflection probes added to the scene
  24014. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24015. */
  24016. _this.reflectionProbes = new Array();
  24017. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24018. // Procedural textures
  24019. /**
  24020. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24021. */
  24022. _this.proceduralTexturesEnabled = true;
  24023. /**
  24024. * The list of procedural textures added to the scene
  24025. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24026. */
  24027. _this.proceduralTextures = new Array();
  24028. /**
  24029. * The list of sound tracks added to the scene
  24030. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24031. */
  24032. _this.soundTracks = new Array();
  24033. _this._audioEnabled = true;
  24034. _this._headphone = false;
  24035. // Performance counters
  24036. _this._totalVertices = new BABYLON.PerfCounter();
  24037. /** @hidden */
  24038. _this._activeIndices = new BABYLON.PerfCounter();
  24039. /** @hidden */
  24040. _this._activeParticles = new BABYLON.PerfCounter();
  24041. /** @hidden */
  24042. _this._activeBones = new BABYLON.PerfCounter();
  24043. _this._animationTime = 0;
  24044. /**
  24045. * Gets or sets a general scale for animation speed
  24046. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24047. */
  24048. _this.animationTimeScale = 1;
  24049. _this._renderId = 0;
  24050. _this._executeWhenReadyTimeoutId = -1;
  24051. _this._intermediateRendering = false;
  24052. _this._viewUpdateFlag = -1;
  24053. _this._projectionUpdateFlag = -1;
  24054. _this._alternateViewUpdateFlag = -1;
  24055. _this._alternateProjectionUpdateFlag = -1;
  24056. /** @hidden */
  24057. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24058. _this._activeRequests = new Array();
  24059. _this._pendingData = new Array();
  24060. _this._isDisposed = false;
  24061. /**
  24062. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24063. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24064. */
  24065. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24066. _this._activeMeshes = new BABYLON.SmartArray(256);
  24067. _this._processedMaterials = new BABYLON.SmartArray(256);
  24068. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24069. /** @hidden */
  24070. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24071. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24072. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24073. /** @hidden */
  24074. _this._activeAnimatables = new Array();
  24075. _this._transformMatrix = BABYLON.Matrix.Zero();
  24076. _this._useAlternateCameraConfiguration = false;
  24077. _this._alternateRendering = false;
  24078. /**
  24079. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24080. * This is useful if there are more lights that the maximum simulteanous authorized
  24081. */
  24082. _this.requireLightSorting = false;
  24083. _this._depthRenderer = {};
  24084. /**
  24085. * Backing store of defined scene components.
  24086. */
  24087. _this._components = [];
  24088. /**
  24089. * Backing store of defined scene components.
  24090. */
  24091. _this._serializableComponents = [];
  24092. /**
  24093. * List of components to register on the next registration step.
  24094. */
  24095. _this._transientComponents = [];
  24096. /**
  24097. * Defines the actions happening before camera updates.
  24098. */
  24099. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24100. /**
  24101. * Defines the actions happening during the per mesh ready checks.
  24102. */
  24103. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24104. /**
  24105. * Defines the actions happening before evaluate active mesh checks.
  24106. */
  24107. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24108. /**
  24109. * Defines the actions happening during the evaluate sub mesh checks.
  24110. */
  24111. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24112. /**
  24113. * Defines the actions happening during the active mesh stage.
  24114. */
  24115. _this._activeMeshStage = BABYLON.Stage.Create();
  24116. /**
  24117. * Defines the actions happening during the per camera render target step.
  24118. */
  24119. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24120. /**
  24121. * Defines the actions happening just before the active camera is drawing.
  24122. */
  24123. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24124. /**
  24125. * Defines the actions happening just before a rendering group is drawing.
  24126. */
  24127. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24128. /**
  24129. * Defines the actions happening just after a rendering group has been drawn.
  24130. */
  24131. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24132. /**
  24133. * Defines the actions happening just after the active camera has been drawn.
  24134. */
  24135. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24136. _this._activeMeshesFrozen = false;
  24137. /** @hidden */
  24138. _this._allowPostProcessClear = true;
  24139. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24140. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24141. _this._engine.scenes.push(_this);
  24142. _this._uid = null;
  24143. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24144. if (BABYLON.PostProcessManager) {
  24145. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24146. }
  24147. if (BABYLON.OutlineRenderer) {
  24148. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24149. }
  24150. if (BABYLON.Tools.IsWindowObjectExist()) {
  24151. _this.attachControl();
  24152. }
  24153. //simplification queue
  24154. if (BABYLON.SimplificationQueue) {
  24155. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24156. }
  24157. //collision coordinator initialization. For now legacy per default.
  24158. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24159. // Uniform Buffer
  24160. _this._createUbo();
  24161. // Default Image processing definition
  24162. if (BABYLON.ImageProcessingConfiguration) {
  24163. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24164. }
  24165. return _this;
  24166. }
  24167. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24168. /** The fog is deactivated */
  24169. get: function () {
  24170. return Scene._FOGMODE_NONE;
  24171. },
  24172. enumerable: true,
  24173. configurable: true
  24174. });
  24175. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24176. /** The fog density is following an exponential function */
  24177. get: function () {
  24178. return Scene._FOGMODE_EXP;
  24179. },
  24180. enumerable: true,
  24181. configurable: true
  24182. });
  24183. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24184. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24185. get: function () {
  24186. return Scene._FOGMODE_EXP2;
  24187. },
  24188. enumerable: true,
  24189. configurable: true
  24190. });
  24191. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24192. /** The fog density is following a linear function. */
  24193. get: function () {
  24194. return Scene._FOGMODE_LINEAR;
  24195. },
  24196. enumerable: true,
  24197. configurable: true
  24198. });
  24199. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24200. /**
  24201. * Texture used in all pbr material as the reflection texture.
  24202. * As in the majority of the scene they are the same (exception for multi room and so on),
  24203. * this is easier to reference from here than from all the materials.
  24204. */
  24205. get: function () {
  24206. return this._environmentTexture;
  24207. },
  24208. /**
  24209. * Texture used in all pbr material as the reflection texture.
  24210. * As in the majority of the scene they are the same (exception for multi room and so on),
  24211. * this is easier to set here than in all the materials.
  24212. */
  24213. set: function (value) {
  24214. if (this._environmentTexture === value) {
  24215. return;
  24216. }
  24217. this._environmentTexture = value;
  24218. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24219. },
  24220. enumerable: true,
  24221. configurable: true
  24222. });
  24223. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24224. /**
  24225. * Default image processing configuration used either in the rendering
  24226. * Forward main pass or through the imageProcessingPostProcess if present.
  24227. * As in the majority of the scene they are the same (exception for multi camera),
  24228. * this is easier to reference from here than from all the materials and post process.
  24229. *
  24230. * No setter as we it is a shared configuration, you can set the values instead.
  24231. */
  24232. get: function () {
  24233. return this._imageProcessingConfiguration;
  24234. },
  24235. enumerable: true,
  24236. configurable: true
  24237. });
  24238. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24239. get: function () {
  24240. return this._forceWireframe;
  24241. },
  24242. /**
  24243. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24244. */
  24245. set: function (value) {
  24246. if (this._forceWireframe === value) {
  24247. return;
  24248. }
  24249. this._forceWireframe = value;
  24250. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24251. },
  24252. enumerable: true,
  24253. configurable: true
  24254. });
  24255. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24256. get: function () {
  24257. return this._forcePointsCloud;
  24258. },
  24259. /**
  24260. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24261. */
  24262. set: function (value) {
  24263. if (this._forcePointsCloud === value) {
  24264. return;
  24265. }
  24266. this._forcePointsCloud = value;
  24267. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24268. },
  24269. enumerable: true,
  24270. configurable: true
  24271. });
  24272. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24273. /**
  24274. * Gets or sets the animation properties override
  24275. */
  24276. get: function () {
  24277. return this._animationPropertiesOverride;
  24278. },
  24279. set: function (value) {
  24280. this._animationPropertiesOverride = value;
  24281. },
  24282. enumerable: true,
  24283. configurable: true
  24284. });
  24285. Object.defineProperty(Scene.prototype, "onDispose", {
  24286. /** Sets a function to be executed when this scene is disposed. */
  24287. set: function (callback) {
  24288. if (this._onDisposeObserver) {
  24289. this.onDisposeObservable.remove(this._onDisposeObserver);
  24290. }
  24291. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24292. },
  24293. enumerable: true,
  24294. configurable: true
  24295. });
  24296. Object.defineProperty(Scene.prototype, "beforeRender", {
  24297. /** Sets a function to be executed before rendering this scene */
  24298. set: function (callback) {
  24299. if (this._onBeforeRenderObserver) {
  24300. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24301. }
  24302. if (callback) {
  24303. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24304. }
  24305. },
  24306. enumerable: true,
  24307. configurable: true
  24308. });
  24309. Object.defineProperty(Scene.prototype, "afterRender", {
  24310. /** Sets a function to be executed after rendering this scene */
  24311. set: function (callback) {
  24312. if (this._onAfterRenderObserver) {
  24313. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24314. }
  24315. if (callback) {
  24316. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24317. }
  24318. },
  24319. enumerable: true,
  24320. configurable: true
  24321. });
  24322. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24323. /** Sets a function to be executed before rendering a camera*/
  24324. set: function (callback) {
  24325. if (this._onBeforeCameraRenderObserver) {
  24326. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24327. }
  24328. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24329. },
  24330. enumerable: true,
  24331. configurable: true
  24332. });
  24333. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24334. /** Sets a function to be executed after rendering a camera*/
  24335. set: function (callback) {
  24336. if (this._onAfterCameraRenderObserver) {
  24337. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24338. }
  24339. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24340. },
  24341. enumerable: true,
  24342. configurable: true
  24343. });
  24344. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24345. /**
  24346. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24347. */
  24348. get: function () {
  24349. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24350. },
  24351. enumerable: true,
  24352. configurable: true
  24353. });
  24354. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24355. get: function () {
  24356. return this._useRightHandedSystem;
  24357. },
  24358. /**
  24359. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24360. */
  24361. set: function (value) {
  24362. if (this._useRightHandedSystem === value) {
  24363. return;
  24364. }
  24365. this._useRightHandedSystem = value;
  24366. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24367. },
  24368. enumerable: true,
  24369. configurable: true
  24370. });
  24371. /**
  24372. * Sets the step Id used by deterministic lock step
  24373. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24374. * @param newStepId defines the step Id
  24375. */
  24376. Scene.prototype.setStepId = function (newStepId) {
  24377. this._currentStepId = newStepId;
  24378. };
  24379. ;
  24380. /**
  24381. * Gets the step Id used by deterministic lock step
  24382. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24383. * @returns the step Id
  24384. */
  24385. Scene.prototype.getStepId = function () {
  24386. return this._currentStepId;
  24387. };
  24388. ;
  24389. /**
  24390. * Gets the internal step used by deterministic lock step
  24391. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24392. * @returns the internal step
  24393. */
  24394. Scene.prototype.getInternalStep = function () {
  24395. return this._currentInternalStep;
  24396. };
  24397. ;
  24398. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24399. get: function () {
  24400. return this._fogEnabled;
  24401. },
  24402. /**
  24403. * Gets or sets a boolean indicating if fog is enabled on this scene
  24404. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24405. */
  24406. set: function (value) {
  24407. if (this._fogEnabled === value) {
  24408. return;
  24409. }
  24410. this._fogEnabled = value;
  24411. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24412. },
  24413. enumerable: true,
  24414. configurable: true
  24415. });
  24416. Object.defineProperty(Scene.prototype, "fogMode", {
  24417. get: function () {
  24418. return this._fogMode;
  24419. },
  24420. /**
  24421. * Gets or sets the fog mode to use
  24422. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24423. */
  24424. set: function (value) {
  24425. if (this._fogMode === value) {
  24426. return;
  24427. }
  24428. this._fogMode = value;
  24429. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24430. },
  24431. enumerable: true,
  24432. configurable: true
  24433. });
  24434. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24435. get: function () {
  24436. return this._shadowsEnabled;
  24437. },
  24438. /**
  24439. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24440. */
  24441. set: function (value) {
  24442. if (this._shadowsEnabled === value) {
  24443. return;
  24444. }
  24445. this._shadowsEnabled = value;
  24446. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24447. },
  24448. enumerable: true,
  24449. configurable: true
  24450. });
  24451. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24452. get: function () {
  24453. return this._lightsEnabled;
  24454. },
  24455. /**
  24456. * Gets or sets a boolean indicating if lights are enabled on this scene
  24457. */
  24458. set: function (value) {
  24459. if (this._lightsEnabled === value) {
  24460. return;
  24461. }
  24462. this._lightsEnabled = value;
  24463. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24464. },
  24465. enumerable: true,
  24466. configurable: true
  24467. });
  24468. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24469. /** The default material used on meshes when no material is affected */
  24470. get: function () {
  24471. if (!this._defaultMaterial) {
  24472. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24473. }
  24474. return this._defaultMaterial;
  24475. },
  24476. /** The default material used on meshes when no material is affected */
  24477. set: function (value) {
  24478. this._defaultMaterial = value;
  24479. },
  24480. enumerable: true,
  24481. configurable: true
  24482. });
  24483. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24484. get: function () {
  24485. return this._texturesEnabled;
  24486. },
  24487. /**
  24488. * Gets or sets a boolean indicating if textures are enabled on this scene
  24489. */
  24490. set: function (value) {
  24491. if (this._texturesEnabled === value) {
  24492. return;
  24493. }
  24494. this._texturesEnabled = value;
  24495. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24496. },
  24497. enumerable: true,
  24498. configurable: true
  24499. });
  24500. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24501. get: function () {
  24502. return this._skeletonsEnabled;
  24503. },
  24504. /**
  24505. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24506. */
  24507. set: function (value) {
  24508. if (this._skeletonsEnabled === value) {
  24509. return;
  24510. }
  24511. this._skeletonsEnabled = value;
  24512. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24513. },
  24514. enumerable: true,
  24515. configurable: true
  24516. });
  24517. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24518. /**
  24519. * Gets the postprocess render pipeline manager
  24520. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24521. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24522. */
  24523. get: function () {
  24524. if (!this._postProcessRenderPipelineManager) {
  24525. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24526. }
  24527. return this._postProcessRenderPipelineManager;
  24528. },
  24529. enumerable: true,
  24530. configurable: true
  24531. });
  24532. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24533. /**
  24534. * Gets the main soundtrack associated with the scene
  24535. */
  24536. get: function () {
  24537. if (!this._mainSoundTrack) {
  24538. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24539. }
  24540. return this._mainSoundTrack;
  24541. },
  24542. enumerable: true,
  24543. configurable: true
  24544. });
  24545. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24546. /** @hidden */
  24547. get: function () {
  24548. return this._alternateRendering;
  24549. },
  24550. enumerable: true,
  24551. configurable: true
  24552. });
  24553. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24554. /**
  24555. * Gets the list of frustum planes (built from the active camera)
  24556. */
  24557. get: function () {
  24558. return this._frustumPlanes;
  24559. },
  24560. enumerable: true,
  24561. configurable: true
  24562. });
  24563. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24564. /**
  24565. * Gets the current geometry buffer associated to the scene.
  24566. */
  24567. get: function () {
  24568. return this._geometryBufferRenderer;
  24569. },
  24570. /**
  24571. * Sets the current geometry buffer for the scene.
  24572. */
  24573. set: function (geometryBufferRenderer) {
  24574. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24575. this._geometryBufferRenderer = geometryBufferRenderer;
  24576. }
  24577. },
  24578. enumerable: true,
  24579. configurable: true
  24580. });
  24581. /**
  24582. * Registers the transient components if needed.
  24583. */
  24584. Scene.prototype._registerTransientComponents = function () {
  24585. // Register components that have been associated lately to the scene.
  24586. if (this._transientComponents.length > 0) {
  24587. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24588. var component = _a[_i];
  24589. component.register();
  24590. }
  24591. this._transientComponents = [];
  24592. }
  24593. };
  24594. /**
  24595. * Add a component to the scene.
  24596. * Note that the ccomponent could be registered on th next frame if this is called after
  24597. * the register component stage.
  24598. * @param component Defines the component to add to the scene
  24599. */
  24600. Scene.prototype._addComponent = function (component) {
  24601. this._components.push(component);
  24602. this._transientComponents.push(component);
  24603. var serializableComponent = component;
  24604. if (serializableComponent.addFromContainer) {
  24605. this._serializableComponents.push(serializableComponent);
  24606. }
  24607. };
  24608. /**
  24609. * Gets a component from the scene.
  24610. * @param name defines the name of the component to retrieve
  24611. * @returns the component or null if not present
  24612. */
  24613. Scene.prototype._getComponent = function (name) {
  24614. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24615. var component = _a[_i];
  24616. if (component.name === name) {
  24617. return component;
  24618. }
  24619. }
  24620. return null;
  24621. };
  24622. Object.defineProperty(Scene.prototype, "debugLayer", {
  24623. /**
  24624. * Gets the debug layer (aka Inspector) associated with the scene
  24625. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24626. */
  24627. get: function () {
  24628. if (!this._debugLayer) {
  24629. this._debugLayer = new BABYLON.DebugLayer(this);
  24630. }
  24631. return this._debugLayer;
  24632. },
  24633. enumerable: true,
  24634. configurable: true
  24635. });
  24636. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24637. /**
  24638. * Gets a boolean indicating if collisions are processed on a web worker
  24639. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24640. */
  24641. get: function () {
  24642. return this._workerCollisions;
  24643. },
  24644. set: function (enabled) {
  24645. if (!BABYLON.CollisionCoordinatorLegacy) {
  24646. return;
  24647. }
  24648. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24649. this._workerCollisions = enabled;
  24650. if (this.collisionCoordinator) {
  24651. this.collisionCoordinator.destroy();
  24652. }
  24653. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24654. this.collisionCoordinator.init(this);
  24655. },
  24656. enumerable: true,
  24657. configurable: true
  24658. });
  24659. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24660. /**
  24661. * Gets the octree used to boost mesh selection (picking)
  24662. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24663. */
  24664. get: function () {
  24665. return this._selectionOctree;
  24666. },
  24667. enumerable: true,
  24668. configurable: true
  24669. });
  24670. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24671. /**
  24672. * Gets the mesh that is currently under the pointer
  24673. */
  24674. get: function () {
  24675. return this._pointerOverMesh;
  24676. },
  24677. enumerable: true,
  24678. configurable: true
  24679. });
  24680. Object.defineProperty(Scene.prototype, "pointerX", {
  24681. /**
  24682. * Gets the current on-screen X position of the pointer
  24683. */
  24684. get: function () {
  24685. return this._pointerX;
  24686. },
  24687. enumerable: true,
  24688. configurable: true
  24689. });
  24690. Object.defineProperty(Scene.prototype, "pointerY", {
  24691. /**
  24692. * Gets the current on-screen Y position of the pointer
  24693. */
  24694. get: function () {
  24695. return this._pointerY;
  24696. },
  24697. enumerable: true,
  24698. configurable: true
  24699. });
  24700. /**
  24701. * Gets the cached material (ie. the latest rendered one)
  24702. * @returns the cached material
  24703. */
  24704. Scene.prototype.getCachedMaterial = function () {
  24705. return this._cachedMaterial;
  24706. };
  24707. /**
  24708. * Gets the cached effect (ie. the latest rendered one)
  24709. * @returns the cached effect
  24710. */
  24711. Scene.prototype.getCachedEffect = function () {
  24712. return this._cachedEffect;
  24713. };
  24714. /**
  24715. * Gets the cached visibility state (ie. the latest rendered one)
  24716. * @returns the cached visibility state
  24717. */
  24718. Scene.prototype.getCachedVisibility = function () {
  24719. return this._cachedVisibility;
  24720. };
  24721. /**
  24722. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24723. * @param material defines the current material
  24724. * @param effect defines the current effect
  24725. * @param visibility defines the current visibility state
  24726. * @returns true if one parameter is not cached
  24727. */
  24728. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24729. if (visibility === void 0) { visibility = 1; }
  24730. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24731. };
  24732. /**
  24733. * Gets the outline renderer associated with the scene
  24734. * @returns a OutlineRenderer
  24735. */
  24736. Scene.prototype.getOutlineRenderer = function () {
  24737. return this._outlineRenderer;
  24738. };
  24739. /**
  24740. * Gets the engine associated with the scene
  24741. * @returns an Engine
  24742. */
  24743. Scene.prototype.getEngine = function () {
  24744. return this._engine;
  24745. };
  24746. /**
  24747. * Gets the total number of vertices rendered per frame
  24748. * @returns the total number of vertices rendered per frame
  24749. */
  24750. Scene.prototype.getTotalVertices = function () {
  24751. return this._totalVertices.current;
  24752. };
  24753. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24754. /**
  24755. * Gets the performance counter for total vertices
  24756. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24757. */
  24758. get: function () {
  24759. return this._totalVertices;
  24760. },
  24761. enumerable: true,
  24762. configurable: true
  24763. });
  24764. /**
  24765. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24766. * @returns the total number of active indices rendered per frame
  24767. */
  24768. Scene.prototype.getActiveIndices = function () {
  24769. return this._activeIndices.current;
  24770. };
  24771. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24772. /**
  24773. * Gets the performance counter for active indices
  24774. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24775. */
  24776. get: function () {
  24777. return this._activeIndices;
  24778. },
  24779. enumerable: true,
  24780. configurable: true
  24781. });
  24782. /**
  24783. * Gets the total number of active particles rendered per frame
  24784. * @returns the total number of active particles rendered per frame
  24785. */
  24786. Scene.prototype.getActiveParticles = function () {
  24787. return this._activeParticles.current;
  24788. };
  24789. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24790. /**
  24791. * Gets the performance counter for active particles
  24792. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24793. */
  24794. get: function () {
  24795. return this._activeParticles;
  24796. },
  24797. enumerable: true,
  24798. configurable: true
  24799. });
  24800. /**
  24801. * Gets the total number of active bones rendered per frame
  24802. * @returns the total number of active bones rendered per frame
  24803. */
  24804. Scene.prototype.getActiveBones = function () {
  24805. return this._activeBones.current;
  24806. };
  24807. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24808. /**
  24809. * Gets the performance counter for active bones
  24810. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24811. */
  24812. get: function () {
  24813. return this._activeBones;
  24814. },
  24815. enumerable: true,
  24816. configurable: true
  24817. });
  24818. /** @hidden */
  24819. Scene.prototype.getInterFramePerfCounter = function () {
  24820. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24821. return 0;
  24822. };
  24823. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24824. /** @hidden */
  24825. get: function () {
  24826. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24827. return null;
  24828. },
  24829. enumerable: true,
  24830. configurable: true
  24831. });
  24832. /** @hidden */
  24833. Scene.prototype.getLastFrameDuration = function () {
  24834. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24835. return 0;
  24836. };
  24837. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24838. /** @hidden */
  24839. get: function () {
  24840. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24841. return null;
  24842. },
  24843. enumerable: true,
  24844. configurable: true
  24845. });
  24846. /** @hidden */
  24847. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24848. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24849. return 0;
  24850. };
  24851. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24852. /** @hidden */
  24853. get: function () {
  24854. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24855. return null;
  24856. },
  24857. enumerable: true,
  24858. configurable: true
  24859. });
  24860. /**
  24861. * Gets the array of active meshes
  24862. * @returns an array of AbstractMesh
  24863. */
  24864. Scene.prototype.getActiveMeshes = function () {
  24865. return this._activeMeshes;
  24866. };
  24867. /** @hidden */
  24868. Scene.prototype.getRenderTargetsDuration = function () {
  24869. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24870. return 0;
  24871. };
  24872. /** @hidden */
  24873. Scene.prototype.getRenderDuration = function () {
  24874. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24875. return 0;
  24876. };
  24877. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24878. /** @hidden */
  24879. get: function () {
  24880. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24881. return null;
  24882. },
  24883. enumerable: true,
  24884. configurable: true
  24885. });
  24886. /** @hidden */
  24887. Scene.prototype.getParticlesDuration = function () {
  24888. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24889. return 0;
  24890. };
  24891. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24892. /** @hidden */
  24893. get: function () {
  24894. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24895. return null;
  24896. },
  24897. enumerable: true,
  24898. configurable: true
  24899. });
  24900. /** @hidden */
  24901. Scene.prototype.getSpritesDuration = function () {
  24902. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24903. return 0;
  24904. };
  24905. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24906. /** @hidden */
  24907. get: function () {
  24908. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24909. return null;
  24910. },
  24911. enumerable: true,
  24912. configurable: true
  24913. });
  24914. /**
  24915. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24916. * @returns a number
  24917. */
  24918. Scene.prototype.getAnimationRatio = function () {
  24919. return this._animationRatio !== undefined ? this._animationRatio : 1;
  24920. };
  24921. /**
  24922. * Gets an unique Id for the current frame
  24923. * @returns a number
  24924. */
  24925. Scene.prototype.getRenderId = function () {
  24926. return this._renderId;
  24927. };
  24928. /** Call this function if you want to manually increment the render Id*/
  24929. Scene.prototype.incrementRenderId = function () {
  24930. this._renderId++;
  24931. };
  24932. Scene.prototype._updatePointerPosition = function (evt) {
  24933. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24934. if (!canvasRect) {
  24935. return;
  24936. }
  24937. this._pointerX = evt.clientX - canvasRect.left;
  24938. this._pointerY = evt.clientY - canvasRect.top;
  24939. this._unTranslatedPointerX = this._pointerX;
  24940. this._unTranslatedPointerY = this._pointerY;
  24941. };
  24942. Scene.prototype._createUbo = function () {
  24943. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24944. this._sceneUbo.addUniform("viewProjection", 16);
  24945. this._sceneUbo.addUniform("view", 16);
  24946. };
  24947. Scene.prototype._createAlternateUbo = function () {
  24948. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24949. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24950. this._alternateSceneUbo.addUniform("view", 16);
  24951. };
  24952. // Pointers handling
  24953. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24954. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24955. if (result) {
  24956. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24957. }
  24958. return result;
  24959. };
  24960. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24961. if (pointerInfo.pickInfo) {
  24962. if (!pointerInfo.pickInfo.ray) {
  24963. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24964. }
  24965. }
  24966. };
  24967. /**
  24968. * Use this method to simulate a pointer move on a mesh
  24969. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24970. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24971. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24972. * @returns the current scene
  24973. */
  24974. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24975. var evt = new PointerEvent("pointermove", pointerEventInit);
  24976. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24977. return this;
  24978. }
  24979. return this._processPointerMove(pickResult, evt);
  24980. };
  24981. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24982. var canvas = this._engine.getRenderingCanvas();
  24983. if (!canvas) {
  24984. return this;
  24985. }
  24986. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24987. this.setPointerOverSprite(null);
  24988. this.setPointerOverMesh(pickResult.pickedMesh);
  24989. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24990. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24991. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24992. }
  24993. else {
  24994. canvas.style.cursor = this.hoverCursor;
  24995. }
  24996. }
  24997. else {
  24998. canvas.style.cursor = this.defaultCursor;
  24999. }
  25000. }
  25001. else {
  25002. this.setPointerOverMesh(null);
  25003. // Sprites
  25004. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25005. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25006. this.setPointerOverSprite(pickResult.pickedSprite);
  25007. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25008. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25009. }
  25010. else {
  25011. canvas.style.cursor = this.hoverCursor;
  25012. }
  25013. }
  25014. else {
  25015. this.setPointerOverSprite(null);
  25016. // Restore pointer
  25017. canvas.style.cursor = this.defaultCursor;
  25018. }
  25019. }
  25020. if (pickResult) {
  25021. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25022. if (this.onPointerMove) {
  25023. this.onPointerMove(evt, pickResult, type);
  25024. }
  25025. if (this.onPointerObservable.hasObservers()) {
  25026. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25027. this._setRayOnPointerInfo(pi);
  25028. this.onPointerObservable.notifyObservers(pi, type);
  25029. }
  25030. }
  25031. return this;
  25032. };
  25033. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25034. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25035. if (pickResult) {
  25036. pi.ray = pickResult.ray;
  25037. }
  25038. this.onPrePointerObservable.notifyObservers(pi, type);
  25039. if (pi.skipOnPointerObservable) {
  25040. return true;
  25041. }
  25042. else {
  25043. return false;
  25044. }
  25045. };
  25046. /**
  25047. * Use this method to simulate a pointer down on a mesh
  25048. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25049. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25050. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25051. * @returns the current scene
  25052. */
  25053. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25054. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25055. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25056. return this;
  25057. }
  25058. return this._processPointerDown(pickResult, evt);
  25059. };
  25060. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25061. var _this = this;
  25062. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25063. this._pickedDownMesh = pickResult.pickedMesh;
  25064. var actionManager = pickResult.pickedMesh.actionManager;
  25065. if (actionManager) {
  25066. if (actionManager.hasPickTriggers) {
  25067. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25068. switch (evt.button) {
  25069. case 0:
  25070. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25071. break;
  25072. case 1:
  25073. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25074. break;
  25075. case 2:
  25076. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25077. break;
  25078. }
  25079. }
  25080. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25081. window.setTimeout(function () {
  25082. 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);
  25083. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25084. if (_this._totalPointersPressed !== 0 &&
  25085. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25086. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25087. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25088. _this._startingPointerTime = 0;
  25089. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25090. }
  25091. }
  25092. }, Scene.LongPressDelay);
  25093. }
  25094. }
  25095. }
  25096. if (pickResult) {
  25097. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25098. if (this.onPointerDown) {
  25099. this.onPointerDown(evt, pickResult, type);
  25100. }
  25101. if (this.onPointerObservable.hasObservers()) {
  25102. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25103. this._setRayOnPointerInfo(pi);
  25104. this.onPointerObservable.notifyObservers(pi, type);
  25105. }
  25106. }
  25107. return this;
  25108. };
  25109. /**
  25110. * Use this method to simulate a pointer up on a mesh
  25111. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25112. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25113. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25114. * @returns the current scene
  25115. */
  25116. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25117. var evt = new PointerEvent("pointerup", pointerEventInit);
  25118. var clickInfo = new ClickInfo();
  25119. clickInfo.singleClick = true;
  25120. clickInfo.ignore = true;
  25121. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25122. return this;
  25123. }
  25124. return this._processPointerUp(pickResult, evt, clickInfo);
  25125. };
  25126. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25127. if (pickResult && pickResult && pickResult.pickedMesh) {
  25128. this._pickedUpMesh = pickResult.pickedMesh;
  25129. if (this._pickedDownMesh === this._pickedUpMesh) {
  25130. if (this.onPointerPick) {
  25131. this.onPointerPick(evt, pickResult);
  25132. }
  25133. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25134. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25135. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25136. this._setRayOnPointerInfo(pi);
  25137. this.onPointerObservable.notifyObservers(pi, type_1);
  25138. }
  25139. }
  25140. if (pickResult.pickedMesh.actionManager) {
  25141. if (clickInfo.ignore) {
  25142. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25143. }
  25144. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25145. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25146. }
  25147. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25148. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25149. }
  25150. }
  25151. }
  25152. if (this._pickedDownMesh &&
  25153. this._pickedDownMesh.actionManager &&
  25154. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25155. this._pickedDownMesh !== this._pickedUpMesh) {
  25156. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25157. }
  25158. var type = BABYLON.PointerEventTypes.POINTERUP;
  25159. if (this.onPointerObservable.hasObservers()) {
  25160. if (!clickInfo.ignore) {
  25161. if (!clickInfo.hasSwiped) {
  25162. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25163. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25164. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25165. this._setRayOnPointerInfo(pi);
  25166. this.onPointerObservable.notifyObservers(pi, type_2);
  25167. }
  25168. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25169. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25170. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25171. this._setRayOnPointerInfo(pi);
  25172. this.onPointerObservable.notifyObservers(pi, type_3);
  25173. }
  25174. }
  25175. }
  25176. else {
  25177. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25178. this._setRayOnPointerInfo(pi);
  25179. this.onPointerObservable.notifyObservers(pi, type);
  25180. }
  25181. }
  25182. if (this.onPointerUp) {
  25183. this.onPointerUp(evt, pickResult, type);
  25184. }
  25185. return this;
  25186. };
  25187. /**
  25188. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25189. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25190. * @returns true if the pointer was captured
  25191. */
  25192. Scene.prototype.isPointerCaptured = function (pointerId) {
  25193. if (pointerId === void 0) { pointerId = 0; }
  25194. return this._pointerCaptures[pointerId];
  25195. };
  25196. /**
  25197. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25198. * @param attachUp defines if you want to attach events to pointerup
  25199. * @param attachDown defines if you want to attach events to pointerdown
  25200. * @param attachMove defines if you want to attach events to pointermove
  25201. */
  25202. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25203. var _this = this;
  25204. if (attachUp === void 0) { attachUp = true; }
  25205. if (attachDown === void 0) { attachDown = true; }
  25206. if (attachMove === void 0) { attachMove = true; }
  25207. this._initActionManager = function (act, clickInfo) {
  25208. if (!_this._meshPickProceed) {
  25209. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25210. _this._currentPickResult = pickResult;
  25211. if (pickResult) {
  25212. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25213. }
  25214. _this._meshPickProceed = true;
  25215. }
  25216. return act;
  25217. };
  25218. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25219. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25220. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25221. btn !== _this._previousButtonPressed) {
  25222. _this._doubleClickOccured = false;
  25223. clickInfo.singleClick = true;
  25224. clickInfo.ignore = false;
  25225. cb(clickInfo, _this._currentPickResult);
  25226. }
  25227. };
  25228. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25229. var clickInfo = new ClickInfo();
  25230. _this._currentPickResult = null;
  25231. var act = null;
  25232. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25233. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25234. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25235. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25236. act = _this._initActionManager(act, clickInfo);
  25237. if (act)
  25238. checkPicking = act.hasPickTriggers;
  25239. }
  25240. if (checkPicking) {
  25241. var btn = evt.button;
  25242. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25243. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25244. if (!clickInfo.hasSwiped) {
  25245. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25246. if (!checkSingleClickImmediately) {
  25247. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25248. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25249. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25250. act = _this._initActionManager(act, clickInfo);
  25251. if (act)
  25252. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25253. }
  25254. }
  25255. if (checkSingleClickImmediately) {
  25256. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25257. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25258. btn !== _this._previousButtonPressed) {
  25259. clickInfo.singleClick = true;
  25260. cb(clickInfo, _this._currentPickResult);
  25261. }
  25262. }
  25263. // at least one double click is required to be check and exclusive double click is enabled
  25264. else {
  25265. // wait that no double click has been raised during the double click delay
  25266. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25267. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25268. }
  25269. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25270. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25271. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25272. act = _this._initActionManager(act, clickInfo);
  25273. if (act)
  25274. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25275. }
  25276. if (checkDoubleClick) {
  25277. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25278. if (btn === _this._previousButtonPressed &&
  25279. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25280. !_this._doubleClickOccured) {
  25281. // pointer has not moved for 2 clicks, it's a double click
  25282. if (!clickInfo.hasSwiped &&
  25283. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25284. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25285. _this._previousStartingPointerTime = 0;
  25286. _this._doubleClickOccured = true;
  25287. clickInfo.doubleClick = true;
  25288. clickInfo.ignore = false;
  25289. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25290. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25291. }
  25292. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25293. cb(clickInfo, _this._currentPickResult);
  25294. }
  25295. // if the two successive clicks are too far, it's just two simple clicks
  25296. else {
  25297. _this._doubleClickOccured = false;
  25298. _this._previousStartingPointerTime = _this._startingPointerTime;
  25299. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25300. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25301. _this._previousButtonPressed = btn;
  25302. if (Scene.ExclusiveDoubleClickMode) {
  25303. if (_this._previousDelayedSimpleClickTimeout) {
  25304. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25305. }
  25306. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25307. cb(clickInfo, _this._previousPickResult);
  25308. }
  25309. else {
  25310. cb(clickInfo, _this._currentPickResult);
  25311. }
  25312. }
  25313. }
  25314. // just the first click of the double has been raised
  25315. else {
  25316. _this._doubleClickOccured = false;
  25317. _this._previousStartingPointerTime = _this._startingPointerTime;
  25318. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25319. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25320. _this._previousButtonPressed = btn;
  25321. }
  25322. }
  25323. }
  25324. }
  25325. clickInfo.ignore = true;
  25326. cb(clickInfo, _this._currentPickResult);
  25327. };
  25328. this._spritePredicate = function (sprite) {
  25329. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25330. };
  25331. this._onPointerMove = function (evt) {
  25332. _this._updatePointerPosition(evt);
  25333. // PreObservable support
  25334. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25335. return;
  25336. }
  25337. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25338. return;
  25339. }
  25340. if (!_this.pointerMovePredicate) {
  25341. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25342. }
  25343. // Meshes
  25344. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25345. _this._processPointerMove(pickResult, evt);
  25346. };
  25347. this._onPointerDown = function (evt) {
  25348. _this._totalPointersPressed++;
  25349. _this._pickedDownMesh = null;
  25350. _this._meshPickProceed = false;
  25351. _this._updatePointerPosition(evt);
  25352. if (_this.preventDefaultOnPointerDown && canvas) {
  25353. evt.preventDefault();
  25354. canvas.focus();
  25355. }
  25356. // PreObservable support
  25357. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25358. return;
  25359. }
  25360. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25361. return;
  25362. }
  25363. _this._pointerCaptures[evt.pointerId] = true;
  25364. _this._startingPointerPosition.x = _this._pointerX;
  25365. _this._startingPointerPosition.y = _this._pointerY;
  25366. _this._startingPointerTime = Date.now();
  25367. if (!_this.pointerDownPredicate) {
  25368. _this.pointerDownPredicate = function (mesh) {
  25369. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25370. };
  25371. }
  25372. // Meshes
  25373. _this._pickedDownMesh = null;
  25374. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25375. _this._processPointerDown(pickResult, evt);
  25376. // Sprites
  25377. _this._pickedDownSprite = null;
  25378. if (_this.spriteManagers.length > 0) {
  25379. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25380. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25381. if (pickResult.pickedSprite.actionManager) {
  25382. _this._pickedDownSprite = pickResult.pickedSprite;
  25383. switch (evt.button) {
  25384. case 0:
  25385. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25386. break;
  25387. case 1:
  25388. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25389. break;
  25390. case 2:
  25391. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25392. break;
  25393. }
  25394. if (pickResult.pickedSprite.actionManager) {
  25395. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25396. }
  25397. }
  25398. }
  25399. }
  25400. };
  25401. this._onPointerUp = function (evt) {
  25402. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25403. return; // So we need to test it the pointer down was pressed before.
  25404. }
  25405. _this._totalPointersPressed--;
  25406. _this._pickedUpMesh = null;
  25407. _this._meshPickProceed = false;
  25408. _this._updatePointerPosition(evt);
  25409. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25410. // PreObservable support
  25411. if (_this.onPrePointerObservable.hasObservers()) {
  25412. if (!clickInfo.ignore) {
  25413. if (!clickInfo.hasSwiped) {
  25414. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25415. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25416. return;
  25417. }
  25418. }
  25419. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25420. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25421. return;
  25422. }
  25423. }
  25424. }
  25425. }
  25426. else {
  25427. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25428. return;
  25429. }
  25430. }
  25431. }
  25432. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25433. return;
  25434. }
  25435. _this._pointerCaptures[evt.pointerId] = false;
  25436. if (!_this.pointerUpPredicate) {
  25437. _this.pointerUpPredicate = function (mesh) {
  25438. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25439. };
  25440. }
  25441. // Meshes
  25442. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25443. _this._initActionManager(null, clickInfo);
  25444. }
  25445. if (!pickResult) {
  25446. pickResult = _this._currentPickResult;
  25447. }
  25448. _this._processPointerUp(pickResult, evt, clickInfo);
  25449. // Sprites
  25450. if (!clickInfo.ignore) {
  25451. if (_this.spriteManagers.length > 0) {
  25452. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25453. if (spritePickResult) {
  25454. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25455. if (spritePickResult.pickedSprite.actionManager) {
  25456. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25457. if (spritePickResult.pickedSprite.actionManager) {
  25458. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25459. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25460. }
  25461. }
  25462. }
  25463. }
  25464. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25465. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25466. }
  25467. }
  25468. }
  25469. }
  25470. _this._previousPickResult = _this._currentPickResult;
  25471. });
  25472. };
  25473. this._onKeyDown = function (evt) {
  25474. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25475. if (_this.onPreKeyboardObservable.hasObservers()) {
  25476. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25477. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25478. if (pi.skipOnPointerObservable) {
  25479. return;
  25480. }
  25481. }
  25482. if (_this.onKeyboardObservable.hasObservers()) {
  25483. var pi = new BABYLON.KeyboardInfo(type, evt);
  25484. _this.onKeyboardObservable.notifyObservers(pi, type);
  25485. }
  25486. if (_this.actionManager) {
  25487. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25488. }
  25489. };
  25490. this._onKeyUp = function (evt) {
  25491. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25492. if (_this.onPreKeyboardObservable.hasObservers()) {
  25493. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25494. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25495. if (pi.skipOnPointerObservable) {
  25496. return;
  25497. }
  25498. }
  25499. if (_this.onKeyboardObservable.hasObservers()) {
  25500. var pi = new BABYLON.KeyboardInfo(type, evt);
  25501. _this.onKeyboardObservable.notifyObservers(pi, type);
  25502. }
  25503. if (_this.actionManager) {
  25504. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25505. }
  25506. };
  25507. var engine = this.getEngine();
  25508. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25509. if (!canvas) {
  25510. return;
  25511. }
  25512. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25513. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25514. });
  25515. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25516. if (!canvas) {
  25517. return;
  25518. }
  25519. canvas.removeEventListener("keydown", _this._onKeyDown);
  25520. canvas.removeEventListener("keyup", _this._onKeyUp);
  25521. });
  25522. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25523. var canvas = this._engine.getRenderingCanvas();
  25524. if (!canvas) {
  25525. return;
  25526. }
  25527. if (attachMove) {
  25528. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25529. // Wheel
  25530. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25531. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25532. }
  25533. if (attachDown) {
  25534. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25535. }
  25536. if (attachUp) {
  25537. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25538. }
  25539. canvas.tabIndex = 1;
  25540. };
  25541. /** Detaches all event handlers*/
  25542. Scene.prototype.detachControl = function () {
  25543. var engine = this.getEngine();
  25544. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25545. var canvas = engine.getRenderingCanvas();
  25546. if (!canvas) {
  25547. return;
  25548. }
  25549. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25550. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25551. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25552. if (this._onCanvasBlurObserver) {
  25553. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25554. }
  25555. if (this._onCanvasFocusObserver) {
  25556. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25557. }
  25558. // Wheel
  25559. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25560. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25561. // Keyboard
  25562. canvas.removeEventListener("keydown", this._onKeyDown);
  25563. canvas.removeEventListener("keyup", this._onKeyUp);
  25564. // Observables
  25565. this.onKeyboardObservable.clear();
  25566. this.onPreKeyboardObservable.clear();
  25567. this.onPointerObservable.clear();
  25568. this.onPrePointerObservable.clear();
  25569. };
  25570. /**
  25571. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25572. * Delay loaded resources are not taking in account
  25573. * @return true if all required resources are ready
  25574. */
  25575. Scene.prototype.isReady = function () {
  25576. if (this._isDisposed) {
  25577. return false;
  25578. }
  25579. if (this._pendingData.length > 0) {
  25580. return false;
  25581. }
  25582. var index;
  25583. var engine = this.getEngine();
  25584. // Geometries
  25585. for (index = 0; index < this.geometries.length; index++) {
  25586. var geometry = this.geometries[index];
  25587. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25588. return false;
  25589. }
  25590. }
  25591. // Meshes
  25592. for (index = 0; index < this.meshes.length; index++) {
  25593. var mesh = this.meshes[index];
  25594. if (!mesh.isEnabled()) {
  25595. continue;
  25596. }
  25597. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25598. continue;
  25599. }
  25600. if (!mesh.isReady(true)) {
  25601. return false;
  25602. }
  25603. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25604. // Is Ready For Mesh
  25605. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25606. var step = _a[_i];
  25607. if (!step.action(mesh, hardwareInstancedRendering)) {
  25608. return false;
  25609. }
  25610. }
  25611. }
  25612. // Post-processes
  25613. if (this.activeCameras && this.activeCameras.length > 0) {
  25614. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25615. var camera = _c[_b];
  25616. if (!camera.isReady(true)) {
  25617. return false;
  25618. }
  25619. }
  25620. }
  25621. else if (this.activeCamera) {
  25622. if (!this.activeCamera.isReady(true)) {
  25623. return false;
  25624. }
  25625. }
  25626. // Particles
  25627. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25628. var particleSystem = _e[_d];
  25629. if (!particleSystem.isReady()) {
  25630. return false;
  25631. }
  25632. }
  25633. return true;
  25634. };
  25635. /** Resets all cached information relative to material (including effect and visibility) */
  25636. Scene.prototype.resetCachedMaterial = function () {
  25637. this._cachedMaterial = null;
  25638. this._cachedEffect = null;
  25639. this._cachedVisibility = null;
  25640. };
  25641. /**
  25642. * Registers a function to be called before every frame render
  25643. * @param func defines the function to register
  25644. */
  25645. Scene.prototype.registerBeforeRender = function (func) {
  25646. this.onBeforeRenderObservable.add(func);
  25647. };
  25648. /**
  25649. * Unregisters a function called before every frame render
  25650. * @param func defines the function to unregister
  25651. */
  25652. Scene.prototype.unregisterBeforeRender = function (func) {
  25653. this.onBeforeRenderObservable.removeCallback(func);
  25654. };
  25655. /**
  25656. * Registers a function to be called after every frame render
  25657. * @param func defines the function to register
  25658. */
  25659. Scene.prototype.registerAfterRender = function (func) {
  25660. this.onAfterRenderObservable.add(func);
  25661. };
  25662. /**
  25663. * Unregisters a function called after every frame render
  25664. * @param func defines the function to unregister
  25665. */
  25666. Scene.prototype.unregisterAfterRender = function (func) {
  25667. this.onAfterRenderObservable.removeCallback(func);
  25668. };
  25669. Scene.prototype._executeOnceBeforeRender = function (func) {
  25670. var _this = this;
  25671. var execFunc = function () {
  25672. func();
  25673. setTimeout(function () {
  25674. _this.unregisterBeforeRender(execFunc);
  25675. });
  25676. };
  25677. this.registerBeforeRender(execFunc);
  25678. };
  25679. /**
  25680. * The provided function will run before render once and will be disposed afterwards.
  25681. * A timeout delay can be provided so that the function will be executed in N ms.
  25682. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25683. * @param func The function to be executed.
  25684. * @param timeout optional delay in ms
  25685. */
  25686. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25687. var _this = this;
  25688. if (timeout !== undefined) {
  25689. setTimeout(function () {
  25690. _this._executeOnceBeforeRender(func);
  25691. }, timeout);
  25692. }
  25693. else {
  25694. this._executeOnceBeforeRender(func);
  25695. }
  25696. };
  25697. /** @hidden */
  25698. Scene.prototype._addPendingData = function (data) {
  25699. this._pendingData.push(data);
  25700. };
  25701. /** @hidden */
  25702. Scene.prototype._removePendingData = function (data) {
  25703. var wasLoading = this.isLoading;
  25704. var index = this._pendingData.indexOf(data);
  25705. if (index !== -1) {
  25706. this._pendingData.splice(index, 1);
  25707. }
  25708. if (wasLoading && !this.isLoading) {
  25709. this.onDataLoadedObservable.notifyObservers(this);
  25710. }
  25711. };
  25712. /**
  25713. * Returns the number of items waiting to be loaded
  25714. * @returns the number of items waiting to be loaded
  25715. */
  25716. Scene.prototype.getWaitingItemsCount = function () {
  25717. return this._pendingData.length;
  25718. };
  25719. Object.defineProperty(Scene.prototype, "isLoading", {
  25720. /**
  25721. * Returns a boolean indicating if the scene is still loading data
  25722. */
  25723. get: function () {
  25724. return this._pendingData.length > 0;
  25725. },
  25726. enumerable: true,
  25727. configurable: true
  25728. });
  25729. /**
  25730. * Registers a function to be executed when the scene is ready
  25731. * @param {Function} func - the function to be executed
  25732. */
  25733. Scene.prototype.executeWhenReady = function (func) {
  25734. var _this = this;
  25735. this.onReadyObservable.add(func);
  25736. if (this._executeWhenReadyTimeoutId !== -1) {
  25737. return;
  25738. }
  25739. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25740. _this._checkIsReady();
  25741. }, 150);
  25742. };
  25743. /**
  25744. * Returns a promise that resolves when the scene is ready
  25745. * @returns A promise that resolves when the scene is ready
  25746. */
  25747. Scene.prototype.whenReadyAsync = function () {
  25748. var _this = this;
  25749. return new Promise(function (resolve) {
  25750. _this.executeWhenReady(function () {
  25751. resolve();
  25752. });
  25753. });
  25754. };
  25755. /** @hidden */
  25756. Scene.prototype._checkIsReady = function () {
  25757. var _this = this;
  25758. this._registerTransientComponents();
  25759. if (this.isReady()) {
  25760. this.onReadyObservable.notifyObservers(this);
  25761. this.onReadyObservable.clear();
  25762. this._executeWhenReadyTimeoutId = -1;
  25763. return;
  25764. }
  25765. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25766. _this._checkIsReady();
  25767. }, 150);
  25768. };
  25769. // Animations
  25770. /**
  25771. * Will start the animation sequence of a given target
  25772. * @param target defines the target
  25773. * @param from defines from which frame should animation start
  25774. * @param to defines until which frame should animation run.
  25775. * @param weight defines the weight to apply to the animation (1.0 by default)
  25776. * @param loop defines if the animation loops
  25777. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25778. * @param onAnimationEnd defines the function to be executed when the animation ends
  25779. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25780. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25781. * @returns the animatable object created for this animation
  25782. */
  25783. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25784. if (weight === void 0) { weight = 1.0; }
  25785. if (speedRatio === void 0) { speedRatio = 1.0; }
  25786. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25787. returnedAnimatable.weight = weight;
  25788. return returnedAnimatable;
  25789. };
  25790. /**
  25791. * Will start the animation sequence of a given target
  25792. * @param target defines the target
  25793. * @param from defines from which frame should animation start
  25794. * @param to defines until which frame should animation run.
  25795. * @param loop defines if the animation loops
  25796. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25797. * @param onAnimationEnd defines the function to be executed when the animation ends
  25798. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25799. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25800. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25801. * @returns the animatable object created for this animation
  25802. */
  25803. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25804. if (speedRatio === void 0) { speedRatio = 1.0; }
  25805. if (stopCurrent === void 0) { stopCurrent = true; }
  25806. if (from > to && speedRatio > 0) {
  25807. speedRatio *= -1;
  25808. }
  25809. if (stopCurrent) {
  25810. this.stopAnimation(target, undefined, targetMask);
  25811. }
  25812. if (!animatable) {
  25813. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25814. }
  25815. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25816. // Local animations
  25817. if (target.animations && shouldRunTargetAnimations) {
  25818. animatable.appendAnimations(target, target.animations);
  25819. }
  25820. // Children animations
  25821. if (target.getAnimatables) {
  25822. var animatables = target.getAnimatables();
  25823. for (var index = 0; index < animatables.length; index++) {
  25824. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25825. }
  25826. }
  25827. animatable.reset();
  25828. return animatable;
  25829. };
  25830. /**
  25831. * Begin a new animation on a given node
  25832. * @param target defines the target where the animation will take place
  25833. * @param animations defines the list of animations to start
  25834. * @param from defines the initial value
  25835. * @param to defines the final value
  25836. * @param loop defines if you want animation to loop (off by default)
  25837. * @param speedRatio defines the speed ratio to apply to all animations
  25838. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25839. * @returns the list of created animatables
  25840. */
  25841. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25842. if (speedRatio === undefined) {
  25843. speedRatio = 1.0;
  25844. }
  25845. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25846. return animatable;
  25847. };
  25848. /**
  25849. * Begin a new animation on a given node and its hierarchy
  25850. * @param target defines the root node where the animation will take place
  25851. * @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.
  25852. * @param animations defines the list of animations to start
  25853. * @param from defines the initial value
  25854. * @param to defines the final value
  25855. * @param loop defines if you want animation to loop (off by default)
  25856. * @param speedRatio defines the speed ratio to apply to all animations
  25857. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25858. * @returns the list of animatables created for all nodes
  25859. */
  25860. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25861. var children = target.getDescendants(directDescendantsOnly);
  25862. var result = [];
  25863. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25864. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25865. var child = children_1[_i];
  25866. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25867. }
  25868. return result;
  25869. };
  25870. /**
  25871. * Gets the animatable associated with a specific target
  25872. * @param target defines the target of the animatable
  25873. * @returns the required animatable if found
  25874. */
  25875. Scene.prototype.getAnimatableByTarget = function (target) {
  25876. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25877. if (this._activeAnimatables[index].target === target) {
  25878. return this._activeAnimatables[index];
  25879. }
  25880. }
  25881. return null;
  25882. };
  25883. /**
  25884. * Gets all animatables associated with a given target
  25885. * @param target defines the target to look animatables for
  25886. * @returns an array of Animatables
  25887. */
  25888. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25889. var result = [];
  25890. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25891. if (this._activeAnimatables[index].target === target) {
  25892. result.push(this._activeAnimatables[index]);
  25893. }
  25894. }
  25895. return result;
  25896. };
  25897. Object.defineProperty(Scene.prototype, "animatables", {
  25898. /**
  25899. * Gets all animatable attached to the scene
  25900. */
  25901. get: function () {
  25902. return this._activeAnimatables;
  25903. },
  25904. enumerable: true,
  25905. configurable: true
  25906. });
  25907. /**
  25908. * Will stop the animation of the given target
  25909. * @param target - the target
  25910. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  25911. * @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)
  25912. */
  25913. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  25914. var animatables = this.getAllAnimatablesByTarget(target);
  25915. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25916. var animatable = animatables_1[_i];
  25917. animatable.stop(animationName, targetMask);
  25918. }
  25919. };
  25920. /**
  25921. * Stops and removes all animations that have been applied to the scene
  25922. */
  25923. Scene.prototype.stopAllAnimations = function () {
  25924. if (this._activeAnimatables) {
  25925. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25926. this._activeAnimatables[i].stop();
  25927. }
  25928. this._activeAnimatables = [];
  25929. }
  25930. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25931. var group = _a[_i];
  25932. group.stop();
  25933. }
  25934. };
  25935. Scene.prototype._animate = function () {
  25936. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25937. return;
  25938. }
  25939. // Getting time
  25940. var now = BABYLON.Tools.Now;
  25941. if (!this._animationTimeLast) {
  25942. if (this._pendingData.length > 0) {
  25943. return;
  25944. }
  25945. this._animationTimeLast = now;
  25946. }
  25947. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25948. this._animationTime += deltaTime;
  25949. this._animationTimeLast = now;
  25950. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25951. this._activeAnimatables[index]._animate(this._animationTime);
  25952. }
  25953. // Late animation bindings
  25954. this._processLateAnimationBindings();
  25955. };
  25956. /** @hidden */
  25957. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25958. var target = runtimeAnimation.target;
  25959. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25960. if (!target._lateAnimationHolders) {
  25961. target._lateAnimationHolders = {};
  25962. }
  25963. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25964. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25965. totalWeight: 0,
  25966. animations: [],
  25967. originalValue: originalValue
  25968. };
  25969. }
  25970. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25971. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25972. };
  25973. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25974. var normalizer = 1.0;
  25975. var finalPosition = BABYLON.Tmp.Vector3[0];
  25976. var finalScaling = BABYLON.Tmp.Vector3[1];
  25977. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25978. var startIndex = 0;
  25979. var originalAnimation = holder.animations[0];
  25980. var originalValue = holder.originalValue;
  25981. var scale = 1;
  25982. if (holder.totalWeight < 1.0) {
  25983. // We need to mix the original value in
  25984. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25985. scale = 1.0 - holder.totalWeight;
  25986. }
  25987. else {
  25988. startIndex = 1;
  25989. // We need to normalize the weights
  25990. normalizer = holder.totalWeight;
  25991. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25992. scale = originalAnimation.weight / normalizer;
  25993. if (scale == 1) {
  25994. return originalAnimation.currentValue;
  25995. }
  25996. }
  25997. finalScaling.scaleInPlace(scale);
  25998. finalPosition.scaleInPlace(scale);
  25999. finalQuaternion.scaleInPlace(scale);
  26000. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26001. var runtimeAnimation = holder.animations[animIndex];
  26002. var scale = runtimeAnimation.weight / normalizer;
  26003. var currentPosition = BABYLON.Tmp.Vector3[2];
  26004. var currentScaling = BABYLON.Tmp.Vector3[3];
  26005. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26006. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26007. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26008. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26009. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26010. }
  26011. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26012. return originalAnimation._workValue;
  26013. };
  26014. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26015. var originalAnimation = holder.animations[0];
  26016. var originalValue = holder.originalValue;
  26017. if (holder.animations.length === 1) {
  26018. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26019. }
  26020. var normalizer = 1.0;
  26021. var quaternions;
  26022. var weights;
  26023. if (holder.totalWeight < 1.0) {
  26024. var scale = 1.0 - holder.totalWeight;
  26025. quaternions = [];
  26026. weights = [];
  26027. quaternions.push(originalValue);
  26028. weights.push(scale);
  26029. }
  26030. else {
  26031. if (holder.animations.length === 2) { // Slerp as soon as we can
  26032. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26033. }
  26034. quaternions = [];
  26035. weights = [];
  26036. normalizer = holder.totalWeight;
  26037. }
  26038. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26039. var runtimeAnimation = holder.animations[animIndex];
  26040. quaternions.push(runtimeAnimation.currentValue);
  26041. weights.push(runtimeAnimation.weight / normalizer);
  26042. }
  26043. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26044. var cumulativeAmount = 0;
  26045. var cumulativeQuaternion = null;
  26046. for (var index = 0; index < quaternions.length;) {
  26047. if (!cumulativeQuaternion) {
  26048. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26049. cumulativeAmount = weights[index] + weights[index + 1];
  26050. index += 2;
  26051. continue;
  26052. }
  26053. cumulativeAmount += weights[index];
  26054. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26055. index++;
  26056. }
  26057. return cumulativeQuaternion;
  26058. };
  26059. Scene.prototype._processLateAnimationBindings = function () {
  26060. if (!this._registeredForLateAnimationBindings.length) {
  26061. return;
  26062. }
  26063. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26064. var target = this._registeredForLateAnimationBindings.data[index];
  26065. for (var path in target._lateAnimationHolders) {
  26066. var holder = target._lateAnimationHolders[path];
  26067. var originalAnimation = holder.animations[0];
  26068. var originalValue = holder.originalValue;
  26069. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26070. var finalValue = void 0;
  26071. if (matrixDecomposeMode) {
  26072. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26073. }
  26074. else {
  26075. var quaternionMode = originalValue.w !== undefined;
  26076. if (quaternionMode) {
  26077. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26078. }
  26079. else {
  26080. var startIndex = 0;
  26081. var normalizer = 1.0;
  26082. if (holder.totalWeight < 1.0) {
  26083. // We need to mix the original value in
  26084. if (originalValue.scale) {
  26085. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26086. }
  26087. else {
  26088. finalValue = originalValue * (1.0 - holder.totalWeight);
  26089. }
  26090. }
  26091. else {
  26092. // We need to normalize the weights
  26093. normalizer = holder.totalWeight;
  26094. var scale_1 = originalAnimation.weight / normalizer;
  26095. if (scale_1 !== 1) {
  26096. if (originalAnimation.currentValue.scale) {
  26097. finalValue = originalAnimation.currentValue.scale(scale_1);
  26098. }
  26099. else {
  26100. finalValue = originalAnimation.currentValue * scale_1;
  26101. }
  26102. }
  26103. else {
  26104. finalValue = originalAnimation.currentValue;
  26105. }
  26106. startIndex = 1;
  26107. }
  26108. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26109. var runtimeAnimation = holder.animations[animIndex];
  26110. var scale = runtimeAnimation.weight / normalizer;
  26111. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26112. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26113. }
  26114. else {
  26115. finalValue += runtimeAnimation.currentValue * scale;
  26116. }
  26117. }
  26118. }
  26119. }
  26120. target[path] = finalValue;
  26121. }
  26122. target._lateAnimationHolders = {};
  26123. }
  26124. this._registeredForLateAnimationBindings.reset();
  26125. };
  26126. // Matrix
  26127. /** @hidden */
  26128. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26129. this._useAlternateCameraConfiguration = active;
  26130. };
  26131. /**
  26132. * Gets the current view matrix
  26133. * @returns a Matrix
  26134. */
  26135. Scene.prototype.getViewMatrix = function () {
  26136. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26137. };
  26138. /**
  26139. * Gets the current projection matrix
  26140. * @returns a Matrix
  26141. */
  26142. Scene.prototype.getProjectionMatrix = function () {
  26143. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26144. };
  26145. /**
  26146. * Gets the current transform matrix
  26147. * @returns a Matrix made of View * Projection
  26148. */
  26149. Scene.prototype.getTransformMatrix = function () {
  26150. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26151. };
  26152. /**
  26153. * Sets the current transform matrix
  26154. * @param view defines the View matrix to use
  26155. * @param projection defines the Projection matrix to use
  26156. */
  26157. Scene.prototype.setTransformMatrix = function (view, projection) {
  26158. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26159. return;
  26160. }
  26161. this._viewUpdateFlag = view.updateFlag;
  26162. this._projectionUpdateFlag = projection.updateFlag;
  26163. this._viewMatrix = view;
  26164. this._projectionMatrix = projection;
  26165. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26166. // Update frustum
  26167. if (!this._frustumPlanes) {
  26168. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26169. }
  26170. else {
  26171. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26172. }
  26173. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26174. var otherCamera = this.activeCamera._alternateCamera;
  26175. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26176. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26177. }
  26178. if (this._sceneUbo.useUbo) {
  26179. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26180. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26181. this._sceneUbo.update();
  26182. }
  26183. };
  26184. /** @hidden */
  26185. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26186. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26187. return;
  26188. }
  26189. this._alternateViewUpdateFlag = view.updateFlag;
  26190. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26191. this._alternateViewMatrix = view;
  26192. this._alternateProjectionMatrix = projection;
  26193. if (!this._alternateTransformMatrix) {
  26194. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26195. }
  26196. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26197. if (!this._alternateSceneUbo) {
  26198. this._createAlternateUbo();
  26199. }
  26200. if (this._alternateSceneUbo.useUbo) {
  26201. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26202. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26203. this._alternateSceneUbo.update();
  26204. }
  26205. };
  26206. /**
  26207. * Gets the uniform buffer used to store scene data
  26208. * @returns a UniformBuffer
  26209. */
  26210. Scene.prototype.getSceneUniformBuffer = function () {
  26211. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26212. };
  26213. /**
  26214. * Gets an unique (relatively to the current scene) Id
  26215. * @returns an unique number for the scene
  26216. */
  26217. Scene.prototype.getUniqueId = function () {
  26218. var result = Scene._uniqueIdCounter;
  26219. Scene._uniqueIdCounter++;
  26220. return result;
  26221. };
  26222. /**
  26223. * Add a mesh to the list of scene's meshes
  26224. * @param newMesh defines the mesh to add
  26225. * @param recursive if all child meshes should also be added to the scene
  26226. */
  26227. Scene.prototype.addMesh = function (newMesh, recursive) {
  26228. var _this = this;
  26229. if (recursive === void 0) { recursive = false; }
  26230. this.meshes.push(newMesh);
  26231. //notify the collision coordinator
  26232. if (this.collisionCoordinator) {
  26233. this.collisionCoordinator.onMeshAdded(newMesh);
  26234. }
  26235. newMesh._resyncLightSources();
  26236. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26237. if (recursive) {
  26238. newMesh.getChildMeshes().forEach(function (m) {
  26239. _this.addMesh(m);
  26240. });
  26241. }
  26242. };
  26243. /**
  26244. * Remove a mesh for the list of scene's meshes
  26245. * @param toRemove defines the mesh to remove
  26246. * @param recursive if all child meshes should also be removed from the scene
  26247. * @returns the index where the mesh was in the mesh list
  26248. */
  26249. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26250. var _this = this;
  26251. if (recursive === void 0) { recursive = false; }
  26252. var index = this.meshes.indexOf(toRemove);
  26253. if (index !== -1) {
  26254. // Remove from the scene if mesh found
  26255. this.meshes.splice(index, 1);
  26256. }
  26257. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26258. if (recursive) {
  26259. toRemove.getChildMeshes().forEach(function (m) {
  26260. _this.removeMesh(m);
  26261. });
  26262. }
  26263. return index;
  26264. };
  26265. /**
  26266. * Add a transform node to the list of scene's transform nodes
  26267. * @param newTransformNode defines the transform node to add
  26268. */
  26269. Scene.prototype.addTransformNode = function (newTransformNode) {
  26270. this.transformNodes.push(newTransformNode);
  26271. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26272. };
  26273. /**
  26274. * Remove a transform node for the list of scene's transform nodes
  26275. * @param toRemove defines the transform node to remove
  26276. * @returns the index where the transform node was in the transform node list
  26277. */
  26278. Scene.prototype.removeTransformNode = function (toRemove) {
  26279. var index = this.transformNodes.indexOf(toRemove);
  26280. if (index !== -1) {
  26281. // Remove from the scene if found
  26282. this.transformNodes.splice(index, 1);
  26283. }
  26284. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26285. return index;
  26286. };
  26287. /**
  26288. * Remove a skeleton for the list of scene's skeletons
  26289. * @param toRemove defines the skeleton to remove
  26290. * @returns the index where the skeleton was in the skeleton list
  26291. */
  26292. Scene.prototype.removeSkeleton = function (toRemove) {
  26293. var index = this.skeletons.indexOf(toRemove);
  26294. if (index !== -1) {
  26295. // Remove from the scene if found
  26296. this.skeletons.splice(index, 1);
  26297. }
  26298. return index;
  26299. };
  26300. /**
  26301. * Remove a morph target for the list of scene's morph targets
  26302. * @param toRemove defines the morph target to remove
  26303. * @returns the index where the morph target was in the morph target list
  26304. */
  26305. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26306. var index = this.morphTargetManagers.indexOf(toRemove);
  26307. if (index !== -1) {
  26308. // Remove from the scene if found
  26309. this.morphTargetManagers.splice(index, 1);
  26310. }
  26311. return index;
  26312. };
  26313. /**
  26314. * Remove a light for the list of scene's lights
  26315. * @param toRemove defines the light to remove
  26316. * @returns the index where the light was in the light list
  26317. */
  26318. Scene.prototype.removeLight = function (toRemove) {
  26319. var index = this.lights.indexOf(toRemove);
  26320. if (index !== -1) {
  26321. // Remove from meshes
  26322. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26323. var mesh = _a[_i];
  26324. mesh._removeLightSource(toRemove);
  26325. }
  26326. // Remove from the scene if mesh found
  26327. this.lights.splice(index, 1);
  26328. this.sortLightsByPriority();
  26329. }
  26330. this.onLightRemovedObservable.notifyObservers(toRemove);
  26331. return index;
  26332. };
  26333. /**
  26334. * Remove a camera for the list of scene's cameras
  26335. * @param toRemove defines the camera to remove
  26336. * @returns the index where the camera was in the camera list
  26337. */
  26338. Scene.prototype.removeCamera = function (toRemove) {
  26339. var index = this.cameras.indexOf(toRemove);
  26340. if (index !== -1) {
  26341. // Remove from the scene if mesh found
  26342. this.cameras.splice(index, 1);
  26343. }
  26344. // Remove from activeCameras
  26345. var index2 = this.activeCameras.indexOf(toRemove);
  26346. if (index2 !== -1) {
  26347. // Remove from the scene if mesh found
  26348. this.activeCameras.splice(index2, 1);
  26349. }
  26350. // Reset the activeCamera
  26351. if (this.activeCamera === toRemove) {
  26352. if (this.cameras.length > 0) {
  26353. this.activeCamera = this.cameras[0];
  26354. }
  26355. else {
  26356. this.activeCamera = null;
  26357. }
  26358. }
  26359. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26360. return index;
  26361. };
  26362. /**
  26363. * Remove a particle system for the list of scene's particle systems
  26364. * @param toRemove defines the particle system to remove
  26365. * @returns the index where the particle system was in the particle system list
  26366. */
  26367. Scene.prototype.removeParticleSystem = function (toRemove) {
  26368. var index = this.particleSystems.indexOf(toRemove);
  26369. if (index !== -1) {
  26370. this.particleSystems.splice(index, 1);
  26371. }
  26372. return index;
  26373. };
  26374. /**
  26375. * Remove a animation for the list of scene's animations
  26376. * @param toRemove defines the animation to remove
  26377. * @returns the index where the animation was in the animation list
  26378. */
  26379. Scene.prototype.removeAnimation = function (toRemove) {
  26380. var index = this.animations.indexOf(toRemove);
  26381. if (index !== -1) {
  26382. this.animations.splice(index, 1);
  26383. }
  26384. return index;
  26385. };
  26386. /**
  26387. * Removes the given animation group from this scene.
  26388. * @param toRemove The animation group to remove
  26389. * @returns The index of the removed animation group
  26390. */
  26391. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26392. var index = this.animationGroups.indexOf(toRemove);
  26393. if (index !== -1) {
  26394. this.animationGroups.splice(index, 1);
  26395. }
  26396. return index;
  26397. };
  26398. /**
  26399. * Removes the given multi-material from this scene.
  26400. * @param toRemove The multi-material to remove
  26401. * @returns The index of the removed multi-material
  26402. */
  26403. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26404. var index = this.multiMaterials.indexOf(toRemove);
  26405. if (index !== -1) {
  26406. this.multiMaterials.splice(index, 1);
  26407. }
  26408. return index;
  26409. };
  26410. /**
  26411. * Removes the given material from this scene.
  26412. * @param toRemove The material to remove
  26413. * @returns The index of the removed material
  26414. */
  26415. Scene.prototype.removeMaterial = function (toRemove) {
  26416. var index = this.materials.indexOf(toRemove);
  26417. if (index !== -1) {
  26418. this.materials.splice(index, 1);
  26419. }
  26420. return index;
  26421. };
  26422. /**
  26423. * Removes the given action manager from this scene.
  26424. * @param toRemove The action manager to remove
  26425. * @returns The index of the removed action manager
  26426. */
  26427. Scene.prototype.removeActionManager = function (toRemove) {
  26428. var index = this.actionManagers.indexOf(toRemove);
  26429. if (index !== -1) {
  26430. this.actionManagers.splice(index, 1);
  26431. }
  26432. return index;
  26433. };
  26434. /**
  26435. * Removes the given texture from this scene.
  26436. * @param toRemove The texture to remove
  26437. * @returns The index of the removed texture
  26438. */
  26439. Scene.prototype.removeTexture = function (toRemove) {
  26440. var index = this.textures.indexOf(toRemove);
  26441. if (index !== -1) {
  26442. this.textures.splice(index, 1);
  26443. }
  26444. return index;
  26445. };
  26446. /**
  26447. * Adds the given light to this scene
  26448. * @param newLight The light to add
  26449. */
  26450. Scene.prototype.addLight = function (newLight) {
  26451. this.lights.push(newLight);
  26452. this.sortLightsByPriority();
  26453. // Add light to all meshes (To support if the light is removed and then readded)
  26454. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26455. var mesh = _a[_i];
  26456. if (mesh._lightSources.indexOf(newLight) === -1) {
  26457. mesh._lightSources.push(newLight);
  26458. mesh._resyncLightSources();
  26459. }
  26460. }
  26461. this.onNewLightAddedObservable.notifyObservers(newLight);
  26462. };
  26463. /**
  26464. * Sorts the list list based on light priorities
  26465. */
  26466. Scene.prototype.sortLightsByPriority = function () {
  26467. if (this.requireLightSorting) {
  26468. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26469. }
  26470. };
  26471. /**
  26472. * Adds the given camera to this scene
  26473. * @param newCamera The camera to add
  26474. */
  26475. Scene.prototype.addCamera = function (newCamera) {
  26476. this.cameras.push(newCamera);
  26477. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26478. };
  26479. /**
  26480. * Adds the given skeleton to this scene
  26481. * @param newSkeleton The skeleton to add
  26482. */
  26483. Scene.prototype.addSkeleton = function (newSkeleton) {
  26484. this.skeletons.push(newSkeleton);
  26485. };
  26486. /**
  26487. * Adds the given particle system to this scene
  26488. * @param newParticleSystem The particle system to add
  26489. */
  26490. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26491. this.particleSystems.push(newParticleSystem);
  26492. };
  26493. /**
  26494. * Adds the given animation to this scene
  26495. * @param newAnimation The animation to add
  26496. */
  26497. Scene.prototype.addAnimation = function (newAnimation) {
  26498. this.animations.push(newAnimation);
  26499. };
  26500. /**
  26501. * Adds the given animation group to this scene.
  26502. * @param newAnimationGroup The animation group to add
  26503. */
  26504. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26505. this.animationGroups.push(newAnimationGroup);
  26506. };
  26507. /**
  26508. * Adds the given multi-material to this scene
  26509. * @param newMultiMaterial The multi-material to add
  26510. */
  26511. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26512. this.multiMaterials.push(newMultiMaterial);
  26513. };
  26514. /**
  26515. * Adds the given material to this scene
  26516. * @param newMaterial The material to add
  26517. */
  26518. Scene.prototype.addMaterial = function (newMaterial) {
  26519. this.materials.push(newMaterial);
  26520. };
  26521. /**
  26522. * Adds the given morph target to this scene
  26523. * @param newMorphTargetManager The morph target to add
  26524. */
  26525. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26526. this.morphTargetManagers.push(newMorphTargetManager);
  26527. };
  26528. /**
  26529. * Adds the given geometry to this scene
  26530. * @param newGeometry The geometry to add
  26531. */
  26532. Scene.prototype.addGeometry = function (newGeometry) {
  26533. this.geometries.push(newGeometry);
  26534. };
  26535. /**
  26536. * Adds the given action manager to this scene
  26537. * @param newActionManager The action manager to add
  26538. */
  26539. Scene.prototype.addActionManager = function (newActionManager) {
  26540. this.actionManagers.push(newActionManager);
  26541. };
  26542. /**
  26543. * Adds the given texture to this scene.
  26544. * @param newTexture The texture to add
  26545. */
  26546. Scene.prototype.addTexture = function (newTexture) {
  26547. this.textures.push(newTexture);
  26548. };
  26549. /**
  26550. * Switch active camera
  26551. * @param newCamera defines the new active camera
  26552. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26553. */
  26554. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26555. if (attachControl === void 0) { attachControl = true; }
  26556. var canvas = this._engine.getRenderingCanvas();
  26557. if (!canvas) {
  26558. return;
  26559. }
  26560. if (this.activeCamera) {
  26561. this.activeCamera.detachControl(canvas);
  26562. }
  26563. this.activeCamera = newCamera;
  26564. if (attachControl) {
  26565. newCamera.attachControl(canvas);
  26566. }
  26567. };
  26568. /**
  26569. * sets the active camera of the scene using its ID
  26570. * @param id defines the camera's ID
  26571. * @return the new active camera or null if none found.
  26572. */
  26573. Scene.prototype.setActiveCameraByID = function (id) {
  26574. var camera = this.getCameraByID(id);
  26575. if (camera) {
  26576. this.activeCamera = camera;
  26577. return camera;
  26578. }
  26579. return null;
  26580. };
  26581. /**
  26582. * sets the active camera of the scene using its name
  26583. * @param name defines the camera's name
  26584. * @returns the new active camera or null if none found.
  26585. */
  26586. Scene.prototype.setActiveCameraByName = function (name) {
  26587. var camera = this.getCameraByName(name);
  26588. if (camera) {
  26589. this.activeCamera = camera;
  26590. return camera;
  26591. }
  26592. return null;
  26593. };
  26594. /**
  26595. * get an animation group using its name
  26596. * @param name defines the material's name
  26597. * @return the animation group or null if none found.
  26598. */
  26599. Scene.prototype.getAnimationGroupByName = function (name) {
  26600. for (var index = 0; index < this.animationGroups.length; index++) {
  26601. if (this.animationGroups[index].name === name) {
  26602. return this.animationGroups[index];
  26603. }
  26604. }
  26605. return null;
  26606. };
  26607. /**
  26608. * get a material using its id
  26609. * @param id defines the material's ID
  26610. * @return the material or null if none found.
  26611. */
  26612. Scene.prototype.getMaterialByID = function (id) {
  26613. for (var index = 0; index < this.materials.length; index++) {
  26614. if (this.materials[index].id === id) {
  26615. return this.materials[index];
  26616. }
  26617. }
  26618. return null;
  26619. };
  26620. /**
  26621. * Gets a material using its name
  26622. * @param name defines the material's name
  26623. * @return the material or null if none found.
  26624. */
  26625. Scene.prototype.getMaterialByName = function (name) {
  26626. for (var index = 0; index < this.materials.length; index++) {
  26627. if (this.materials[index].name === name) {
  26628. return this.materials[index];
  26629. }
  26630. }
  26631. return null;
  26632. };
  26633. /**
  26634. * Gets a camera using its id
  26635. * @param id defines the id to look for
  26636. * @returns the camera or null if not found
  26637. */
  26638. Scene.prototype.getCameraByID = function (id) {
  26639. for (var index = 0; index < this.cameras.length; index++) {
  26640. if (this.cameras[index].id === id) {
  26641. return this.cameras[index];
  26642. }
  26643. }
  26644. return null;
  26645. };
  26646. /**
  26647. * Gets a camera using its unique id
  26648. * @param uniqueId defines the unique id to look for
  26649. * @returns the camera or null if not found
  26650. */
  26651. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26652. for (var index = 0; index < this.cameras.length; index++) {
  26653. if (this.cameras[index].uniqueId === uniqueId) {
  26654. return this.cameras[index];
  26655. }
  26656. }
  26657. return null;
  26658. };
  26659. /**
  26660. * Gets a camera using its name
  26661. * @param name defines the camera's name
  26662. * @return the camera or null if none found.
  26663. */
  26664. Scene.prototype.getCameraByName = function (name) {
  26665. for (var index = 0; index < this.cameras.length; index++) {
  26666. if (this.cameras[index].name === name) {
  26667. return this.cameras[index];
  26668. }
  26669. }
  26670. return null;
  26671. };
  26672. /**
  26673. * Gets a bone using its id
  26674. * @param id defines the bone's id
  26675. * @return the bone or null if not found
  26676. */
  26677. Scene.prototype.getBoneByID = function (id) {
  26678. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26679. var skeleton = this.skeletons[skeletonIndex];
  26680. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26681. if (skeleton.bones[boneIndex].id === id) {
  26682. return skeleton.bones[boneIndex];
  26683. }
  26684. }
  26685. }
  26686. return null;
  26687. };
  26688. /**
  26689. * Gets a bone using its id
  26690. * @param name defines the bone's name
  26691. * @return the bone or null if not found
  26692. */
  26693. Scene.prototype.getBoneByName = function (name) {
  26694. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26695. var skeleton = this.skeletons[skeletonIndex];
  26696. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26697. if (skeleton.bones[boneIndex].name === name) {
  26698. return skeleton.bones[boneIndex];
  26699. }
  26700. }
  26701. }
  26702. return null;
  26703. };
  26704. /**
  26705. * Gets a light node using its name
  26706. * @param name defines the the light's name
  26707. * @return the light or null if none found.
  26708. */
  26709. Scene.prototype.getLightByName = function (name) {
  26710. for (var index = 0; index < this.lights.length; index++) {
  26711. if (this.lights[index].name === name) {
  26712. return this.lights[index];
  26713. }
  26714. }
  26715. return null;
  26716. };
  26717. /**
  26718. * Gets a light node using its id
  26719. * @param id defines the light's id
  26720. * @return the light or null if none found.
  26721. */
  26722. Scene.prototype.getLightByID = function (id) {
  26723. for (var index = 0; index < this.lights.length; index++) {
  26724. if (this.lights[index].id === id) {
  26725. return this.lights[index];
  26726. }
  26727. }
  26728. return null;
  26729. };
  26730. /**
  26731. * Gets a light node using its scene-generated unique ID
  26732. * @param uniqueId defines the light's unique id
  26733. * @return the light or null if none found.
  26734. */
  26735. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26736. for (var index = 0; index < this.lights.length; index++) {
  26737. if (this.lights[index].uniqueId === uniqueId) {
  26738. return this.lights[index];
  26739. }
  26740. }
  26741. return null;
  26742. };
  26743. /**
  26744. * Gets a particle system by id
  26745. * @param id defines the particle system id
  26746. * @return the corresponding system or null if none found
  26747. */
  26748. Scene.prototype.getParticleSystemByID = function (id) {
  26749. for (var index = 0; index < this.particleSystems.length; index++) {
  26750. if (this.particleSystems[index].id === id) {
  26751. return this.particleSystems[index];
  26752. }
  26753. }
  26754. return null;
  26755. };
  26756. /**
  26757. * Gets a geometry using its ID
  26758. * @param id defines the geometry's id
  26759. * @return the geometry or null if none found.
  26760. */
  26761. Scene.prototype.getGeometryByID = function (id) {
  26762. for (var index = 0; index < this.geometries.length; index++) {
  26763. if (this.geometries[index].id === id) {
  26764. return this.geometries[index];
  26765. }
  26766. }
  26767. return null;
  26768. };
  26769. /**
  26770. * Add a new geometry to this scene
  26771. * @param geometry defines the geometry to be added to the scene.
  26772. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26773. * @return a boolean defining if the geometry was added or not
  26774. */
  26775. Scene.prototype.pushGeometry = function (geometry, force) {
  26776. if (!force && this.getGeometryByID(geometry.id)) {
  26777. return false;
  26778. }
  26779. this.geometries.push(geometry);
  26780. //notify the collision coordinator
  26781. if (this.collisionCoordinator) {
  26782. this.collisionCoordinator.onGeometryAdded(geometry);
  26783. }
  26784. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26785. return true;
  26786. };
  26787. /**
  26788. * Removes an existing geometry
  26789. * @param geometry defines the geometry to be removed from the scene
  26790. * @return a boolean defining if the geometry was removed or not
  26791. */
  26792. Scene.prototype.removeGeometry = function (geometry) {
  26793. var index = this.geometries.indexOf(geometry);
  26794. if (index > -1) {
  26795. this.geometries.splice(index, 1);
  26796. //notify the collision coordinator
  26797. if (this.collisionCoordinator) {
  26798. this.collisionCoordinator.onGeometryDeleted(geometry);
  26799. }
  26800. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26801. return true;
  26802. }
  26803. return false;
  26804. };
  26805. /**
  26806. * Gets the list of geometries attached to the scene
  26807. * @returns an array of Geometry
  26808. */
  26809. Scene.prototype.getGeometries = function () {
  26810. return this.geometries;
  26811. };
  26812. /**
  26813. * Gets the first added mesh found of a given ID
  26814. * @param id defines the id to search for
  26815. * @return the mesh found or null if not found at all
  26816. */
  26817. Scene.prototype.getMeshByID = function (id) {
  26818. for (var index = 0; index < this.meshes.length; index++) {
  26819. if (this.meshes[index].id === id) {
  26820. return this.meshes[index];
  26821. }
  26822. }
  26823. return null;
  26824. };
  26825. /**
  26826. * Gets a list of meshes using their id
  26827. * @param id defines the id to search for
  26828. * @returns a list of meshes
  26829. */
  26830. Scene.prototype.getMeshesByID = function (id) {
  26831. return this.meshes.filter(function (m) {
  26832. return m.id === id;
  26833. });
  26834. };
  26835. /**
  26836. * Gets the first added transform node found of a given ID
  26837. * @param id defines the id to search for
  26838. * @return the found transform node or null if not found at all.
  26839. */
  26840. Scene.prototype.getTransformNodeByID = function (id) {
  26841. for (var index = 0; index < this.transformNodes.length; index++) {
  26842. if (this.transformNodes[index].id === id) {
  26843. return this.transformNodes[index];
  26844. }
  26845. }
  26846. return null;
  26847. };
  26848. /**
  26849. * Gets a list of transform nodes using their id
  26850. * @param id defines the id to search for
  26851. * @returns a list of transform nodes
  26852. */
  26853. Scene.prototype.getTransformNodesByID = function (id) {
  26854. return this.transformNodes.filter(function (m) {
  26855. return m.id === id;
  26856. });
  26857. };
  26858. /**
  26859. * Gets a mesh with its auto-generated unique id
  26860. * @param uniqueId defines the unique id to search for
  26861. * @return the found mesh or null if not found at all.
  26862. */
  26863. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26864. for (var index = 0; index < this.meshes.length; index++) {
  26865. if (this.meshes[index].uniqueId === uniqueId) {
  26866. return this.meshes[index];
  26867. }
  26868. }
  26869. return null;
  26870. };
  26871. /**
  26872. * Gets a the last added mesh using a given id
  26873. * @param id defines the id to search for
  26874. * @return the found mesh or null if not found at all.
  26875. */
  26876. Scene.prototype.getLastMeshByID = function (id) {
  26877. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26878. if (this.meshes[index].id === id) {
  26879. return this.meshes[index];
  26880. }
  26881. }
  26882. return null;
  26883. };
  26884. /**
  26885. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26886. * @param id defines the id to search for
  26887. * @return the found node or null if not found at all
  26888. */
  26889. Scene.prototype.getLastEntryByID = function (id) {
  26890. var index;
  26891. for (index = this.meshes.length - 1; index >= 0; index--) {
  26892. if (this.meshes[index].id === id) {
  26893. return this.meshes[index];
  26894. }
  26895. }
  26896. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26897. if (this.transformNodes[index].id === id) {
  26898. return this.transformNodes[index];
  26899. }
  26900. }
  26901. for (index = this.cameras.length - 1; index >= 0; index--) {
  26902. if (this.cameras[index].id === id) {
  26903. return this.cameras[index];
  26904. }
  26905. }
  26906. for (index = this.lights.length - 1; index >= 0; index--) {
  26907. if (this.lights[index].id === id) {
  26908. return this.lights[index];
  26909. }
  26910. }
  26911. return null;
  26912. };
  26913. /**
  26914. * Gets a node (Mesh, Camera, Light) using a given id
  26915. * @param id defines the id to search for
  26916. * @return the found node or null if not found at all
  26917. */
  26918. Scene.prototype.getNodeByID = function (id) {
  26919. var mesh = this.getMeshByID(id);
  26920. if (mesh) {
  26921. return mesh;
  26922. }
  26923. var light = this.getLightByID(id);
  26924. if (light) {
  26925. return light;
  26926. }
  26927. var camera = this.getCameraByID(id);
  26928. if (camera) {
  26929. return camera;
  26930. }
  26931. var bone = this.getBoneByID(id);
  26932. return bone;
  26933. };
  26934. /**
  26935. * Gets a node (Mesh, Camera, Light) using a given name
  26936. * @param name defines the name to search for
  26937. * @return the found node or null if not found at all.
  26938. */
  26939. Scene.prototype.getNodeByName = function (name) {
  26940. var mesh = this.getMeshByName(name);
  26941. if (mesh) {
  26942. return mesh;
  26943. }
  26944. var light = this.getLightByName(name);
  26945. if (light) {
  26946. return light;
  26947. }
  26948. var camera = this.getCameraByName(name);
  26949. if (camera) {
  26950. return camera;
  26951. }
  26952. var bone = this.getBoneByName(name);
  26953. return bone;
  26954. };
  26955. /**
  26956. * Gets a mesh using a given name
  26957. * @param name defines the name to search for
  26958. * @return the found mesh or null if not found at all.
  26959. */
  26960. Scene.prototype.getMeshByName = function (name) {
  26961. for (var index = 0; index < this.meshes.length; index++) {
  26962. if (this.meshes[index].name === name) {
  26963. return this.meshes[index];
  26964. }
  26965. }
  26966. return null;
  26967. };
  26968. /**
  26969. * Gets a transform node using a given name
  26970. * @param name defines the name to search for
  26971. * @return the found transform node or null if not found at all.
  26972. */
  26973. Scene.prototype.getTransformNodeByName = function (name) {
  26974. for (var index = 0; index < this.transformNodes.length; index++) {
  26975. if (this.transformNodes[index].name === name) {
  26976. return this.transformNodes[index];
  26977. }
  26978. }
  26979. return null;
  26980. };
  26981. /**
  26982. * Gets a sound using a given name
  26983. * @param name defines the name to search for
  26984. * @return the found sound or null if not found at all.
  26985. */
  26986. Scene.prototype.getSoundByName = function (name) {
  26987. var index;
  26988. if (BABYLON.AudioEngine) {
  26989. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26990. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26991. return this.mainSoundTrack.soundCollection[index];
  26992. }
  26993. }
  26994. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26995. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26996. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26997. return this.soundTracks[sdIndex].soundCollection[index];
  26998. }
  26999. }
  27000. }
  27001. }
  27002. return null;
  27003. };
  27004. /**
  27005. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27006. * @param id defines the id to search for
  27007. * @return the found skeleton or null if not found at all.
  27008. */
  27009. Scene.prototype.getLastSkeletonByID = function (id) {
  27010. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27011. if (this.skeletons[index].id === id) {
  27012. return this.skeletons[index];
  27013. }
  27014. }
  27015. return null;
  27016. };
  27017. /**
  27018. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27019. * @param id defines the id to search for
  27020. * @return the found skeleton or null if not found at all.
  27021. */
  27022. Scene.prototype.getSkeletonById = function (id) {
  27023. for (var index = 0; index < this.skeletons.length; index++) {
  27024. if (this.skeletons[index].id === id) {
  27025. return this.skeletons[index];
  27026. }
  27027. }
  27028. return null;
  27029. };
  27030. /**
  27031. * Gets a skeleton using a given name
  27032. * @param name defines the name to search for
  27033. * @return the found skeleton or null if not found at all.
  27034. */
  27035. Scene.prototype.getSkeletonByName = function (name) {
  27036. for (var index = 0; index < this.skeletons.length; index++) {
  27037. if (this.skeletons[index].name === name) {
  27038. return this.skeletons[index];
  27039. }
  27040. }
  27041. return null;
  27042. };
  27043. /**
  27044. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27045. * @param id defines the id to search for
  27046. * @return the found morph target manager or null if not found at all.
  27047. */
  27048. Scene.prototype.getMorphTargetManagerById = function (id) {
  27049. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27050. if (this.morphTargetManagers[index].uniqueId === id) {
  27051. return this.morphTargetManagers[index];
  27052. }
  27053. }
  27054. return null;
  27055. };
  27056. /**
  27057. * Gets a boolean indicating if the given mesh is active
  27058. * @param mesh defines the mesh to look for
  27059. * @returns true if the mesh is in the active list
  27060. */
  27061. Scene.prototype.isActiveMesh = function (mesh) {
  27062. return (this._activeMeshes.indexOf(mesh) !== -1);
  27063. };
  27064. Object.defineProperty(Scene.prototype, "uid", {
  27065. /**
  27066. * Return a unique id as a string which can serve as an identifier for the scene
  27067. */
  27068. get: function () {
  27069. if (!this._uid) {
  27070. this._uid = BABYLON.Tools.RandomId();
  27071. }
  27072. return this._uid;
  27073. },
  27074. enumerable: true,
  27075. configurable: true
  27076. });
  27077. /**
  27078. * Add an externaly attached data from its key.
  27079. * This method call will fail and return false, if such key already exists.
  27080. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27081. * @param key the unique key that identifies the data
  27082. * @param data the data object to associate to the key for this Engine instance
  27083. * @return true if no such key were already present and the data was added successfully, false otherwise
  27084. */
  27085. Scene.prototype.addExternalData = function (key, data) {
  27086. if (!this._externalData) {
  27087. this._externalData = new BABYLON.StringDictionary();
  27088. }
  27089. return this._externalData.add(key, data);
  27090. };
  27091. /**
  27092. * Get an externaly attached data from its key
  27093. * @param key the unique key that identifies the data
  27094. * @return the associated data, if present (can be null), or undefined if not present
  27095. */
  27096. Scene.prototype.getExternalData = function (key) {
  27097. if (!this._externalData) {
  27098. return null;
  27099. }
  27100. return this._externalData.get(key);
  27101. };
  27102. /**
  27103. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27104. * @param key the unique key that identifies the data
  27105. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27106. * @return the associated data, can be null if the factory returned null.
  27107. */
  27108. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27109. if (!this._externalData) {
  27110. this._externalData = new BABYLON.StringDictionary();
  27111. }
  27112. return this._externalData.getOrAddWithFactory(key, factory);
  27113. };
  27114. /**
  27115. * Remove an externaly attached data from the Engine instance
  27116. * @param key the unique key that identifies the data
  27117. * @return true if the data was successfully removed, false if it doesn't exist
  27118. */
  27119. Scene.prototype.removeExternalData = function (key) {
  27120. return this._externalData.remove(key);
  27121. };
  27122. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27123. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27124. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27125. var step = _a[_i];
  27126. step.action(mesh, subMesh);
  27127. }
  27128. var material = subMesh.getMaterial();
  27129. if (material !== null && material !== undefined) {
  27130. // Render targets
  27131. if (material.getRenderTargetTextures !== undefined) {
  27132. if (this._processedMaterials.indexOf(material) === -1) {
  27133. this._processedMaterials.push(material);
  27134. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27135. }
  27136. }
  27137. // Dispatch
  27138. this._activeIndices.addCount(subMesh.indexCount, false);
  27139. this._renderingManager.dispatch(subMesh, mesh, material);
  27140. }
  27141. }
  27142. };
  27143. /**
  27144. * Clear the processed materials smart array preventing retention point in material dispose.
  27145. */
  27146. Scene.prototype.freeProcessedMaterials = function () {
  27147. this._processedMaterials.dispose();
  27148. };
  27149. /**
  27150. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27151. */
  27152. Scene.prototype.freeActiveMeshes = function () {
  27153. this._activeMeshes.dispose();
  27154. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27155. this.activeCamera._activeMeshes.dispose();
  27156. }
  27157. if (this.activeCameras) {
  27158. for (var i = 0; i < this.activeCameras.length; i++) {
  27159. var activeCamera = this.activeCameras[i];
  27160. if (activeCamera && activeCamera._activeMeshes) {
  27161. activeCamera._activeMeshes.dispose();
  27162. }
  27163. }
  27164. }
  27165. };
  27166. /**
  27167. * Clear the info related to rendering groups preventing retention points during dispose.
  27168. */
  27169. Scene.prototype.freeRenderingGroups = function () {
  27170. if (this._renderingManager) {
  27171. this._renderingManager.freeRenderingGroups();
  27172. }
  27173. if (this.textures) {
  27174. for (var i = 0; i < this.textures.length; i++) {
  27175. var texture = this.textures[i];
  27176. if (texture && texture.renderList) {
  27177. texture.freeRenderingGroups();
  27178. }
  27179. }
  27180. }
  27181. };
  27182. /** @hidden */
  27183. Scene.prototype._isInIntermediateRendering = function () {
  27184. return this._intermediateRendering;
  27185. };
  27186. /**
  27187. * Defines the current active mesh candidate provider
  27188. * @param provider defines the provider to use
  27189. */
  27190. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27191. this._activeMeshCandidateProvider = provider;
  27192. };
  27193. /**
  27194. * Gets the current active mesh candidate provider
  27195. * @returns the current active mesh candidate provider
  27196. */
  27197. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27198. return this._activeMeshCandidateProvider;
  27199. };
  27200. /**
  27201. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27202. * @returns the current scene
  27203. */
  27204. Scene.prototype.freezeActiveMeshes = function () {
  27205. if (!this.activeCamera) {
  27206. return this;
  27207. }
  27208. if (!this._frustumPlanes) {
  27209. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27210. }
  27211. this._evaluateActiveMeshes();
  27212. this._activeMeshesFrozen = true;
  27213. return this;
  27214. };
  27215. /**
  27216. * Use this function to restart evaluating active meshes on every frame
  27217. * @returns the current scene
  27218. */
  27219. Scene.prototype.unfreezeActiveMeshes = function () {
  27220. this._activeMeshesFrozen = false;
  27221. return this;
  27222. };
  27223. Scene.prototype._evaluateActiveMeshes = function () {
  27224. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27225. return;
  27226. }
  27227. if (!this.activeCamera) {
  27228. return;
  27229. }
  27230. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27231. this.activeCamera._activeMeshes.reset();
  27232. this._activeMeshes.reset();
  27233. this._renderingManager.reset();
  27234. this._processedMaterials.reset();
  27235. this._activeParticleSystems.reset();
  27236. this._activeSkeletons.reset();
  27237. this._softwareSkinnedMeshes.reset();
  27238. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27239. var step = _a[_i];
  27240. step.action();
  27241. }
  27242. // Meshes
  27243. var meshes;
  27244. var len;
  27245. var checkIsEnabled = true;
  27246. // Determine mesh candidates
  27247. if (this._activeMeshCandidateProvider !== undefined) {
  27248. // Use _activeMeshCandidateProvider
  27249. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27250. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27251. if (meshes !== undefined) {
  27252. len = meshes.length;
  27253. }
  27254. else {
  27255. len = 0;
  27256. }
  27257. }
  27258. else if (this._selectionOctree !== undefined) {
  27259. // Octree
  27260. var selection = this._selectionOctree.select(this._frustumPlanes);
  27261. meshes = selection.data;
  27262. len = selection.length;
  27263. }
  27264. else {
  27265. // Full scene traversal
  27266. len = this.meshes.length;
  27267. meshes = this.meshes;
  27268. }
  27269. // Check each mesh
  27270. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27271. mesh = meshes[meshIndex];
  27272. if (mesh.isBlocked) {
  27273. continue;
  27274. }
  27275. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27276. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27277. continue;
  27278. }
  27279. mesh.computeWorldMatrix();
  27280. // Intersections
  27281. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27282. this._meshesForIntersections.pushNoDuplicate(mesh);
  27283. }
  27284. // Switch to current LOD
  27285. meshLOD = mesh.getLOD(this.activeCamera);
  27286. if (meshLOD === undefined || meshLOD === null) {
  27287. continue;
  27288. }
  27289. mesh._preActivate();
  27290. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27291. this._activeMeshes.push(mesh);
  27292. this.activeCamera._activeMeshes.push(mesh);
  27293. mesh._activate(this._renderId);
  27294. if (meshLOD !== mesh) {
  27295. meshLOD._activate(this._renderId);
  27296. }
  27297. this._activeMesh(mesh, meshLOD);
  27298. }
  27299. }
  27300. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27301. // Particle systems
  27302. if (this.particlesEnabled) {
  27303. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27304. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27305. var particleSystem = this.particleSystems[particleIndex];
  27306. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27307. continue;
  27308. }
  27309. var emitter = particleSystem.emitter;
  27310. if (!emitter.position || emitter.isEnabled()) {
  27311. this._activeParticleSystems.push(particleSystem);
  27312. particleSystem.animate();
  27313. this._renderingManager.dispatchParticles(particleSystem);
  27314. }
  27315. }
  27316. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27317. }
  27318. };
  27319. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27320. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27321. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27322. mesh.skeleton.prepare();
  27323. }
  27324. if (!mesh.computeBonesUsingShaders) {
  27325. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27326. }
  27327. }
  27328. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27329. var step = _a[_i];
  27330. step.action(sourceMesh, mesh);
  27331. }
  27332. if (mesh !== undefined && mesh !== null
  27333. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27334. // Submeshes Octrees
  27335. var len;
  27336. var subMeshes;
  27337. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27338. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27339. len = intersections.length;
  27340. subMeshes = intersections.data;
  27341. }
  27342. else {
  27343. subMeshes = mesh.subMeshes;
  27344. len = subMeshes.length;
  27345. }
  27346. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27347. subMesh = subMeshes[subIndex];
  27348. this._evaluateSubMesh(subMesh, mesh);
  27349. }
  27350. }
  27351. };
  27352. /**
  27353. * Update the transform matrix to update from the current active camera
  27354. * @param force defines a boolean used to force the update even if cache is up to date
  27355. */
  27356. Scene.prototype.updateTransformMatrix = function (force) {
  27357. if (!this.activeCamera) {
  27358. return;
  27359. }
  27360. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27361. };
  27362. /**
  27363. * 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)
  27364. * @param alternateCamera defines the camera to use
  27365. */
  27366. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27367. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27368. };
  27369. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27370. if (camera && camera._skipRendering) {
  27371. return;
  27372. }
  27373. var engine = this._engine;
  27374. this.activeCamera = camera;
  27375. if (!this.activeCamera)
  27376. throw new Error("Active camera not set");
  27377. // Viewport
  27378. engine.setViewport(this.activeCamera.viewport);
  27379. // Camera
  27380. this.resetCachedMaterial();
  27381. this._renderId++;
  27382. this.updateTransformMatrix();
  27383. if (camera._alternateCamera) {
  27384. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27385. this._alternateRendering = true;
  27386. }
  27387. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27388. // Meshes
  27389. this._evaluateActiveMeshes();
  27390. // Software skinning
  27391. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27392. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27393. mesh.applySkeleton(mesh.skeleton);
  27394. }
  27395. // Render targets
  27396. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27397. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27398. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27399. }
  27400. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27401. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27402. }
  27403. if (this.renderTargetsEnabled) {
  27404. this._intermediateRendering = true;
  27405. if (this._renderTargets.length > 0) {
  27406. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27407. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27408. var renderTarget = this._renderTargets.data[renderIndex];
  27409. if (renderTarget._shouldRender()) {
  27410. this._renderId++;
  27411. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27412. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27413. }
  27414. }
  27415. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27416. this._renderId++;
  27417. }
  27418. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27419. var step = _a[_i];
  27420. step.action(this.activeCamera);
  27421. }
  27422. this._intermediateRendering = false;
  27423. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27424. }
  27425. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27426. // Prepare Frame
  27427. if (this.postProcessManager) {
  27428. this.postProcessManager._prepareFrame();
  27429. }
  27430. // Before Camera Draw
  27431. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27432. var step = _c[_b];
  27433. step.action(this.activeCamera);
  27434. }
  27435. // Render
  27436. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27437. this._renderingManager.render(null, null, true, true);
  27438. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27439. // After Camera Draw
  27440. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27441. var step = _e[_d];
  27442. step.action(this.activeCamera);
  27443. }
  27444. // Finalize frame
  27445. if (this.postProcessManager) {
  27446. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27447. }
  27448. // Reset some special arrays
  27449. this._renderTargets.reset();
  27450. this._alternateRendering = false;
  27451. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27452. };
  27453. Scene.prototype._processSubCameras = function (camera) {
  27454. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27455. this._renderForCamera(camera);
  27456. return;
  27457. }
  27458. // rig cameras
  27459. for (var index = 0; index < camera._rigCameras.length; index++) {
  27460. this._renderForCamera(camera._rigCameras[index], camera);
  27461. }
  27462. this.activeCamera = camera;
  27463. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27464. };
  27465. Scene.prototype._checkIntersections = function () {
  27466. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27467. var sourceMesh = this._meshesForIntersections.data[index];
  27468. if (!sourceMesh.actionManager) {
  27469. continue;
  27470. }
  27471. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27472. var action = sourceMesh.actionManager.actions[actionIndex];
  27473. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27474. var parameters = action.getTriggerParameter();
  27475. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27476. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27477. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27478. if (areIntersecting && currentIntersectionInProgress === -1) {
  27479. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27480. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27481. sourceMesh._intersectionsInProgress.push(otherMesh);
  27482. }
  27483. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27484. sourceMesh._intersectionsInProgress.push(otherMesh);
  27485. }
  27486. }
  27487. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27488. //They intersected, and now they don't.
  27489. //is this trigger an exit trigger? execute an event.
  27490. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27491. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27492. }
  27493. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27494. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27495. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27496. return otherMesh === parameterMesh;
  27497. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27498. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27499. }
  27500. }
  27501. }
  27502. }
  27503. }
  27504. };
  27505. /**
  27506. * Render the scene
  27507. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27508. */
  27509. Scene.prototype.render = function (updateCameras) {
  27510. if (updateCameras === void 0) { updateCameras = true; }
  27511. if (this.isDisposed) {
  27512. return;
  27513. }
  27514. // Register components that have been associated lately to the scene.
  27515. this._registerTransientComponents();
  27516. this._activeParticles.fetchNewFrame();
  27517. this._totalVertices.fetchNewFrame();
  27518. this._activeIndices.fetchNewFrame();
  27519. this._activeBones.fetchNewFrame();
  27520. this._meshesForIntersections.reset();
  27521. this.resetCachedMaterial();
  27522. this.onBeforeAnimationsObservable.notifyObservers(this);
  27523. // Actions
  27524. if (this.actionManager) {
  27525. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27526. }
  27527. //Simplification Queue
  27528. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27529. this.simplificationQueue.executeNext();
  27530. }
  27531. if (this._engine.isDeterministicLockStep()) {
  27532. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27533. var defaultFPS = (60.0 / 1000.0);
  27534. var defaultFrameTime = 1000 / 60; // frame time in MS
  27535. if (this._physicsEngine) {
  27536. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27537. }
  27538. var stepsTaken = 0;
  27539. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27540. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27541. internalSteps = Math.min(internalSteps, maxSubSteps);
  27542. do {
  27543. this.onBeforeStepObservable.notifyObservers(this);
  27544. // Animations
  27545. this._animationRatio = defaultFrameTime * defaultFPS;
  27546. this._animate();
  27547. this.onAfterAnimationsObservable.notifyObservers(this);
  27548. // Physics
  27549. if (this._physicsEngine) {
  27550. this.onBeforePhysicsObservable.notifyObservers(this);
  27551. this._physicsEngine._step(defaultFrameTime / 1000);
  27552. this.onAfterPhysicsObservable.notifyObservers(this);
  27553. }
  27554. this.onAfterStepObservable.notifyObservers(this);
  27555. this._currentStepId++;
  27556. stepsTaken++;
  27557. deltaTime -= defaultFrameTime;
  27558. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27559. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27560. }
  27561. else {
  27562. // Animations
  27563. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27564. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27565. this._animate();
  27566. this.onAfterAnimationsObservable.notifyObservers(this);
  27567. // Physics
  27568. if (this._physicsEngine) {
  27569. this.onBeforePhysicsObservable.notifyObservers(this);
  27570. this._physicsEngine._step(deltaTime / 1000.0);
  27571. this.onAfterPhysicsObservable.notifyObservers(this);
  27572. }
  27573. }
  27574. // Before camera update steps
  27575. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27576. var step = _a[_i];
  27577. step.action();
  27578. }
  27579. // Update Cameras
  27580. if (updateCameras) {
  27581. if (this.activeCameras.length > 0) {
  27582. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27583. var camera = this.activeCameras[cameraIndex];
  27584. camera.update();
  27585. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27586. // rig cameras
  27587. for (var index = 0; index < camera._rigCameras.length; index++) {
  27588. camera._rigCameras[index].update();
  27589. }
  27590. }
  27591. }
  27592. }
  27593. else if (this.activeCamera) {
  27594. this.activeCamera.update();
  27595. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27596. // rig cameras
  27597. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27598. this.activeCamera._rigCameras[index].update();
  27599. }
  27600. }
  27601. }
  27602. }
  27603. // Before render
  27604. this.onBeforeRenderObservable.notifyObservers(this);
  27605. // Customs render targets
  27606. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27607. var engine = this.getEngine();
  27608. var currentActiveCamera = this.activeCamera;
  27609. if (this.renderTargetsEnabled) {
  27610. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27611. this._intermediateRendering = true;
  27612. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27613. var renderTarget = this.customRenderTargets[customIndex];
  27614. if (renderTarget._shouldRender()) {
  27615. this._renderId++;
  27616. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27617. if (!this.activeCamera)
  27618. throw new Error("Active camera not set");
  27619. // Viewport
  27620. engine.setViewport(this.activeCamera.viewport);
  27621. // Camera
  27622. this.updateTransformMatrix();
  27623. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27624. }
  27625. }
  27626. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27627. this._intermediateRendering = false;
  27628. this._renderId++;
  27629. }
  27630. // Restore back buffer
  27631. if (this.customRenderTargets.length > 0) {
  27632. engine.restoreDefaultFramebuffer();
  27633. }
  27634. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27635. this.activeCamera = currentActiveCamera;
  27636. // Procedural textures
  27637. if (this.proceduralTexturesEnabled) {
  27638. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27639. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27640. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27641. if (proceduralTexture._shouldRender()) {
  27642. proceduralTexture.render();
  27643. }
  27644. }
  27645. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27646. }
  27647. // Clear
  27648. if (this.autoClearDepthAndStencil || this.autoClear) {
  27649. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27650. }
  27651. // Shadows
  27652. if (this.shadowsEnabled) {
  27653. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27654. var light = this.lights[lightIndex];
  27655. var shadowGenerator = light.getShadowGenerator();
  27656. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27657. var shadowMap = (shadowGenerator.getShadowMap());
  27658. if (this.textures.indexOf(shadowMap) !== -1) {
  27659. this._renderTargets.push(shadowMap);
  27660. }
  27661. }
  27662. }
  27663. }
  27664. // Depth renderer
  27665. for (var key in this._depthRenderer) {
  27666. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27667. }
  27668. // Geometry renderer
  27669. if (this._geometryBufferRenderer) {
  27670. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27671. }
  27672. // RenderPipeline
  27673. if (this._postProcessRenderPipelineManager) {
  27674. this._postProcessRenderPipelineManager.update();
  27675. }
  27676. // Multi-cameras?
  27677. if (this.activeCameras.length > 0) {
  27678. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27679. if (cameraIndex > 0) {
  27680. this._engine.clear(null, false, true, true);
  27681. }
  27682. this._processSubCameras(this.activeCameras[cameraIndex]);
  27683. }
  27684. }
  27685. else {
  27686. if (!this.activeCamera) {
  27687. throw new Error("No camera defined");
  27688. }
  27689. this._processSubCameras(this.activeCamera);
  27690. }
  27691. // Intersection checks
  27692. this._checkIntersections();
  27693. // Update the audio listener attached to the camera
  27694. if (BABYLON.AudioEngine) {
  27695. this._updateAudioParameters();
  27696. }
  27697. // After render
  27698. if (this.afterRender) {
  27699. this.afterRender();
  27700. }
  27701. this.onAfterRenderObservable.notifyObservers(this);
  27702. // Cleaning
  27703. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27704. var data = this._toBeDisposed.data[index];
  27705. if (data) {
  27706. data.dispose();
  27707. }
  27708. this._toBeDisposed[index] = null;
  27709. }
  27710. this._toBeDisposed.reset();
  27711. if (this.dumpNextRenderTargets) {
  27712. this.dumpNextRenderTargets = false;
  27713. }
  27714. this._activeBones.addCount(0, true);
  27715. this._activeIndices.addCount(0, true);
  27716. this._activeParticles.addCount(0, true);
  27717. };
  27718. Scene.prototype._updateAudioParameters = function () {
  27719. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27720. return;
  27721. }
  27722. var listeningCamera;
  27723. var audioEngine = BABYLON.Engine.audioEngine;
  27724. if (this.activeCameras.length > 0) {
  27725. listeningCamera = this.activeCameras[0];
  27726. }
  27727. else {
  27728. listeningCamera = this.activeCamera;
  27729. }
  27730. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27731. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27732. // for VR cameras
  27733. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27734. listeningCamera = listeningCamera.rigCameras[0];
  27735. }
  27736. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27737. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27738. cameraDirection.normalize();
  27739. // To avoid some errors on GearVR
  27740. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27741. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27742. }
  27743. var i;
  27744. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27745. var sound = this.mainSoundTrack.soundCollection[i];
  27746. if (sound.useCustomAttenuation) {
  27747. sound.updateDistanceFromListener();
  27748. }
  27749. }
  27750. for (i = 0; i < this.soundTracks.length; i++) {
  27751. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27752. sound = this.soundTracks[i].soundCollection[j];
  27753. if (sound.useCustomAttenuation) {
  27754. sound.updateDistanceFromListener();
  27755. }
  27756. }
  27757. }
  27758. }
  27759. };
  27760. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27761. // Audio
  27762. /**
  27763. * Gets or sets if audio support is enabled
  27764. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27765. */
  27766. get: function () {
  27767. return this._audioEnabled;
  27768. },
  27769. set: function (value) {
  27770. this._audioEnabled = value;
  27771. if (BABYLON.AudioEngine) {
  27772. if (this._audioEnabled) {
  27773. this._enableAudio();
  27774. }
  27775. else {
  27776. this._disableAudio();
  27777. }
  27778. }
  27779. },
  27780. enumerable: true,
  27781. configurable: true
  27782. });
  27783. Scene.prototype._disableAudio = function () {
  27784. var i;
  27785. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27786. this.mainSoundTrack.soundCollection[i].pause();
  27787. }
  27788. for (i = 0; i < this.soundTracks.length; i++) {
  27789. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27790. this.soundTracks[i].soundCollection[j].pause();
  27791. }
  27792. }
  27793. };
  27794. Scene.prototype._enableAudio = function () {
  27795. var i;
  27796. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27797. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27798. this.mainSoundTrack.soundCollection[i].play();
  27799. }
  27800. }
  27801. for (i = 0; i < this.soundTracks.length; i++) {
  27802. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27803. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27804. this.soundTracks[i].soundCollection[j].play();
  27805. }
  27806. }
  27807. }
  27808. };
  27809. Object.defineProperty(Scene.prototype, "headphone", {
  27810. /**
  27811. * Gets or sets if audio will be output to headphones
  27812. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27813. */
  27814. get: function () {
  27815. return this._headphone;
  27816. },
  27817. set: function (value) {
  27818. this._headphone = value;
  27819. if (BABYLON.AudioEngine) {
  27820. if (this._headphone) {
  27821. this._switchAudioModeForHeadphones();
  27822. }
  27823. else {
  27824. this._switchAudioModeForNormalSpeakers();
  27825. }
  27826. }
  27827. },
  27828. enumerable: true,
  27829. configurable: true
  27830. });
  27831. Scene.prototype._switchAudioModeForHeadphones = function () {
  27832. this.mainSoundTrack.switchPanningModelToHRTF();
  27833. for (var i = 0; i < this.soundTracks.length; i++) {
  27834. this.soundTracks[i].switchPanningModelToHRTF();
  27835. }
  27836. };
  27837. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27838. this.mainSoundTrack.switchPanningModelToEqualPower();
  27839. for (var i = 0; i < this.soundTracks.length; i++) {
  27840. this.soundTracks[i].switchPanningModelToEqualPower();
  27841. }
  27842. };
  27843. /**
  27844. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27845. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27846. * @returns the created depth renderer
  27847. */
  27848. Scene.prototype.enableDepthRenderer = function (camera) {
  27849. camera = camera || this.activeCamera;
  27850. if (!camera) {
  27851. throw "No camera available to enable depth renderer";
  27852. }
  27853. if (!this._depthRenderer[camera.id]) {
  27854. var textureType = 0;
  27855. if (this._engine.getCaps().textureHalfFloatRender) {
  27856. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27857. }
  27858. else if (this._engine.getCaps().textureFloatRender) {
  27859. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27860. }
  27861. else {
  27862. throw "Depth renderer does not support int texture type";
  27863. }
  27864. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27865. }
  27866. return this._depthRenderer[camera.id];
  27867. };
  27868. /**
  27869. * Disables a depth renderer for a given camera
  27870. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27871. */
  27872. Scene.prototype.disableDepthRenderer = function (camera) {
  27873. camera = camera || this.activeCamera;
  27874. if (!camera || !this._depthRenderer[camera.id]) {
  27875. return;
  27876. }
  27877. this._depthRenderer[camera.id].dispose();
  27878. delete this._depthRenderer[camera.id];
  27879. };
  27880. /**
  27881. * Enables a GeometryBufferRender and associates it with the scene
  27882. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27883. * @returns the GeometryBufferRenderer
  27884. */
  27885. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27886. if (ratio === void 0) { ratio = 1; }
  27887. if (this._geometryBufferRenderer) {
  27888. return this._geometryBufferRenderer;
  27889. }
  27890. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27891. if (!this._geometryBufferRenderer.isSupported) {
  27892. this._geometryBufferRenderer = null;
  27893. }
  27894. return this._geometryBufferRenderer;
  27895. };
  27896. /**
  27897. * Disables the GeometryBufferRender associated with the scene
  27898. */
  27899. Scene.prototype.disableGeometryBufferRenderer = function () {
  27900. if (!this._geometryBufferRenderer) {
  27901. return;
  27902. }
  27903. this._geometryBufferRenderer.dispose();
  27904. this._geometryBufferRenderer = null;
  27905. };
  27906. /**
  27907. * Freeze all materials
  27908. * A frozen material will not be updatable but should be faster to render
  27909. */
  27910. Scene.prototype.freezeMaterials = function () {
  27911. for (var i = 0; i < this.materials.length; i++) {
  27912. this.materials[i].freeze();
  27913. }
  27914. };
  27915. /**
  27916. * Unfreeze all materials
  27917. * A frozen material will not be updatable but should be faster to render
  27918. */
  27919. Scene.prototype.unfreezeMaterials = function () {
  27920. for (var i = 0; i < this.materials.length; i++) {
  27921. this.materials[i].unfreeze();
  27922. }
  27923. };
  27924. /**
  27925. * Releases all held ressources
  27926. */
  27927. Scene.prototype.dispose = function () {
  27928. this.beforeRender = null;
  27929. this.afterRender = null;
  27930. this.skeletons = [];
  27931. this.morphTargetManagers = [];
  27932. this._transientComponents = [];
  27933. this._isReadyForMeshStage.clear();
  27934. this._beforeEvaluateActiveMeshStage.clear();
  27935. this._evaluateSubMeshStage.clear();
  27936. this._activeMeshStage.clear();
  27937. this._cameraDrawRenderTargetStage.clear();
  27938. this._beforeCameraDrawStage.clear();
  27939. this._beforeRenderingGroupDrawStage.clear();
  27940. this._afterRenderingGroupDrawStage.clear();
  27941. this._afterCameraDrawStage.clear();
  27942. this._beforeCameraUpdateStage.clear();
  27943. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27944. var component = _a[_i];
  27945. component.dispose();
  27946. }
  27947. this.importedMeshesFiles = new Array();
  27948. this.stopAllAnimations();
  27949. this.resetCachedMaterial();
  27950. for (var key in this._depthRenderer) {
  27951. this._depthRenderer[key].dispose();
  27952. }
  27953. // Smart arrays
  27954. if (this.activeCamera) {
  27955. this.activeCamera._activeMeshes.dispose();
  27956. this.activeCamera = null;
  27957. }
  27958. this._activeMeshes.dispose();
  27959. this._renderingManager.dispose();
  27960. this._processedMaterials.dispose();
  27961. this._activeParticleSystems.dispose();
  27962. this._activeSkeletons.dispose();
  27963. this._softwareSkinnedMeshes.dispose();
  27964. this._renderTargets.dispose();
  27965. this._registeredForLateAnimationBindings.dispose();
  27966. this._meshesForIntersections.dispose();
  27967. this._toBeDisposed.dispose();
  27968. // Abort active requests
  27969. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27970. var request = _c[_b];
  27971. request.abort();
  27972. }
  27973. // Debug layer
  27974. if (this._debugLayer) {
  27975. this._debugLayer.hide();
  27976. }
  27977. // Events
  27978. this.onDisposeObservable.notifyObservers(this);
  27979. this.onDisposeObservable.clear();
  27980. this.onBeforeRenderObservable.clear();
  27981. this.onAfterRenderObservable.clear();
  27982. this.onBeforeRenderTargetsRenderObservable.clear();
  27983. this.onAfterRenderTargetsRenderObservable.clear();
  27984. this.onAfterStepObservable.clear();
  27985. this.onBeforeStepObservable.clear();
  27986. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27987. this.onAfterActiveMeshesEvaluationObservable.clear();
  27988. this.onBeforeParticlesRenderingObservable.clear();
  27989. this.onAfterParticlesRenderingObservable.clear();
  27990. this.onBeforeSpritesRenderingObservable.clear();
  27991. this.onAfterSpritesRenderingObservable.clear();
  27992. this.onBeforeDrawPhaseObservable.clear();
  27993. this.onAfterDrawPhaseObservable.clear();
  27994. this.onBeforePhysicsObservable.clear();
  27995. this.onAfterPhysicsObservable.clear();
  27996. this.onBeforeAnimationsObservable.clear();
  27997. this.onAfterAnimationsObservable.clear();
  27998. this.onDataLoadedObservable.clear();
  27999. this.onBeforeRenderingGroupObservable.clear();
  28000. this.onAfterRenderingGroupObservable.clear();
  28001. this.detachControl();
  28002. // Release sounds & sounds tracks
  28003. if (BABYLON.AudioEngine) {
  28004. this.disposeSounds();
  28005. }
  28006. // VR Helper
  28007. if (this.VRHelper) {
  28008. this.VRHelper.dispose();
  28009. }
  28010. // Detach cameras
  28011. var canvas = this._engine.getRenderingCanvas();
  28012. if (canvas) {
  28013. var index;
  28014. for (index = 0; index < this.cameras.length; index++) {
  28015. this.cameras[index].detachControl(canvas);
  28016. }
  28017. }
  28018. // Release animation groups
  28019. while (this.animationGroups.length) {
  28020. this.animationGroups[0].dispose();
  28021. }
  28022. // Release lights
  28023. while (this.lights.length) {
  28024. this.lights[0].dispose();
  28025. }
  28026. // Release meshes
  28027. while (this.meshes.length) {
  28028. this.meshes[0].dispose(true);
  28029. }
  28030. while (this.transformNodes.length) {
  28031. this.removeTransformNode(this.transformNodes[0]);
  28032. }
  28033. // Release cameras
  28034. while (this.cameras.length) {
  28035. this.cameras[0].dispose();
  28036. }
  28037. // Release materials
  28038. if (this.defaultMaterial) {
  28039. this.defaultMaterial.dispose();
  28040. }
  28041. while (this.multiMaterials.length) {
  28042. this.multiMaterials[0].dispose();
  28043. }
  28044. while (this.materials.length) {
  28045. this.materials[0].dispose();
  28046. }
  28047. // Release particles
  28048. while (this.particleSystems.length) {
  28049. this.particleSystems[0].dispose();
  28050. }
  28051. // Release sprites
  28052. while (this.spriteManagers.length) {
  28053. this.spriteManagers[0].dispose();
  28054. }
  28055. // Release postProcesses
  28056. while (this.postProcesses.length) {
  28057. this.postProcesses[0].dispose();
  28058. }
  28059. // Release textures
  28060. while (this.textures.length) {
  28061. this.textures[0].dispose();
  28062. }
  28063. // Release UBO
  28064. this._sceneUbo.dispose();
  28065. if (this._alternateSceneUbo) {
  28066. this._alternateSceneUbo.dispose();
  28067. }
  28068. // Post-processes
  28069. this.postProcessManager.dispose();
  28070. if (this._postProcessRenderPipelineManager) {
  28071. this._postProcessRenderPipelineManager.dispose();
  28072. }
  28073. // Physics
  28074. if (this._physicsEngine) {
  28075. this.disablePhysicsEngine();
  28076. }
  28077. // Remove from engine
  28078. index = this._engine.scenes.indexOf(this);
  28079. if (index > -1) {
  28080. this._engine.scenes.splice(index, 1);
  28081. }
  28082. this._engine.wipeCaches(true);
  28083. this._isDisposed = true;
  28084. };
  28085. Object.defineProperty(Scene.prototype, "isDisposed", {
  28086. /**
  28087. * Gets if the scene is already disposed
  28088. */
  28089. get: function () {
  28090. return this._isDisposed;
  28091. },
  28092. enumerable: true,
  28093. configurable: true
  28094. });
  28095. /**
  28096. * Releases sounds & soundtracks
  28097. */
  28098. Scene.prototype.disposeSounds = function () {
  28099. if (!this._mainSoundTrack) {
  28100. return;
  28101. }
  28102. this.mainSoundTrack.dispose();
  28103. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28104. this.soundTracks[scIndex].dispose();
  28105. }
  28106. };
  28107. /**
  28108. * Call this function to reduce memory footprint of the scene.
  28109. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28110. */
  28111. Scene.prototype.clearCachedVertexData = function () {
  28112. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28113. var mesh = this.meshes[meshIndex];
  28114. var geometry = mesh.geometry;
  28115. if (geometry) {
  28116. geometry._indices = [];
  28117. for (var vbName in geometry._vertexBuffers) {
  28118. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28119. continue;
  28120. }
  28121. geometry._vertexBuffers[vbName]._buffer._data = null;
  28122. }
  28123. }
  28124. }
  28125. };
  28126. /**
  28127. * This function will remove the local cached buffer data from texture.
  28128. * It will save memory but will prevent the texture from being rebuilt
  28129. */
  28130. Scene.prototype.cleanCachedTextureBuffer = function () {
  28131. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28132. var baseTexture = _a[_i];
  28133. var buffer = baseTexture._buffer;
  28134. if (buffer) {
  28135. baseTexture._buffer = null;
  28136. }
  28137. }
  28138. };
  28139. // Octrees
  28140. /**
  28141. * Get the world extend vectors with an optional filter
  28142. *
  28143. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28144. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28145. */
  28146. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28147. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28148. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28149. filterPredicate = filterPredicate || (function () { return true; });
  28150. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28151. mesh.computeWorldMatrix(true);
  28152. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28153. return;
  28154. }
  28155. var boundingInfo = mesh.getBoundingInfo();
  28156. var minBox = boundingInfo.boundingBox.minimumWorld;
  28157. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28158. BABYLON.Tools.CheckExtends(minBox, min, max);
  28159. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28160. });
  28161. return {
  28162. min: min,
  28163. max: max
  28164. };
  28165. };
  28166. /**
  28167. * Creates or updates the octree used to boost selection (picking)
  28168. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28169. * @param maxCapacity defines the maximum capacity per leaf
  28170. * @param maxDepth defines the maximum depth of the octree
  28171. * @returns an octree of AbstractMesh
  28172. */
  28173. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28174. if (maxCapacity === void 0) { maxCapacity = 64; }
  28175. if (maxDepth === void 0) { maxDepth = 2; }
  28176. if (!this._selectionOctree) {
  28177. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28178. }
  28179. var worldExtends = this.getWorldExtends();
  28180. // Update octree
  28181. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28182. return this._selectionOctree;
  28183. };
  28184. // Picking
  28185. /**
  28186. * Creates a ray that can be used to pick in the scene
  28187. * @param x defines the x coordinate of the origin (on-screen)
  28188. * @param y defines the y coordinate of the origin (on-screen)
  28189. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28190. * @param camera defines the camera to use for the picking
  28191. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28192. * @returns a Ray
  28193. */
  28194. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28195. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28196. var result = BABYLON.Ray.Zero();
  28197. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28198. return result;
  28199. };
  28200. /**
  28201. * Creates a ray that can be used to pick in the scene
  28202. * @param x defines the x coordinate of the origin (on-screen)
  28203. * @param y defines the y coordinate of the origin (on-screen)
  28204. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28205. * @param result defines the ray where to store the picking ray
  28206. * @param camera defines the camera to use for the picking
  28207. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28208. * @returns the current scene
  28209. */
  28210. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28211. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28212. var engine = this._engine;
  28213. if (!camera) {
  28214. if (!this.activeCamera)
  28215. throw new Error("Active camera not set");
  28216. camera = this.activeCamera;
  28217. }
  28218. var cameraViewport = camera.viewport;
  28219. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28220. // Moving coordinates to local viewport world
  28221. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28222. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28223. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28224. return this;
  28225. };
  28226. /**
  28227. * Creates a ray that can be used to pick in the scene
  28228. * @param x defines the x coordinate of the origin (on-screen)
  28229. * @param y defines the y coordinate of the origin (on-screen)
  28230. * @param camera defines the camera to use for the picking
  28231. * @returns a Ray
  28232. */
  28233. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28234. var result = BABYLON.Ray.Zero();
  28235. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28236. return result;
  28237. };
  28238. /**
  28239. * Creates a ray that can be used to pick in the scene
  28240. * @param x defines the x coordinate of the origin (on-screen)
  28241. * @param y defines the y coordinate of the origin (on-screen)
  28242. * @param result defines the ray where to store the picking ray
  28243. * @param camera defines the camera to use for the picking
  28244. * @returns the current scene
  28245. */
  28246. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28247. if (!BABYLON.PickingInfo) {
  28248. return this;
  28249. }
  28250. var engine = this._engine;
  28251. if (!camera) {
  28252. if (!this.activeCamera)
  28253. throw new Error("Active camera not set");
  28254. camera = this.activeCamera;
  28255. }
  28256. var cameraViewport = camera.viewport;
  28257. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28258. var identity = BABYLON.Matrix.Identity();
  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, identity, identity, camera.getProjectionMatrix());
  28263. return this;
  28264. };
  28265. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28266. if (!BABYLON.PickingInfo) {
  28267. return null;
  28268. }
  28269. var pickingInfo = null;
  28270. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28271. var mesh = this.meshes[meshIndex];
  28272. if (predicate) {
  28273. if (!predicate(mesh)) {
  28274. continue;
  28275. }
  28276. }
  28277. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28278. continue;
  28279. }
  28280. var world = mesh.getWorldMatrix();
  28281. var ray = rayFunction(world);
  28282. var result = mesh.intersects(ray, fastCheck);
  28283. if (!result || !result.hit)
  28284. continue;
  28285. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28286. continue;
  28287. pickingInfo = result;
  28288. if (fastCheck) {
  28289. break;
  28290. }
  28291. }
  28292. return pickingInfo || new BABYLON.PickingInfo();
  28293. };
  28294. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28295. if (!BABYLON.PickingInfo) {
  28296. return null;
  28297. }
  28298. var pickingInfos = new Array();
  28299. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28300. var mesh = this.meshes[meshIndex];
  28301. if (predicate) {
  28302. if (!predicate(mesh)) {
  28303. continue;
  28304. }
  28305. }
  28306. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28307. continue;
  28308. }
  28309. var world = mesh.getWorldMatrix();
  28310. var ray = rayFunction(world);
  28311. var result = mesh.intersects(ray, false);
  28312. if (!result || !result.hit)
  28313. continue;
  28314. pickingInfos.push(result);
  28315. }
  28316. return pickingInfos;
  28317. };
  28318. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28319. if (!BABYLON.PickingInfo) {
  28320. return null;
  28321. }
  28322. var pickingInfo = null;
  28323. if (!camera) {
  28324. if (!this.activeCamera) {
  28325. return null;
  28326. }
  28327. camera = this.activeCamera;
  28328. }
  28329. if (this.spriteManagers.length > 0) {
  28330. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28331. var spriteManager = this.spriteManagers[spriteIndex];
  28332. if (!spriteManager.isPickable) {
  28333. continue;
  28334. }
  28335. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28336. if (!result || !result.hit)
  28337. continue;
  28338. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28339. continue;
  28340. pickingInfo = result;
  28341. if (fastCheck) {
  28342. break;
  28343. }
  28344. }
  28345. }
  28346. return pickingInfo || new BABYLON.PickingInfo();
  28347. };
  28348. /** Launch a ray to try to pick a mesh in the scene
  28349. * @param x position on screen
  28350. * @param y position on screen
  28351. * @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
  28352. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28353. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28354. * @returns a PickingInfo
  28355. */
  28356. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28357. var _this = this;
  28358. if (!BABYLON.PickingInfo) {
  28359. return null;
  28360. }
  28361. var result = this._internalPick(function (world) {
  28362. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28363. return _this._tempPickingRay;
  28364. }, predicate, fastCheck);
  28365. if (result) {
  28366. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28367. }
  28368. return result;
  28369. };
  28370. /** Launch a ray to try to pick a sprite in the scene
  28371. * @param x position on screen
  28372. * @param y position on screen
  28373. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28374. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28375. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28376. * @returns a PickingInfo
  28377. */
  28378. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28379. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28380. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28381. };
  28382. /** Use the given ray to pick a mesh in the scene
  28383. * @param ray The ray to use to pick meshes
  28384. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28385. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28386. * @returns a PickingInfo
  28387. */
  28388. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28389. var _this = this;
  28390. var result = this._internalPick(function (world) {
  28391. if (!_this._pickWithRayInverseMatrix) {
  28392. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28393. }
  28394. world.invertToRef(_this._pickWithRayInverseMatrix);
  28395. if (!_this._cachedRayForTransform) {
  28396. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28397. }
  28398. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28399. return _this._cachedRayForTransform;
  28400. }, predicate, fastCheck);
  28401. if (result) {
  28402. result.ray = ray;
  28403. }
  28404. return result;
  28405. };
  28406. /**
  28407. * Launch a ray to try to pick a mesh in the scene
  28408. * @param x X position on screen
  28409. * @param y Y position on screen
  28410. * @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
  28411. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28412. * @returns an array of PickingInfo
  28413. */
  28414. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28415. var _this = this;
  28416. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28417. };
  28418. /**
  28419. * Launch a ray to try to pick a mesh in the scene
  28420. * @param ray Ray to use
  28421. * @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
  28422. * @returns an array of PickingInfo
  28423. */
  28424. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28425. var _this = this;
  28426. return this._internalMultiPick(function (world) {
  28427. if (!_this._pickWithRayInverseMatrix) {
  28428. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28429. }
  28430. world.invertToRef(_this._pickWithRayInverseMatrix);
  28431. if (!_this._cachedRayForTransform) {
  28432. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28433. }
  28434. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28435. return _this._cachedRayForTransform;
  28436. }, predicate);
  28437. };
  28438. /**
  28439. * Force the value of meshUnderPointer
  28440. * @param mesh defines the mesh to use
  28441. */
  28442. Scene.prototype.setPointerOverMesh = function (mesh) {
  28443. if (this._pointerOverMesh === mesh) {
  28444. return;
  28445. }
  28446. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28447. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28448. }
  28449. this._pointerOverMesh = mesh;
  28450. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28451. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28452. }
  28453. };
  28454. /**
  28455. * Gets the mesh under the pointer
  28456. * @returns a Mesh or null if no mesh is under the pointer
  28457. */
  28458. Scene.prototype.getPointerOverMesh = function () {
  28459. return this._pointerOverMesh;
  28460. };
  28461. /**
  28462. * Force the sprite under the pointer
  28463. * @param sprite defines the sprite to use
  28464. */
  28465. Scene.prototype.setPointerOverSprite = function (sprite) {
  28466. if (this._pointerOverSprite === sprite) {
  28467. return;
  28468. }
  28469. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28470. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28471. }
  28472. this._pointerOverSprite = sprite;
  28473. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28474. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28475. }
  28476. };
  28477. /**
  28478. * Gets the sprite under the pointer
  28479. * @returns a Sprite or null if no sprite is under the pointer
  28480. */
  28481. Scene.prototype.getPointerOverSprite = function () {
  28482. return this._pointerOverSprite;
  28483. };
  28484. // Physics
  28485. /**
  28486. * Gets the current physics engine
  28487. * @returns a PhysicsEngine or null if none attached
  28488. */
  28489. Scene.prototype.getPhysicsEngine = function () {
  28490. return this._physicsEngine;
  28491. };
  28492. /**
  28493. * Enables physics to the current scene
  28494. * @param gravity defines the scene's gravity for the physics engine
  28495. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28496. * @return a boolean indicating if the physics engine was initialized
  28497. */
  28498. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28499. if (gravity === void 0) { gravity = null; }
  28500. if (this._physicsEngine) {
  28501. return true;
  28502. }
  28503. try {
  28504. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28505. return true;
  28506. }
  28507. catch (e) {
  28508. BABYLON.Tools.Error(e.message);
  28509. return false;
  28510. }
  28511. };
  28512. /**
  28513. * Disables and disposes the physics engine associated with the scene
  28514. */
  28515. Scene.prototype.disablePhysicsEngine = function () {
  28516. if (!this._physicsEngine) {
  28517. return;
  28518. }
  28519. this._physicsEngine.dispose();
  28520. this._physicsEngine = null;
  28521. };
  28522. /**
  28523. * Gets a boolean indicating if there is an active physics engine
  28524. * @returns a boolean indicating if there is an active physics engine
  28525. */
  28526. Scene.prototype.isPhysicsEnabled = function () {
  28527. return this._physicsEngine !== undefined;
  28528. };
  28529. /**
  28530. * Deletes a physics compound impostor
  28531. * @param compound defines the compound to delete
  28532. */
  28533. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28534. var mesh = compound.parts[0].mesh;
  28535. if (mesh.physicsImpostor) {
  28536. mesh.physicsImpostor.dispose( /*true*/);
  28537. mesh.physicsImpostor = null;
  28538. }
  28539. };
  28540. // Misc.
  28541. /** @hidden */
  28542. Scene.prototype._rebuildGeometries = function () {
  28543. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28544. var geometry = _a[_i];
  28545. geometry._rebuild();
  28546. }
  28547. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28548. var mesh = _c[_b];
  28549. mesh._rebuild();
  28550. }
  28551. if (this.postProcessManager) {
  28552. this.postProcessManager._rebuild();
  28553. }
  28554. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28555. var component = _e[_d];
  28556. component.rebuild();
  28557. }
  28558. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28559. var system = _g[_f];
  28560. system.rebuild();
  28561. }
  28562. if (this._postProcessRenderPipelineManager) {
  28563. this._postProcessRenderPipelineManager._rebuild();
  28564. }
  28565. };
  28566. /** @hidden */
  28567. Scene.prototype._rebuildTextures = function () {
  28568. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28569. var texture = _a[_i];
  28570. texture._rebuild();
  28571. }
  28572. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28573. };
  28574. /**
  28575. * Creates a default light for the scene.
  28576. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28577. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28578. */
  28579. Scene.prototype.createDefaultLight = function (replace) {
  28580. if (replace === void 0) { replace = false; }
  28581. // Dispose existing light in replace mode.
  28582. if (replace) {
  28583. if (this.lights) {
  28584. for (var i = 0; i < this.lights.length; i++) {
  28585. this.lights[i].dispose();
  28586. }
  28587. }
  28588. }
  28589. // Light
  28590. if (this.lights.length === 0) {
  28591. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28592. }
  28593. };
  28594. /**
  28595. * Creates a default camera for the scene.
  28596. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28597. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28598. * @param replace has default false, when true replaces the active camera in the scene
  28599. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28600. */
  28601. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28602. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28603. if (replace === void 0) { replace = false; }
  28604. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28605. // Dispose existing camera in replace mode.
  28606. if (replace) {
  28607. if (this.activeCamera) {
  28608. this.activeCamera.dispose();
  28609. this.activeCamera = null;
  28610. }
  28611. }
  28612. // Camera
  28613. if (!this.activeCamera) {
  28614. var worldExtends = this.getWorldExtends();
  28615. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28616. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28617. var camera;
  28618. var radius = worldSize.length() * 1.5;
  28619. // empty scene scenario!
  28620. if (!isFinite(radius)) {
  28621. radius = 1;
  28622. worldCenter.copyFromFloats(0, 0, 0);
  28623. }
  28624. if (createArcRotateCamera) {
  28625. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28626. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28627. arcRotateCamera.wheelPrecision = 100 / radius;
  28628. camera = arcRotateCamera;
  28629. }
  28630. else {
  28631. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28632. freeCamera.setTarget(worldCenter);
  28633. camera = freeCamera;
  28634. }
  28635. camera.minZ = radius * 0.01;
  28636. camera.maxZ = radius * 1000;
  28637. camera.speed = radius * 0.2;
  28638. this.activeCamera = camera;
  28639. var canvas = this.getEngine().getRenderingCanvas();
  28640. if (attachCameraControls && canvas) {
  28641. camera.attachControl(canvas);
  28642. }
  28643. }
  28644. };
  28645. /**
  28646. * Creates a default camera and a default light.
  28647. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28648. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28649. * @param replace has the default false, when true replaces the active camera/light in the scene
  28650. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28651. */
  28652. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28653. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28654. if (replace === void 0) { replace = false; }
  28655. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28656. this.createDefaultLight(replace);
  28657. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28658. };
  28659. /**
  28660. * Creates a new sky box
  28661. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28662. * @param environmentTexture defines the texture to use as environment texture
  28663. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28664. * @param scale defines the overall scale of the skybox
  28665. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28666. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28667. * @returns a new mesh holding the sky box
  28668. */
  28669. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28670. if (pbr === void 0) { pbr = false; }
  28671. if (scale === void 0) { scale = 1000; }
  28672. if (blur === void 0) { blur = 0; }
  28673. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28674. if (!environmentTexture) {
  28675. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28676. return null;
  28677. }
  28678. if (setGlobalEnvTexture) {
  28679. if (environmentTexture) {
  28680. this.environmentTexture = environmentTexture;
  28681. }
  28682. }
  28683. // Skybox
  28684. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28685. if (pbr) {
  28686. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28687. hdrSkyboxMaterial.backFaceCulling = false;
  28688. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28689. if (hdrSkyboxMaterial.reflectionTexture) {
  28690. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28691. }
  28692. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28693. hdrSkyboxMaterial.disableLighting = true;
  28694. hdrSkyboxMaterial.twoSidedLighting = true;
  28695. hdrSkybox.infiniteDistance = true;
  28696. hdrSkybox.material = hdrSkyboxMaterial;
  28697. }
  28698. else {
  28699. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28700. skyboxMaterial.backFaceCulling = false;
  28701. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28702. if (skyboxMaterial.reflectionTexture) {
  28703. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28704. }
  28705. skyboxMaterial.disableLighting = true;
  28706. hdrSkybox.infiniteDistance = true;
  28707. hdrSkybox.material = skyboxMaterial;
  28708. }
  28709. return hdrSkybox;
  28710. };
  28711. /**
  28712. * Creates a new environment
  28713. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28714. * @param options defines the options you can use to configure the environment
  28715. * @returns the new EnvironmentHelper
  28716. */
  28717. Scene.prototype.createDefaultEnvironment = function (options) {
  28718. if (BABYLON.EnvironmentHelper) {
  28719. return new BABYLON.EnvironmentHelper(options, this);
  28720. }
  28721. return null;
  28722. };
  28723. /**
  28724. * Creates a new VREXperienceHelper
  28725. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28726. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28727. * @returns a new VREXperienceHelper
  28728. */
  28729. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28730. if (webVROptions === void 0) { webVROptions = {}; }
  28731. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28732. };
  28733. // Tags
  28734. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28735. if (tagsQuery === undefined) {
  28736. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28737. return list;
  28738. }
  28739. var listByTags = [];
  28740. forEach = forEach || (function (item) { return; });
  28741. for (var i in list) {
  28742. var item = list[i];
  28743. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28744. listByTags.push(item);
  28745. forEach(item);
  28746. }
  28747. }
  28748. return listByTags;
  28749. };
  28750. /**
  28751. * Get a list of meshes by tags
  28752. * @param tagsQuery defines the tags query to use
  28753. * @param forEach defines a predicate used to filter results
  28754. * @returns an array of Mesh
  28755. */
  28756. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28757. return this._getByTags(this.meshes, tagsQuery, forEach);
  28758. };
  28759. /**
  28760. * Get a list of cameras by tags
  28761. * @param tagsQuery defines the tags query to use
  28762. * @param forEach defines a predicate used to filter results
  28763. * @returns an array of Camera
  28764. */
  28765. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28766. return this._getByTags(this.cameras, tagsQuery, forEach);
  28767. };
  28768. /**
  28769. * Get a list of lights by tags
  28770. * @param tagsQuery defines the tags query to use
  28771. * @param forEach defines a predicate used to filter results
  28772. * @returns an array of Light
  28773. */
  28774. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28775. return this._getByTags(this.lights, tagsQuery, forEach);
  28776. };
  28777. /**
  28778. * Get a list of materials by tags
  28779. * @param tagsQuery defines the tags query to use
  28780. * @param forEach defines a predicate used to filter results
  28781. * @returns an array of Material
  28782. */
  28783. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28784. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28785. };
  28786. /**
  28787. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28788. * This allowed control for front to back rendering or reversly depending of the special needs.
  28789. *
  28790. * @param renderingGroupId The rendering group id corresponding to its index
  28791. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28792. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28793. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28794. */
  28795. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28796. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28797. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28798. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28799. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28800. };
  28801. /**
  28802. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28803. *
  28804. * @param renderingGroupId The rendering group id corresponding to its index
  28805. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28806. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28807. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28808. */
  28809. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28810. if (depth === void 0) { depth = true; }
  28811. if (stencil === void 0) { stencil = true; }
  28812. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28813. };
  28814. /**
  28815. * Gets the current auto clear configuration for one rendering group of the rendering
  28816. * manager.
  28817. * @param index the rendering group index to get the information for
  28818. * @returns The auto clear setup for the requested rendering group
  28819. */
  28820. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28821. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28822. };
  28823. /**
  28824. * Will flag all materials as dirty to trigger new shader compilation
  28825. * @param flag defines the flag used to specify which material part must be marked as dirty
  28826. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28827. */
  28828. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28829. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28830. var material = _a[_i];
  28831. if (predicate && !predicate(material)) {
  28832. continue;
  28833. }
  28834. material.markAsDirty(flag);
  28835. }
  28836. };
  28837. /** @hidden */
  28838. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28839. var _this = this;
  28840. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28841. this._activeRequests.push(request);
  28842. request.onCompleteObservable.add(function (request) {
  28843. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28844. });
  28845. return request;
  28846. };
  28847. /** @hidden */
  28848. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28849. var _this = this;
  28850. return new Promise(function (resolve, reject) {
  28851. _this._loadFile(url, function (data) {
  28852. resolve(data);
  28853. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28854. reject(exception);
  28855. });
  28856. });
  28857. };
  28858. // Statics
  28859. Scene._FOGMODE_NONE = 0;
  28860. Scene._FOGMODE_EXP = 1;
  28861. Scene._FOGMODE_EXP2 = 2;
  28862. Scene._FOGMODE_LINEAR = 3;
  28863. Scene._uniqueIdCounter = 0;
  28864. /**
  28865. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28866. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28867. */
  28868. Scene.MinDeltaTime = 1.0;
  28869. /**
  28870. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28871. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28872. */
  28873. Scene.MaxDeltaTime = 1000.0;
  28874. /** The distance in pixel that you have to move to prevent some events */
  28875. Scene.DragMovementThreshold = 10; // in pixels
  28876. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28877. Scene.LongPressDelay = 500; // in milliseconds
  28878. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28879. Scene.DoubleClickDelay = 300; // in milliseconds
  28880. /** If you need to check double click without raising a single click at first click, enable this flag */
  28881. Scene.ExclusiveDoubleClickMode = false;
  28882. return Scene;
  28883. }(BABYLON.AbstractScene));
  28884. BABYLON.Scene = Scene;
  28885. })(BABYLON || (BABYLON = {}));
  28886. //# sourceMappingURL=babylon.scene.js.map
  28887. var BABYLON;
  28888. (function (BABYLON) {
  28889. /**
  28890. * Set of assets to keep when moving a scene into an asset container.
  28891. */
  28892. var KeepAssets = /** @class */ (function (_super) {
  28893. __extends(KeepAssets, _super);
  28894. function KeepAssets() {
  28895. return _super !== null && _super.apply(this, arguments) || this;
  28896. }
  28897. return KeepAssets;
  28898. }(BABYLON.AbstractScene));
  28899. BABYLON.KeepAssets = KeepAssets;
  28900. /**
  28901. * Container with a set of assets that can be added or removed from a scene.
  28902. */
  28903. var AssetContainer = /** @class */ (function (_super) {
  28904. __extends(AssetContainer, _super);
  28905. /**
  28906. * Instantiates an AssetContainer.
  28907. * @param scene The scene the AssetContainer belongs to.
  28908. */
  28909. function AssetContainer(scene) {
  28910. var _this = _super.call(this) || this;
  28911. _this.scene = scene;
  28912. return _this;
  28913. }
  28914. /**
  28915. * Adds all the assets from the container to the scene.
  28916. */
  28917. AssetContainer.prototype.addAllToScene = function () {
  28918. var _this = this;
  28919. this.cameras.forEach(function (o) {
  28920. _this.scene.addCamera(o);
  28921. });
  28922. this.lights.forEach(function (o) {
  28923. _this.scene.addLight(o);
  28924. });
  28925. this.meshes.forEach(function (o) {
  28926. _this.scene.addMesh(o);
  28927. });
  28928. this.skeletons.forEach(function (o) {
  28929. _this.scene.addSkeleton(o);
  28930. });
  28931. this.animations.forEach(function (o) {
  28932. _this.scene.addAnimation(o);
  28933. });
  28934. this.animationGroups.forEach(function (o) {
  28935. _this.scene.addAnimationGroup(o);
  28936. });
  28937. this.multiMaterials.forEach(function (o) {
  28938. _this.scene.addMultiMaterial(o);
  28939. });
  28940. this.materials.forEach(function (o) {
  28941. _this.scene.addMaterial(o);
  28942. });
  28943. this.morphTargetManagers.forEach(function (o) {
  28944. _this.scene.addMorphTargetManager(o);
  28945. });
  28946. this.geometries.forEach(function (o) {
  28947. _this.scene.addGeometry(o);
  28948. });
  28949. this.transformNodes.forEach(function (o) {
  28950. _this.scene.addTransformNode(o);
  28951. });
  28952. this.actionManagers.forEach(function (o) {
  28953. _this.scene.addActionManager(o);
  28954. });
  28955. this.sounds.forEach(function (o) {
  28956. o.play();
  28957. o.autoplay = true;
  28958. _this.scene.mainSoundTrack.AddSound(o);
  28959. });
  28960. this.textures.forEach(function (o) {
  28961. _this.scene.addTexture(o);
  28962. });
  28963. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28964. var component = _a[_i];
  28965. component.addFromContainer(this.scene);
  28966. }
  28967. };
  28968. /**
  28969. * Removes all the assets in the container from the scene
  28970. */
  28971. AssetContainer.prototype.removeAllFromScene = function () {
  28972. var _this = this;
  28973. this.cameras.forEach(function (o) {
  28974. _this.scene.removeCamera(o);
  28975. });
  28976. this.lights.forEach(function (o) {
  28977. _this.scene.removeLight(o);
  28978. });
  28979. this.meshes.forEach(function (o) {
  28980. _this.scene.removeMesh(o);
  28981. });
  28982. this.skeletons.forEach(function (o) {
  28983. _this.scene.removeSkeleton(o);
  28984. });
  28985. this.animations.forEach(function (o) {
  28986. _this.scene.removeAnimation(o);
  28987. });
  28988. this.animationGroups.forEach(function (o) {
  28989. _this.scene.removeAnimationGroup(o);
  28990. });
  28991. this.multiMaterials.forEach(function (o) {
  28992. _this.scene.removeMultiMaterial(o);
  28993. });
  28994. this.materials.forEach(function (o) {
  28995. _this.scene.removeMaterial(o);
  28996. });
  28997. this.morphTargetManagers.forEach(function (o) {
  28998. _this.scene.removeMorphTargetManager(o);
  28999. });
  29000. this.geometries.forEach(function (o) {
  29001. _this.scene.removeGeometry(o);
  29002. });
  29003. this.transformNodes.forEach(function (o) {
  29004. _this.scene.removeTransformNode(o);
  29005. });
  29006. this.actionManagers.forEach(function (o) {
  29007. _this.scene.removeActionManager(o);
  29008. });
  29009. this.sounds.forEach(function (o) {
  29010. o.stop();
  29011. o.autoplay = false;
  29012. _this.scene.mainSoundTrack.RemoveSound(o);
  29013. });
  29014. this.textures.forEach(function (o) {
  29015. _this.scene.removeTexture(o);
  29016. });
  29017. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29018. var component = _a[_i];
  29019. component.removeFromContainer(this.scene);
  29020. }
  29021. };
  29022. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29023. if (!sourceAssets) {
  29024. return;
  29025. }
  29026. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29027. var asset = sourceAssets_1[_i];
  29028. var move = true;
  29029. if (keepAssets) {
  29030. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29031. var keepAsset = keepAssets_1[_a];
  29032. if (asset === keepAsset) {
  29033. move = false;
  29034. break;
  29035. }
  29036. }
  29037. }
  29038. if (move) {
  29039. targetAssets.push(asset);
  29040. }
  29041. }
  29042. };
  29043. /**
  29044. * Removes all the assets contained in the scene and adds them to the container.
  29045. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29046. */
  29047. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29048. if (keepAssets === undefined) {
  29049. keepAssets = new KeepAssets();
  29050. }
  29051. for (var key in this) {
  29052. if (this.hasOwnProperty(key)) {
  29053. this[key] = this[key] || [];
  29054. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29055. }
  29056. }
  29057. this.removeAllFromScene();
  29058. };
  29059. /**
  29060. * 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.
  29061. * @returns the root mesh
  29062. */
  29063. AssetContainer.prototype.createRootMesh = function () {
  29064. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29065. this.meshes.forEach(function (m) {
  29066. if (!m.parent) {
  29067. rootMesh.addChild(m);
  29068. }
  29069. });
  29070. this.meshes.unshift(rootMesh);
  29071. return rootMesh;
  29072. };
  29073. return AssetContainer;
  29074. }(BABYLON.AbstractScene));
  29075. BABYLON.AssetContainer = AssetContainer;
  29076. })(BABYLON || (BABYLON = {}));
  29077. //# sourceMappingURL=babylon.assetContainer.js.map
  29078. var BABYLON;
  29079. (function (BABYLON) {
  29080. var Buffer = /** @class */ (function () {
  29081. /**
  29082. * Constructor
  29083. * @param engine the engine
  29084. * @param data the data to use for this buffer
  29085. * @param updatable whether the data is updatable
  29086. * @param stride the stride (optional)
  29087. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29088. * @param instanced whether the buffer is instanced (optional)
  29089. * @param useBytes set to true if the stride in in bytes (optional)
  29090. */
  29091. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29092. if (stride === void 0) { stride = 0; }
  29093. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29094. if (instanced === void 0) { instanced = false; }
  29095. if (useBytes === void 0) { useBytes = false; }
  29096. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29097. this._engine = engine.getScene().getEngine();
  29098. }
  29099. else {
  29100. this._engine = engine;
  29101. }
  29102. this._updatable = updatable;
  29103. this._instanced = instanced;
  29104. this._data = data;
  29105. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29106. if (!postponeInternalCreation) { // by default
  29107. this.create();
  29108. }
  29109. }
  29110. /**
  29111. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29112. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29113. * @param offset defines offset in the buffer (0 by default)
  29114. * @param size defines the size in floats of attributes (position is 3 for instance)
  29115. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29116. * @param instanced defines if the vertex buffer contains indexed data
  29117. * @param useBytes defines if the offset and stride are in bytes
  29118. * @returns the new vertex buffer
  29119. */
  29120. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29121. if (useBytes === void 0) { useBytes = false; }
  29122. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29123. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29124. // a lot of these parameters are ignored as they are overriden by the buffer
  29125. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29126. };
  29127. // Properties
  29128. Buffer.prototype.isUpdatable = function () {
  29129. return this._updatable;
  29130. };
  29131. Buffer.prototype.getData = function () {
  29132. return this._data;
  29133. };
  29134. Buffer.prototype.getBuffer = function () {
  29135. return this._buffer;
  29136. };
  29137. /**
  29138. * Gets the stride in float32 units (i.e. byte stride / 4).
  29139. * May not be an integer if the byte stride is not divisible by 4.
  29140. * DEPRECATED. Use byteStride instead.
  29141. * @returns the stride in float32 units
  29142. */
  29143. Buffer.prototype.getStrideSize = function () {
  29144. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29145. };
  29146. // Methods
  29147. Buffer.prototype.create = function (data) {
  29148. if (data === void 0) { data = null; }
  29149. if (!data && this._buffer) {
  29150. return; // nothing to do
  29151. }
  29152. data = data || this._data;
  29153. if (!data) {
  29154. return;
  29155. }
  29156. if (!this._buffer) { // create buffer
  29157. if (this._updatable) {
  29158. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29159. this._data = data;
  29160. }
  29161. else {
  29162. this._buffer = this._engine.createVertexBuffer(data);
  29163. }
  29164. }
  29165. else if (this._updatable) { // update buffer
  29166. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29167. this._data = data;
  29168. }
  29169. };
  29170. Buffer.prototype._rebuild = function () {
  29171. this._buffer = null;
  29172. this.create(this._data);
  29173. };
  29174. Buffer.prototype.update = function (data) {
  29175. this.create(data);
  29176. };
  29177. /**
  29178. * Updates the data directly.
  29179. * @param data the new data
  29180. * @param offset the new offset
  29181. * @param vertexCount the vertex count (optional)
  29182. * @param useBytes set to true if the offset is in bytes
  29183. */
  29184. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29185. if (useBytes === void 0) { useBytes = false; }
  29186. if (!this._buffer) {
  29187. return;
  29188. }
  29189. if (this._updatable) { // update buffer
  29190. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29191. this._data = null;
  29192. }
  29193. };
  29194. Buffer.prototype.dispose = function () {
  29195. if (!this._buffer) {
  29196. return;
  29197. }
  29198. if (this._engine._releaseBuffer(this._buffer)) {
  29199. this._buffer = null;
  29200. }
  29201. };
  29202. return Buffer;
  29203. }());
  29204. BABYLON.Buffer = Buffer;
  29205. })(BABYLON || (BABYLON = {}));
  29206. //# sourceMappingURL=babylon.buffer.js.map
  29207. var BABYLON;
  29208. (function (BABYLON) {
  29209. var VertexBuffer = /** @class */ (function () {
  29210. /**
  29211. * Constructor
  29212. * @param engine the engine
  29213. * @param data the data to use for this vertex buffer
  29214. * @param kind the vertex buffer kind
  29215. * @param updatable whether the data is updatable
  29216. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29217. * @param stride the stride (optional)
  29218. * @param instanced whether the buffer is instanced (optional)
  29219. * @param offset the offset of the data (optional)
  29220. * @param size the number of components (optional)
  29221. * @param type the type of the component (optional)
  29222. * @param normalized whether the data contains normalized data (optional)
  29223. * @param useBytes set to true if stride and offset are in bytes (optional)
  29224. */
  29225. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29226. if (normalized === void 0) { normalized = false; }
  29227. if (useBytes === void 0) { useBytes = false; }
  29228. if (data instanceof BABYLON.Buffer) {
  29229. this._buffer = data;
  29230. this._ownsBuffer = false;
  29231. }
  29232. else {
  29233. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29234. this._ownsBuffer = true;
  29235. }
  29236. this._kind = kind;
  29237. if (type == undefined) {
  29238. var data_1 = this.getData();
  29239. this.type = VertexBuffer.FLOAT;
  29240. if (data_1 instanceof Int8Array)
  29241. this.type = VertexBuffer.BYTE;
  29242. else if (data_1 instanceof Uint8Array)
  29243. this.type = VertexBuffer.UNSIGNED_BYTE;
  29244. else if (data_1 instanceof Int16Array)
  29245. this.type = VertexBuffer.SHORT;
  29246. else if (data_1 instanceof Uint16Array)
  29247. this.type = VertexBuffer.UNSIGNED_SHORT;
  29248. else if (data_1 instanceof Int32Array)
  29249. this.type = VertexBuffer.INT;
  29250. else if (data_1 instanceof Uint32Array)
  29251. this.type = VertexBuffer.UNSIGNED_INT;
  29252. }
  29253. else {
  29254. this.type = type;
  29255. }
  29256. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29257. if (useBytes) {
  29258. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29259. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29260. this.byteOffset = offset || 0;
  29261. }
  29262. else {
  29263. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29264. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29265. this.byteOffset = (offset || 0) * typeByteLength;
  29266. }
  29267. this.normalized = normalized;
  29268. this._instanced = instanced !== undefined ? instanced : false;
  29269. this._instanceDivisor = instanced ? 1 : 0;
  29270. }
  29271. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29272. /**
  29273. * Gets or sets the instance divisor when in instanced mode
  29274. */
  29275. get: function () {
  29276. return this._instanceDivisor;
  29277. },
  29278. set: function (value) {
  29279. this._instanceDivisor = value;
  29280. if (value == 0) {
  29281. this._instanced = false;
  29282. }
  29283. else {
  29284. this._instanced = true;
  29285. }
  29286. },
  29287. enumerable: true,
  29288. configurable: true
  29289. });
  29290. VertexBuffer.prototype._rebuild = function () {
  29291. if (!this._buffer) {
  29292. return;
  29293. }
  29294. this._buffer._rebuild();
  29295. };
  29296. /**
  29297. * Returns the kind of the VertexBuffer (string).
  29298. */
  29299. VertexBuffer.prototype.getKind = function () {
  29300. return this._kind;
  29301. };
  29302. // Properties
  29303. /**
  29304. * Boolean : is the VertexBuffer updatable ?
  29305. */
  29306. VertexBuffer.prototype.isUpdatable = function () {
  29307. return this._buffer.isUpdatable();
  29308. };
  29309. /**
  29310. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29311. */
  29312. VertexBuffer.prototype.getData = function () {
  29313. return this._buffer.getData();
  29314. };
  29315. /**
  29316. * Returns the WebGLBuffer associated to the VertexBuffer.
  29317. */
  29318. VertexBuffer.prototype.getBuffer = function () {
  29319. return this._buffer.getBuffer();
  29320. };
  29321. /**
  29322. * Returns the stride as a multiple of the type byte length.
  29323. * DEPRECATED. Use byteStride instead.
  29324. */
  29325. VertexBuffer.prototype.getStrideSize = function () {
  29326. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29327. };
  29328. /**
  29329. * Returns the offset as a multiple of the type byte length.
  29330. * DEPRECATED. Use byteOffset instead.
  29331. */
  29332. VertexBuffer.prototype.getOffset = function () {
  29333. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29334. };
  29335. /**
  29336. * Returns the number of components per vertex attribute (integer).
  29337. */
  29338. VertexBuffer.prototype.getSize = function () {
  29339. return this._size;
  29340. };
  29341. /**
  29342. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29343. */
  29344. VertexBuffer.prototype.getIsInstanced = function () {
  29345. return this._instanced;
  29346. };
  29347. /**
  29348. * Returns the instancing divisor, zero for non-instanced (integer).
  29349. */
  29350. VertexBuffer.prototype.getInstanceDivisor = function () {
  29351. return this._instanceDivisor;
  29352. };
  29353. // Methods
  29354. /**
  29355. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29356. * Returns the created WebGLBuffer.
  29357. */
  29358. VertexBuffer.prototype.create = function (data) {
  29359. return this._buffer.create(data);
  29360. };
  29361. /**
  29362. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29363. * This function will create a new buffer if the current one is not updatable
  29364. * Returns the updated WebGLBuffer.
  29365. */
  29366. VertexBuffer.prototype.update = function (data) {
  29367. return this._buffer.update(data);
  29368. };
  29369. /**
  29370. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29371. * Returns the directly updated WebGLBuffer.
  29372. * @param data the new data
  29373. * @param offset the new offset
  29374. * @param useBytes set to true if the offset is in bytes
  29375. */
  29376. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29377. if (useBytes === void 0) { useBytes = false; }
  29378. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29379. };
  29380. /**
  29381. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29382. */
  29383. VertexBuffer.prototype.dispose = function () {
  29384. if (this._ownsBuffer) {
  29385. this._buffer.dispose();
  29386. }
  29387. };
  29388. /**
  29389. * Enumerates each value of this vertex buffer as numbers.
  29390. * @param count the number of values to enumerate
  29391. * @param callback the callback function called for each value
  29392. */
  29393. VertexBuffer.prototype.forEach = function (count, callback) {
  29394. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29395. };
  29396. Object.defineProperty(VertexBuffer, "PositionKind", {
  29397. get: function () {
  29398. return VertexBuffer._PositionKind;
  29399. },
  29400. enumerable: true,
  29401. configurable: true
  29402. });
  29403. Object.defineProperty(VertexBuffer, "NormalKind", {
  29404. get: function () {
  29405. return VertexBuffer._NormalKind;
  29406. },
  29407. enumerable: true,
  29408. configurable: true
  29409. });
  29410. Object.defineProperty(VertexBuffer, "TangentKind", {
  29411. get: function () {
  29412. return VertexBuffer._TangentKind;
  29413. },
  29414. enumerable: true,
  29415. configurable: true
  29416. });
  29417. Object.defineProperty(VertexBuffer, "UVKind", {
  29418. get: function () {
  29419. return VertexBuffer._UVKind;
  29420. },
  29421. enumerable: true,
  29422. configurable: true
  29423. });
  29424. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29425. get: function () {
  29426. return VertexBuffer._UV2Kind;
  29427. },
  29428. enumerable: true,
  29429. configurable: true
  29430. });
  29431. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29432. get: function () {
  29433. return VertexBuffer._UV3Kind;
  29434. },
  29435. enumerable: true,
  29436. configurable: true
  29437. });
  29438. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29439. get: function () {
  29440. return VertexBuffer._UV4Kind;
  29441. },
  29442. enumerable: true,
  29443. configurable: true
  29444. });
  29445. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29446. get: function () {
  29447. return VertexBuffer._UV5Kind;
  29448. },
  29449. enumerable: true,
  29450. configurable: true
  29451. });
  29452. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29453. get: function () {
  29454. return VertexBuffer._UV6Kind;
  29455. },
  29456. enumerable: true,
  29457. configurable: true
  29458. });
  29459. Object.defineProperty(VertexBuffer, "ColorKind", {
  29460. get: function () {
  29461. return VertexBuffer._ColorKind;
  29462. },
  29463. enumerable: true,
  29464. configurable: true
  29465. });
  29466. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29467. get: function () {
  29468. return VertexBuffer._MatricesIndicesKind;
  29469. },
  29470. enumerable: true,
  29471. configurable: true
  29472. });
  29473. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29474. get: function () {
  29475. return VertexBuffer._MatricesWeightsKind;
  29476. },
  29477. enumerable: true,
  29478. configurable: true
  29479. });
  29480. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29481. get: function () {
  29482. return VertexBuffer._MatricesIndicesExtraKind;
  29483. },
  29484. enumerable: true,
  29485. configurable: true
  29486. });
  29487. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29488. get: function () {
  29489. return VertexBuffer._MatricesWeightsExtraKind;
  29490. },
  29491. enumerable: true,
  29492. configurable: true
  29493. });
  29494. /**
  29495. * Deduces the stride given a kind.
  29496. * @param kind The kind string to deduce
  29497. * @returns The deduced stride
  29498. */
  29499. VertexBuffer.DeduceStride = function (kind) {
  29500. switch (kind) {
  29501. case VertexBuffer.UVKind:
  29502. case VertexBuffer.UV2Kind:
  29503. case VertexBuffer.UV3Kind:
  29504. case VertexBuffer.UV4Kind:
  29505. case VertexBuffer.UV5Kind:
  29506. case VertexBuffer.UV6Kind:
  29507. return 2;
  29508. case VertexBuffer.NormalKind:
  29509. case VertexBuffer.PositionKind:
  29510. return 3;
  29511. case VertexBuffer.ColorKind:
  29512. case VertexBuffer.MatricesIndicesKind:
  29513. case VertexBuffer.MatricesIndicesExtraKind:
  29514. case VertexBuffer.MatricesWeightsKind:
  29515. case VertexBuffer.MatricesWeightsExtraKind:
  29516. case VertexBuffer.TangentKind:
  29517. return 4;
  29518. default:
  29519. throw new Error("Invalid kind '" + kind + "'");
  29520. }
  29521. };
  29522. /**
  29523. * Gets the byte length of the given type.
  29524. * @param type the type
  29525. * @returns the number of bytes
  29526. */
  29527. VertexBuffer.GetTypeByteLength = function (type) {
  29528. switch (type) {
  29529. case VertexBuffer.BYTE:
  29530. case VertexBuffer.UNSIGNED_BYTE:
  29531. return 1;
  29532. case VertexBuffer.SHORT:
  29533. case VertexBuffer.UNSIGNED_SHORT:
  29534. return 2;
  29535. case VertexBuffer.INT:
  29536. case VertexBuffer.FLOAT:
  29537. return 4;
  29538. default:
  29539. throw new Error("Invalid type '" + type + "'");
  29540. }
  29541. };
  29542. /**
  29543. * Enumerates each value of the given parameters as numbers.
  29544. * @param data the data to enumerate
  29545. * @param byteOffset the byte offset of the data
  29546. * @param byteStride the byte stride of the data
  29547. * @param componentCount the number of components per element
  29548. * @param componentType the type of the component
  29549. * @param count the total number of components
  29550. * @param normalized whether the data is normalized
  29551. * @param callback the callback function called for each value
  29552. */
  29553. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29554. if (data instanceof Array) {
  29555. var offset = byteOffset / 4;
  29556. var stride = byteStride / 4;
  29557. for (var index = 0; index < count; index += componentCount) {
  29558. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29559. callback(data[offset + componentIndex], index + componentIndex);
  29560. }
  29561. offset += stride;
  29562. }
  29563. }
  29564. else {
  29565. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29566. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29567. for (var index = 0; index < count; index += componentCount) {
  29568. var componentByteOffset = byteOffset;
  29569. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29570. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29571. callback(value, index + componentIndex);
  29572. componentByteOffset += componentByteLength;
  29573. }
  29574. byteOffset += byteStride;
  29575. }
  29576. }
  29577. };
  29578. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29579. switch (type) {
  29580. case VertexBuffer.BYTE: {
  29581. var value = dataView.getInt8(byteOffset);
  29582. if (normalized) {
  29583. value = Math.max(value / 127, -1);
  29584. }
  29585. return value;
  29586. }
  29587. case VertexBuffer.UNSIGNED_BYTE: {
  29588. var value = dataView.getUint8(byteOffset);
  29589. if (normalized) {
  29590. value = value / 255;
  29591. }
  29592. return value;
  29593. }
  29594. case VertexBuffer.SHORT: {
  29595. var value = dataView.getInt16(byteOffset, true);
  29596. if (normalized) {
  29597. value = Math.max(value / 16383, -1);
  29598. }
  29599. return value;
  29600. }
  29601. case VertexBuffer.UNSIGNED_SHORT: {
  29602. var value = dataView.getUint16(byteOffset, true);
  29603. if (normalized) {
  29604. value = value / 65535;
  29605. }
  29606. return value;
  29607. }
  29608. case VertexBuffer.FLOAT: {
  29609. return dataView.getFloat32(byteOffset, true);
  29610. }
  29611. default: {
  29612. throw new Error("Invalid component type " + type);
  29613. }
  29614. }
  29615. };
  29616. /**
  29617. * The byte type.
  29618. */
  29619. VertexBuffer.BYTE = 5120;
  29620. /**
  29621. * The unsigned byte type.
  29622. */
  29623. VertexBuffer.UNSIGNED_BYTE = 5121;
  29624. /**
  29625. * The short type.
  29626. */
  29627. VertexBuffer.SHORT = 5122;
  29628. /**
  29629. * The unsigned short type.
  29630. */
  29631. VertexBuffer.UNSIGNED_SHORT = 5123;
  29632. /**
  29633. * The integer type.
  29634. */
  29635. VertexBuffer.INT = 5124;
  29636. /**
  29637. * The unsigned integer type.
  29638. */
  29639. VertexBuffer.UNSIGNED_INT = 5125;
  29640. /**
  29641. * The float type.
  29642. */
  29643. VertexBuffer.FLOAT = 5126;
  29644. // Enums
  29645. VertexBuffer._PositionKind = "position";
  29646. VertexBuffer._NormalKind = "normal";
  29647. VertexBuffer._TangentKind = "tangent";
  29648. VertexBuffer._UVKind = "uv";
  29649. VertexBuffer._UV2Kind = "uv2";
  29650. VertexBuffer._UV3Kind = "uv3";
  29651. VertexBuffer._UV4Kind = "uv4";
  29652. VertexBuffer._UV5Kind = "uv5";
  29653. VertexBuffer._UV6Kind = "uv6";
  29654. VertexBuffer._ColorKind = "color";
  29655. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29656. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29657. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29658. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29659. return VertexBuffer;
  29660. }());
  29661. BABYLON.VertexBuffer = VertexBuffer;
  29662. })(BABYLON || (BABYLON = {}));
  29663. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29664. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29665. var BABYLON;
  29666. (function (BABYLON) {
  29667. /**
  29668. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29669. */
  29670. var DummyInternalTextureTracker = /** @class */ (function () {
  29671. function DummyInternalTextureTracker() {
  29672. /**
  29673. * Gets or set the previous tracker in the list
  29674. */
  29675. this.previous = null;
  29676. /**
  29677. * Gets or set the next tracker in the list
  29678. */
  29679. this.next = null;
  29680. }
  29681. return DummyInternalTextureTracker;
  29682. }());
  29683. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29684. })(BABYLON || (BABYLON = {}));
  29685. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29686. var BABYLON;
  29687. (function (BABYLON) {
  29688. /**
  29689. * Class used to store data associated with WebGL texture data for the engine
  29690. * This class should not be used directly
  29691. */
  29692. var InternalTexture = /** @class */ (function () {
  29693. /**
  29694. * Creates a new InternalTexture
  29695. * @param engine defines the engine to use
  29696. * @param dataSource defines the type of data that will be used
  29697. */
  29698. function InternalTexture(engine, dataSource) {
  29699. /**
  29700. * Observable called when the texture is loaded
  29701. */
  29702. this.onLoadedObservable = new BABYLON.Observable();
  29703. /**
  29704. * Gets or set the previous tracker in the list
  29705. */
  29706. this.previous = null;
  29707. /**
  29708. * Gets or set the next tracker in the list
  29709. */
  29710. this.next = null;
  29711. // Private
  29712. /** @hidden */
  29713. this._initialSlot = -1;
  29714. /** @hidden */
  29715. this._designatedSlot = -1;
  29716. /** @hidden */
  29717. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29718. /** @hidden */
  29719. this._comparisonFunction = 0;
  29720. /** @hidden */
  29721. this._sphericalPolynomial = null;
  29722. /** @hidden */
  29723. this._lodGenerationScale = 0;
  29724. /** @hidden */
  29725. this._lodGenerationOffset = 0;
  29726. /** @hidden */
  29727. this._isRGBD = false;
  29728. /** @hidden */
  29729. this._references = 1;
  29730. this._engine = engine;
  29731. this._dataSource = dataSource;
  29732. this._webGLTexture = engine._createTexture();
  29733. }
  29734. /**
  29735. * Gets the Engine the texture belongs to.
  29736. * @returns The babylon engine
  29737. */
  29738. InternalTexture.prototype.getEngine = function () {
  29739. return this._engine;
  29740. };
  29741. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29742. /**
  29743. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29744. */
  29745. get: function () {
  29746. return this._dataSource;
  29747. },
  29748. enumerable: true,
  29749. configurable: true
  29750. });
  29751. /**
  29752. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29753. */
  29754. InternalTexture.prototype.incrementReferences = function () {
  29755. this._references++;
  29756. };
  29757. /**
  29758. * Change the size of the texture (not the size of the content)
  29759. * @param width defines the new width
  29760. * @param height defines the new height
  29761. * @param depth defines the new depth (1 by default)
  29762. */
  29763. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29764. if (depth === void 0) { depth = 1; }
  29765. this.width = width;
  29766. this.height = height;
  29767. this.depth = depth;
  29768. this.baseWidth = width;
  29769. this.baseHeight = height;
  29770. this.baseDepth = depth;
  29771. this._size = width * height * depth;
  29772. };
  29773. /** @hidden */
  29774. InternalTexture.prototype._rebuild = function () {
  29775. var _this = this;
  29776. var proxy;
  29777. this.isReady = false;
  29778. this._cachedCoordinatesMode = null;
  29779. this._cachedWrapU = null;
  29780. this._cachedWrapV = null;
  29781. this._cachedAnisotropicFilteringLevel = null;
  29782. switch (this._dataSource) {
  29783. case InternalTexture.DATASOURCE_TEMP:
  29784. return;
  29785. case InternalTexture.DATASOURCE_URL:
  29786. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29787. _this.isReady = true;
  29788. }, null, this._buffer, undefined, this.format);
  29789. proxy._swapAndDie(this);
  29790. return;
  29791. case InternalTexture.DATASOURCE_RAW:
  29792. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29793. proxy._swapAndDie(this);
  29794. this.isReady = true;
  29795. return;
  29796. case InternalTexture.DATASOURCE_RAW3D:
  29797. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29798. proxy._swapAndDie(this);
  29799. this.isReady = true;
  29800. return;
  29801. case InternalTexture.DATASOURCE_DYNAMIC:
  29802. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29803. proxy._swapAndDie(this);
  29804. // The engine will make sure to update content so no need to flag it as isReady = true
  29805. return;
  29806. case InternalTexture.DATASOURCE_RENDERTARGET:
  29807. var options = new BABYLON.RenderTargetCreationOptions();
  29808. options.generateDepthBuffer = this._generateDepthBuffer;
  29809. options.generateMipMaps = this.generateMipMaps;
  29810. options.generateStencilBuffer = this._generateStencilBuffer;
  29811. options.samplingMode = this.samplingMode;
  29812. options.type = this.type;
  29813. if (this.isCube) {
  29814. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29815. }
  29816. else {
  29817. var size = {
  29818. width: this.width,
  29819. height: this.height
  29820. };
  29821. proxy = this._engine.createRenderTargetTexture(size, options);
  29822. }
  29823. proxy._swapAndDie(this);
  29824. this.isReady = true;
  29825. return;
  29826. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29827. var depthTextureOptions = {
  29828. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29829. comparisonFunction: this._comparisonFunction,
  29830. generateStencil: this._generateStencilBuffer,
  29831. isCube: this.isCube
  29832. };
  29833. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29834. proxy._swapAndDie(this);
  29835. this.isReady = true;
  29836. return;
  29837. case InternalTexture.DATASOURCE_CUBE:
  29838. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29839. _this.isReady = true;
  29840. }, null, this.format, this._extension);
  29841. proxy._swapAndDie(this);
  29842. return;
  29843. case InternalTexture.DATASOURCE_CUBERAW:
  29844. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29845. proxy._swapAndDie(this);
  29846. this.isReady = true;
  29847. return;
  29848. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29849. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29850. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29851. _this.isReady = true;
  29852. });
  29853. proxy._swapAndDie(this);
  29854. return;
  29855. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29856. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29857. if (proxy) {
  29858. proxy._swapAndDie(_this);
  29859. }
  29860. _this.isReady = true;
  29861. }, null, this.format, this._extension);
  29862. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29863. return;
  29864. }
  29865. };
  29866. InternalTexture.prototype._swapAndDie = function (target) {
  29867. target._webGLTexture = this._webGLTexture;
  29868. if (this._framebuffer) {
  29869. target._framebuffer = this._framebuffer;
  29870. }
  29871. if (this._depthStencilBuffer) {
  29872. target._depthStencilBuffer = this._depthStencilBuffer;
  29873. }
  29874. if (this._lodTextureHigh) {
  29875. if (target._lodTextureHigh) {
  29876. target._lodTextureHigh.dispose();
  29877. }
  29878. target._lodTextureHigh = this._lodTextureHigh;
  29879. }
  29880. if (this._lodTextureMid) {
  29881. if (target._lodTextureMid) {
  29882. target._lodTextureMid.dispose();
  29883. }
  29884. target._lodTextureMid = this._lodTextureMid;
  29885. }
  29886. if (this._lodTextureLow) {
  29887. if (target._lodTextureLow) {
  29888. target._lodTextureLow.dispose();
  29889. }
  29890. target._lodTextureLow = this._lodTextureLow;
  29891. }
  29892. var cache = this._engine.getLoadedTexturesCache();
  29893. var index = cache.indexOf(this);
  29894. if (index !== -1) {
  29895. cache.splice(index, 1);
  29896. }
  29897. };
  29898. /**
  29899. * Dispose the current allocated resources
  29900. */
  29901. InternalTexture.prototype.dispose = function () {
  29902. if (!this._webGLTexture) {
  29903. return;
  29904. }
  29905. this._references--;
  29906. if (this._references === 0) {
  29907. this._engine._releaseTexture(this);
  29908. this._webGLTexture = null;
  29909. this.previous = null;
  29910. this.next = null;
  29911. }
  29912. };
  29913. /**
  29914. * The source of the texture data is unknown
  29915. */
  29916. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29917. /**
  29918. * Texture data comes from an URL
  29919. */
  29920. InternalTexture.DATASOURCE_URL = 1;
  29921. /**
  29922. * Texture data is only used for temporary storage
  29923. */
  29924. InternalTexture.DATASOURCE_TEMP = 2;
  29925. /**
  29926. * Texture data comes from raw data (ArrayBuffer)
  29927. */
  29928. InternalTexture.DATASOURCE_RAW = 3;
  29929. /**
  29930. * Texture content is dynamic (video or dynamic texture)
  29931. */
  29932. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29933. /**
  29934. * Texture content is generated by rendering to it
  29935. */
  29936. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29937. /**
  29938. * Texture content is part of a multi render target process
  29939. */
  29940. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29941. /**
  29942. * Texture data comes from a cube data file
  29943. */
  29944. InternalTexture.DATASOURCE_CUBE = 7;
  29945. /**
  29946. * Texture data comes from a raw cube data
  29947. */
  29948. InternalTexture.DATASOURCE_CUBERAW = 8;
  29949. /**
  29950. * Texture data come from a prefiltered cube data file
  29951. */
  29952. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29953. /**
  29954. * Texture content is raw 3D data
  29955. */
  29956. InternalTexture.DATASOURCE_RAW3D = 10;
  29957. /**
  29958. * Texture content is a depth texture
  29959. */
  29960. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29961. /**
  29962. * Texture data comes from a raw cube data encoded with RGBD
  29963. */
  29964. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29965. return InternalTexture;
  29966. }());
  29967. BABYLON.InternalTexture = InternalTexture;
  29968. })(BABYLON || (BABYLON = {}));
  29969. //# sourceMappingURL=babylon.internalTexture.js.map
  29970. var BABYLON;
  29971. (function (BABYLON) {
  29972. var BaseTexture = /** @class */ (function () {
  29973. function BaseTexture(scene) {
  29974. this._hasAlpha = false;
  29975. this.getAlphaFromRGB = false;
  29976. this.level = 1;
  29977. this.coordinatesIndex = 0;
  29978. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29979. /**
  29980. * | Value | Type | Description |
  29981. * | ----- | ------------------ | ----------- |
  29982. * | 0 | CLAMP_ADDRESSMODE | |
  29983. * | 1 | WRAP_ADDRESSMODE | |
  29984. * | 2 | MIRROR_ADDRESSMODE | |
  29985. */
  29986. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29987. /**
  29988. * | Value | Type | Description |
  29989. * | ----- | ------------------ | ----------- |
  29990. * | 0 | CLAMP_ADDRESSMODE | |
  29991. * | 1 | WRAP_ADDRESSMODE | |
  29992. * | 2 | MIRROR_ADDRESSMODE | |
  29993. */
  29994. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29995. /**
  29996. * | Value | Type | Description |
  29997. * | ----- | ------------------ | ----------- |
  29998. * | 0 | CLAMP_ADDRESSMODE | |
  29999. * | 1 | WRAP_ADDRESSMODE | |
  30000. * | 2 | MIRROR_ADDRESSMODE | |
  30001. */
  30002. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30003. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30004. this.isCube = false;
  30005. this.is3D = false;
  30006. this.gammaSpace = true;
  30007. this.invertZ = false;
  30008. this.lodLevelInAlpha = false;
  30009. this.isRenderTarget = false;
  30010. this.animations = new Array();
  30011. /**
  30012. * An event triggered when the texture is disposed.
  30013. */
  30014. this.onDisposeObservable = new BABYLON.Observable();
  30015. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30016. this._cachedSize = BABYLON.Size.Zero();
  30017. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30018. if (this._scene) {
  30019. this._scene.textures.push(this);
  30020. }
  30021. this._uid = null;
  30022. }
  30023. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30024. get: function () {
  30025. return this._hasAlpha;
  30026. },
  30027. set: function (value) {
  30028. if (this._hasAlpha === value) {
  30029. return;
  30030. }
  30031. this._hasAlpha = value;
  30032. if (this._scene) {
  30033. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30034. }
  30035. },
  30036. enumerable: true,
  30037. configurable: true
  30038. });
  30039. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30040. get: function () {
  30041. return this._coordinatesMode;
  30042. },
  30043. /**
  30044. * How a texture is mapped.
  30045. *
  30046. * | Value | Type | Description |
  30047. * | ----- | ----------------------------------- | ----------- |
  30048. * | 0 | EXPLICIT_MODE | |
  30049. * | 1 | SPHERICAL_MODE | |
  30050. * | 2 | PLANAR_MODE | |
  30051. * | 3 | CUBIC_MODE | |
  30052. * | 4 | PROJECTION_MODE | |
  30053. * | 5 | SKYBOX_MODE | |
  30054. * | 6 | INVCUBIC_MODE | |
  30055. * | 7 | EQUIRECTANGULAR_MODE | |
  30056. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30057. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30058. */
  30059. set: function (value) {
  30060. if (this._coordinatesMode === value) {
  30061. return;
  30062. }
  30063. this._coordinatesMode = value;
  30064. if (this._scene) {
  30065. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30066. }
  30067. },
  30068. enumerable: true,
  30069. configurable: true
  30070. });
  30071. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30072. /**
  30073. * Gets whether or not the texture contains RGBD data.
  30074. */
  30075. get: function () {
  30076. return this._texture != null && this._texture._isRGBD;
  30077. },
  30078. enumerable: true,
  30079. configurable: true
  30080. });
  30081. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30082. get: function () {
  30083. if (this._texture)
  30084. return this._texture._lodGenerationOffset;
  30085. return 0.0;
  30086. },
  30087. set: function (value) {
  30088. if (this._texture)
  30089. this._texture._lodGenerationOffset = value;
  30090. },
  30091. enumerable: true,
  30092. configurable: true
  30093. });
  30094. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30095. get: function () {
  30096. if (this._texture)
  30097. return this._texture._lodGenerationScale;
  30098. return 0.0;
  30099. },
  30100. set: function (value) {
  30101. if (this._texture)
  30102. this._texture._lodGenerationScale = value;
  30103. },
  30104. enumerable: true,
  30105. configurable: true
  30106. });
  30107. Object.defineProperty(BaseTexture.prototype, "uid", {
  30108. get: function () {
  30109. if (!this._uid) {
  30110. this._uid = BABYLON.Tools.RandomId();
  30111. }
  30112. return this._uid;
  30113. },
  30114. enumerable: true,
  30115. configurable: true
  30116. });
  30117. BaseTexture.prototype.toString = function () {
  30118. return this.name;
  30119. };
  30120. BaseTexture.prototype.getClassName = function () {
  30121. return "BaseTexture";
  30122. };
  30123. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30124. set: function (callback) {
  30125. if (this._onDisposeObserver) {
  30126. this.onDisposeObservable.remove(this._onDisposeObserver);
  30127. }
  30128. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30129. },
  30130. enumerable: true,
  30131. configurable: true
  30132. });
  30133. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30134. get: function () {
  30135. return true;
  30136. },
  30137. enumerable: true,
  30138. configurable: true
  30139. });
  30140. BaseTexture.prototype.getScene = function () {
  30141. return this._scene;
  30142. };
  30143. BaseTexture.prototype.getTextureMatrix = function () {
  30144. return BABYLON.Matrix.IdentityReadOnly;
  30145. };
  30146. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30147. return BABYLON.Matrix.IdentityReadOnly;
  30148. };
  30149. BaseTexture.prototype.getInternalTexture = function () {
  30150. return this._texture;
  30151. };
  30152. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30153. return !this.isBlocking || this.isReady();
  30154. };
  30155. BaseTexture.prototype.isReady = function () {
  30156. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30157. this.delayLoad();
  30158. return false;
  30159. }
  30160. if (this._texture) {
  30161. return this._texture.isReady;
  30162. }
  30163. return false;
  30164. };
  30165. BaseTexture.prototype.getSize = function () {
  30166. if (this._texture) {
  30167. if (this._texture.width) {
  30168. this._cachedSize.width = this._texture.width;
  30169. this._cachedSize.height = this._texture.height;
  30170. return this._cachedSize;
  30171. }
  30172. if (this._texture._size) {
  30173. this._cachedSize.width = this._texture._size;
  30174. this._cachedSize.height = this._texture._size;
  30175. return this._cachedSize;
  30176. }
  30177. }
  30178. return this._cachedSize;
  30179. };
  30180. BaseTexture.prototype.getBaseSize = function () {
  30181. if (!this.isReady() || !this._texture)
  30182. return BABYLON.Size.Zero();
  30183. if (this._texture._size) {
  30184. return new BABYLON.Size(this._texture._size, this._texture._size);
  30185. }
  30186. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30187. };
  30188. BaseTexture.prototype.scale = function (ratio) {
  30189. };
  30190. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30191. get: function () {
  30192. return false;
  30193. },
  30194. enumerable: true,
  30195. configurable: true
  30196. });
  30197. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30198. if (!this._scene) {
  30199. return null;
  30200. }
  30201. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30202. for (var index = 0; index < texturesCache.length; index++) {
  30203. var texturesCacheEntry = texturesCache[index];
  30204. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30205. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30206. texturesCacheEntry.incrementReferences();
  30207. return texturesCacheEntry;
  30208. }
  30209. }
  30210. }
  30211. return null;
  30212. };
  30213. BaseTexture.prototype._rebuild = function () {
  30214. };
  30215. BaseTexture.prototype.delayLoad = function () {
  30216. };
  30217. BaseTexture.prototype.clone = function () {
  30218. return null;
  30219. };
  30220. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30221. get: function () {
  30222. if (!this._texture) {
  30223. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30224. }
  30225. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30226. },
  30227. enumerable: true,
  30228. configurable: true
  30229. });
  30230. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30231. get: function () {
  30232. if (!this._texture) {
  30233. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30234. }
  30235. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30236. },
  30237. enumerable: true,
  30238. configurable: true
  30239. });
  30240. /**
  30241. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30242. * This will returns an RGBA array buffer containing either in values (0-255) or
  30243. * float values (0-1) depending of the underlying buffer type.
  30244. * @param faceIndex The face of the texture to read (in case of cube texture)
  30245. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30246. * @returns The Array buffer containing the pixels data.
  30247. */
  30248. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30249. if (faceIndex === void 0) { faceIndex = 0; }
  30250. if (level === void 0) { level = 0; }
  30251. if (!this._texture) {
  30252. return null;
  30253. }
  30254. var size = this.getSize();
  30255. var width = size.width;
  30256. var height = size.height;
  30257. var scene = this.getScene();
  30258. if (!scene) {
  30259. return null;
  30260. }
  30261. var engine = scene.getEngine();
  30262. if (level != 0) {
  30263. width = width / Math.pow(2, level);
  30264. height = height / Math.pow(2, level);
  30265. width = Math.round(width);
  30266. height = Math.round(height);
  30267. }
  30268. if (this._texture.isCube) {
  30269. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30270. }
  30271. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30272. };
  30273. BaseTexture.prototype.releaseInternalTexture = function () {
  30274. if (this._texture) {
  30275. this._texture.dispose();
  30276. this._texture = null;
  30277. }
  30278. };
  30279. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30280. get: function () {
  30281. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30282. return null;
  30283. }
  30284. if (!this._texture._sphericalPolynomial) {
  30285. this._texture._sphericalPolynomial =
  30286. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30287. }
  30288. return this._texture._sphericalPolynomial;
  30289. },
  30290. set: function (value) {
  30291. if (this._texture) {
  30292. this._texture._sphericalPolynomial = value;
  30293. }
  30294. },
  30295. enumerable: true,
  30296. configurable: true
  30297. });
  30298. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30299. get: function () {
  30300. if (this._texture) {
  30301. return this._texture._lodTextureHigh;
  30302. }
  30303. return null;
  30304. },
  30305. enumerable: true,
  30306. configurable: true
  30307. });
  30308. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30309. get: function () {
  30310. if (this._texture) {
  30311. return this._texture._lodTextureMid;
  30312. }
  30313. return null;
  30314. },
  30315. enumerable: true,
  30316. configurable: true
  30317. });
  30318. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30319. get: function () {
  30320. if (this._texture) {
  30321. return this._texture._lodTextureLow;
  30322. }
  30323. return null;
  30324. },
  30325. enumerable: true,
  30326. configurable: true
  30327. });
  30328. BaseTexture.prototype.dispose = function () {
  30329. if (!this._scene) {
  30330. return;
  30331. }
  30332. // Animations
  30333. this._scene.stopAnimation(this);
  30334. // Remove from scene
  30335. this._scene._removePendingData(this);
  30336. var index = this._scene.textures.indexOf(this);
  30337. if (index >= 0) {
  30338. this._scene.textures.splice(index, 1);
  30339. }
  30340. if (this._texture === undefined) {
  30341. return;
  30342. }
  30343. // Release
  30344. this.releaseInternalTexture();
  30345. // Callback
  30346. this.onDisposeObservable.notifyObservers(this);
  30347. this.onDisposeObservable.clear();
  30348. };
  30349. BaseTexture.prototype.serialize = function () {
  30350. if (!this.name) {
  30351. return null;
  30352. }
  30353. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30354. // Animations
  30355. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30356. return serializationObject;
  30357. };
  30358. BaseTexture.WhenAllReady = function (textures, callback) {
  30359. var numRemaining = textures.length;
  30360. if (numRemaining === 0) {
  30361. callback();
  30362. return;
  30363. }
  30364. var _loop_1 = function () {
  30365. texture = textures[i];
  30366. if (texture.isReady()) {
  30367. if (--numRemaining === 0) {
  30368. callback();
  30369. }
  30370. }
  30371. else {
  30372. onLoadObservable = texture.onLoadObservable;
  30373. var onLoadCallback_1 = function () {
  30374. onLoadObservable.removeCallback(onLoadCallback_1);
  30375. if (--numRemaining === 0) {
  30376. callback();
  30377. }
  30378. };
  30379. onLoadObservable.add(onLoadCallback_1);
  30380. }
  30381. };
  30382. var texture, onLoadObservable;
  30383. for (var i = 0; i < textures.length; i++) {
  30384. _loop_1();
  30385. }
  30386. };
  30387. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30388. __decorate([
  30389. BABYLON.serialize()
  30390. ], BaseTexture.prototype, "name", void 0);
  30391. __decorate([
  30392. BABYLON.serialize("hasAlpha")
  30393. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30394. __decorate([
  30395. BABYLON.serialize()
  30396. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30397. __decorate([
  30398. BABYLON.serialize()
  30399. ], BaseTexture.prototype, "level", void 0);
  30400. __decorate([
  30401. BABYLON.serialize()
  30402. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30403. __decorate([
  30404. BABYLON.serialize("coordinatesMode")
  30405. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30406. __decorate([
  30407. BABYLON.serialize()
  30408. ], BaseTexture.prototype, "wrapU", void 0);
  30409. __decorate([
  30410. BABYLON.serialize()
  30411. ], BaseTexture.prototype, "wrapV", void 0);
  30412. __decorate([
  30413. BABYLON.serialize()
  30414. ], BaseTexture.prototype, "wrapR", void 0);
  30415. __decorate([
  30416. BABYLON.serialize()
  30417. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30418. __decorate([
  30419. BABYLON.serialize()
  30420. ], BaseTexture.prototype, "isCube", void 0);
  30421. __decorate([
  30422. BABYLON.serialize()
  30423. ], BaseTexture.prototype, "is3D", void 0);
  30424. __decorate([
  30425. BABYLON.serialize()
  30426. ], BaseTexture.prototype, "gammaSpace", void 0);
  30427. __decorate([
  30428. BABYLON.serialize()
  30429. ], BaseTexture.prototype, "invertZ", void 0);
  30430. __decorate([
  30431. BABYLON.serialize()
  30432. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30433. __decorate([
  30434. BABYLON.serialize()
  30435. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30436. __decorate([
  30437. BABYLON.serialize()
  30438. ], BaseTexture.prototype, "lodGenerationScale", null);
  30439. __decorate([
  30440. BABYLON.serialize()
  30441. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30442. return BaseTexture;
  30443. }());
  30444. BABYLON.BaseTexture = BaseTexture;
  30445. })(BABYLON || (BABYLON = {}));
  30446. //# sourceMappingURL=babylon.baseTexture.js.map
  30447. var BABYLON;
  30448. (function (BABYLON) {
  30449. var Texture = /** @class */ (function (_super) {
  30450. __extends(Texture, _super);
  30451. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30452. if (noMipmap === void 0) { noMipmap = false; }
  30453. if (invertY === void 0) { invertY = true; }
  30454. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30455. if (onLoad === void 0) { onLoad = null; }
  30456. if (onError === void 0) { onError = null; }
  30457. if (buffer === void 0) { buffer = null; }
  30458. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30459. var _this = _super.call(this, scene) || this;
  30460. _this.uOffset = 0;
  30461. _this.vOffset = 0;
  30462. _this.uScale = 1.0;
  30463. _this.vScale = 1.0;
  30464. _this.uAng = 0;
  30465. _this.vAng = 0;
  30466. _this.wAng = 0;
  30467. /**
  30468. * Defines the center of rotation (U)
  30469. */
  30470. _this.uRotationCenter = 0.5;
  30471. /**
  30472. * Defines the center of rotation (V)
  30473. */
  30474. _this.vRotationCenter = 0.5;
  30475. /**
  30476. * Defines the center of rotation (W)
  30477. */
  30478. _this.wRotationCenter = 0.5;
  30479. _this._isBlocking = true;
  30480. _this.name = url || "";
  30481. _this.url = url;
  30482. _this._noMipmap = noMipmap;
  30483. _this._invertY = invertY;
  30484. _this._samplingMode = samplingMode;
  30485. _this._buffer = buffer;
  30486. _this._deleteBuffer = deleteBuffer;
  30487. if (format) {
  30488. _this._format = format;
  30489. }
  30490. scene = _this.getScene();
  30491. if (!scene) {
  30492. return _this;
  30493. }
  30494. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30495. var load = function () {
  30496. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30497. _this.onLoadObservable.notifyObservers(_this);
  30498. }
  30499. if (onLoad) {
  30500. onLoad();
  30501. }
  30502. if (!_this.isBlocking && scene) {
  30503. scene.resetCachedMaterial();
  30504. }
  30505. };
  30506. if (!_this.url) {
  30507. _this._delayedOnLoad = load;
  30508. _this._delayedOnError = onError;
  30509. return _this;
  30510. }
  30511. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30512. if (!_this._texture) {
  30513. if (!scene.useDelayedTextureLoading) {
  30514. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30515. if (deleteBuffer) {
  30516. delete _this._buffer;
  30517. }
  30518. }
  30519. else {
  30520. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30521. _this._delayedOnLoad = load;
  30522. _this._delayedOnError = onError;
  30523. }
  30524. }
  30525. else {
  30526. if (_this._texture.isReady) {
  30527. BABYLON.Tools.SetImmediate(function () { return load(); });
  30528. }
  30529. else {
  30530. _this._texture.onLoadedObservable.add(load);
  30531. }
  30532. }
  30533. return _this;
  30534. }
  30535. Object.defineProperty(Texture.prototype, "noMipmap", {
  30536. get: function () {
  30537. return this._noMipmap;
  30538. },
  30539. enumerable: true,
  30540. configurable: true
  30541. });
  30542. Object.defineProperty(Texture.prototype, "isBlocking", {
  30543. get: function () {
  30544. return this._isBlocking;
  30545. },
  30546. set: function (value) {
  30547. this._isBlocking = value;
  30548. },
  30549. enumerable: true,
  30550. configurable: true
  30551. });
  30552. Object.defineProperty(Texture.prototype, "samplingMode", {
  30553. get: function () {
  30554. return this._samplingMode;
  30555. },
  30556. enumerable: true,
  30557. configurable: true
  30558. });
  30559. /**
  30560. * Update the url (and optional buffer) of this texture if url was null during construction.
  30561. * @param url the url of the texture
  30562. * @param buffer the buffer of the texture (defaults to null)
  30563. */
  30564. Texture.prototype.updateURL = function (url, buffer) {
  30565. if (buffer === void 0) { buffer = null; }
  30566. if (this.url) {
  30567. throw new Error("URL is already set");
  30568. }
  30569. this.url = url;
  30570. this._buffer = buffer;
  30571. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30572. this.delayLoad();
  30573. };
  30574. Texture.prototype.delayLoad = function () {
  30575. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30576. return;
  30577. }
  30578. var scene = this.getScene();
  30579. if (!scene) {
  30580. return;
  30581. }
  30582. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30583. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30584. if (!this._texture) {
  30585. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30586. if (this._deleteBuffer) {
  30587. delete this._buffer;
  30588. }
  30589. }
  30590. else {
  30591. if (this._delayedOnLoad) {
  30592. if (this._texture.isReady) {
  30593. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30594. }
  30595. else {
  30596. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30597. }
  30598. }
  30599. }
  30600. this._delayedOnLoad = null;
  30601. this._delayedOnError = null;
  30602. };
  30603. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30604. if (!this._texture) {
  30605. return;
  30606. }
  30607. var scene = this.getScene();
  30608. if (!scene) {
  30609. return;
  30610. }
  30611. this._samplingMode = samplingMode;
  30612. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30613. };
  30614. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30615. x *= this.uScale;
  30616. y *= this.vScale;
  30617. x -= this.uRotationCenter * this.uScale;
  30618. y -= this.vRotationCenter * this.vScale;
  30619. z -= this.wRotationCenter;
  30620. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30621. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30622. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30623. t.z += this.wRotationCenter;
  30624. };
  30625. Texture.prototype.getTextureMatrix = function () {
  30626. var _this = this;
  30627. if (this.uOffset === this._cachedUOffset &&
  30628. this.vOffset === this._cachedVOffset &&
  30629. this.uScale === this._cachedUScale &&
  30630. this.vScale === this._cachedVScale &&
  30631. this.uAng === this._cachedUAng &&
  30632. this.vAng === this._cachedVAng &&
  30633. this.wAng === this._cachedWAng) {
  30634. return this._cachedTextureMatrix;
  30635. }
  30636. this._cachedUOffset = this.uOffset;
  30637. this._cachedVOffset = this.vOffset;
  30638. this._cachedUScale = this.uScale;
  30639. this._cachedVScale = this.vScale;
  30640. this._cachedUAng = this.uAng;
  30641. this._cachedVAng = this.vAng;
  30642. this._cachedWAng = this.wAng;
  30643. if (!this._cachedTextureMatrix) {
  30644. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30645. this._rowGenerationMatrix = new BABYLON.Matrix();
  30646. this._t0 = BABYLON.Vector3.Zero();
  30647. this._t1 = BABYLON.Vector3.Zero();
  30648. this._t2 = BABYLON.Vector3.Zero();
  30649. }
  30650. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30651. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30652. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30653. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30654. this._t1.subtractInPlace(this._t0);
  30655. this._t2.subtractInPlace(this._t0);
  30656. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30657. this._cachedTextureMatrix.m[0] = this._t1.x;
  30658. this._cachedTextureMatrix.m[1] = this._t1.y;
  30659. this._cachedTextureMatrix.m[2] = this._t1.z;
  30660. this._cachedTextureMatrix.m[4] = this._t2.x;
  30661. this._cachedTextureMatrix.m[5] = this._t2.y;
  30662. this._cachedTextureMatrix.m[6] = this._t2.z;
  30663. this._cachedTextureMatrix.m[8] = this._t0.x;
  30664. this._cachedTextureMatrix.m[9] = this._t0.y;
  30665. this._cachedTextureMatrix.m[10] = this._t0.z;
  30666. var scene = this.getScene();
  30667. if (!scene) {
  30668. return this._cachedTextureMatrix;
  30669. }
  30670. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30671. return mat.hasTexture(_this);
  30672. });
  30673. return this._cachedTextureMatrix;
  30674. };
  30675. Texture.prototype.getReflectionTextureMatrix = function () {
  30676. var _this = this;
  30677. var scene = this.getScene();
  30678. if (!scene) {
  30679. return this._cachedTextureMatrix;
  30680. }
  30681. if (this.uOffset === this._cachedUOffset &&
  30682. this.vOffset === this._cachedVOffset &&
  30683. this.uScale === this._cachedUScale &&
  30684. this.vScale === this._cachedVScale &&
  30685. this.coordinatesMode === this._cachedCoordinatesMode) {
  30686. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30687. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30688. return this._cachedTextureMatrix;
  30689. }
  30690. }
  30691. else {
  30692. return this._cachedTextureMatrix;
  30693. }
  30694. }
  30695. if (!this._cachedTextureMatrix) {
  30696. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30697. }
  30698. if (!this._projectionModeMatrix) {
  30699. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30700. }
  30701. this._cachedUOffset = this.uOffset;
  30702. this._cachedVOffset = this.vOffset;
  30703. this._cachedUScale = this.uScale;
  30704. this._cachedVScale = this.vScale;
  30705. this._cachedCoordinatesMode = this.coordinatesMode;
  30706. switch (this.coordinatesMode) {
  30707. case Texture.PLANAR_MODE:
  30708. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30709. this._cachedTextureMatrix[0] = this.uScale;
  30710. this._cachedTextureMatrix[5] = this.vScale;
  30711. this._cachedTextureMatrix[12] = this.uOffset;
  30712. this._cachedTextureMatrix[13] = this.vOffset;
  30713. break;
  30714. case Texture.PROJECTION_MODE:
  30715. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30716. this._projectionModeMatrix.m[0] = 0.5;
  30717. this._projectionModeMatrix.m[5] = -0.5;
  30718. this._projectionModeMatrix.m[10] = 0.0;
  30719. this._projectionModeMatrix.m[12] = 0.5;
  30720. this._projectionModeMatrix.m[13] = 0.5;
  30721. this._projectionModeMatrix.m[14] = 1.0;
  30722. this._projectionModeMatrix.m[15] = 1.0;
  30723. var projectionMatrix = scene.getProjectionMatrix();
  30724. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30725. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30726. break;
  30727. default:
  30728. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30729. break;
  30730. }
  30731. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30732. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30733. });
  30734. return this._cachedTextureMatrix;
  30735. };
  30736. Texture.prototype.clone = function () {
  30737. var _this = this;
  30738. return BABYLON.SerializationHelper.Clone(function () {
  30739. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30740. }, this);
  30741. };
  30742. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30743. get: function () {
  30744. if (!this._onLoadObservable) {
  30745. this._onLoadObservable = new BABYLON.Observable();
  30746. }
  30747. return this._onLoadObservable;
  30748. },
  30749. enumerable: true,
  30750. configurable: true
  30751. });
  30752. Texture.prototype.serialize = function () {
  30753. var serializationObject = _super.prototype.serialize.call(this);
  30754. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30755. serializationObject.base64String = this._buffer;
  30756. serializationObject.name = serializationObject.name.replace("data:", "");
  30757. }
  30758. serializationObject.invertY = this._invertY;
  30759. serializationObject.samplingMode = this.samplingMode;
  30760. return serializationObject;
  30761. };
  30762. Texture.prototype.getClassName = function () {
  30763. return "Texture";
  30764. };
  30765. Texture.prototype.dispose = function () {
  30766. _super.prototype.dispose.call(this);
  30767. if (this._onLoadObservable) {
  30768. this._onLoadObservable.clear();
  30769. this._onLoadObservable = null;
  30770. }
  30771. this._delayedOnLoad = null;
  30772. this._delayedOnError = null;
  30773. };
  30774. // Statics
  30775. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30776. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30777. if (onLoad === void 0) { onLoad = null; }
  30778. if (onError === void 0) { onError = null; }
  30779. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30780. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30781. };
  30782. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30783. if (parsedTexture.customType) {
  30784. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30785. // Update Sampling Mode
  30786. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30787. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30788. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30789. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30790. }
  30791. }
  30792. return parsedCustomTexture;
  30793. }
  30794. if (parsedTexture.isCube) {
  30795. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30796. }
  30797. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30798. return null;
  30799. }
  30800. var texture = BABYLON.SerializationHelper.Parse(function () {
  30801. var generateMipMaps = true;
  30802. if (parsedTexture.noMipmap) {
  30803. generateMipMaps = false;
  30804. }
  30805. if (parsedTexture.mirrorPlane) {
  30806. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30807. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30808. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30809. return mirrorTexture;
  30810. }
  30811. else if (parsedTexture.isRenderTarget) {
  30812. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30813. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30814. return renderTargetTexture;
  30815. }
  30816. else {
  30817. var texture;
  30818. if (parsedTexture.base64String) {
  30819. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30820. }
  30821. else {
  30822. var url = rootUrl + parsedTexture.name;
  30823. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30824. url = parsedTexture.url;
  30825. }
  30826. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30827. }
  30828. return texture;
  30829. }
  30830. }, parsedTexture, scene);
  30831. // Update Sampling Mode
  30832. if (parsedTexture.samplingMode) {
  30833. var sampling = parsedTexture.samplingMode;
  30834. if (texture._samplingMode !== sampling) {
  30835. texture.updateSamplingMode(sampling);
  30836. }
  30837. }
  30838. // Animations
  30839. if (parsedTexture.animations) {
  30840. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30841. var parsedAnimation = parsedTexture.animations[animationIndex];
  30842. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30843. }
  30844. }
  30845. return texture;
  30846. };
  30847. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30848. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30849. if (noMipmap === void 0) { noMipmap = false; }
  30850. if (invertY === void 0) { invertY = true; }
  30851. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30852. if (onLoad === void 0) { onLoad = null; }
  30853. if (onError === void 0) { onError = null; }
  30854. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30855. if (name.substr(0, 5) !== "data:") {
  30856. name = "data:" + name;
  30857. }
  30858. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30859. };
  30860. // Constants
  30861. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30862. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30863. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30864. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30865. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30866. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30867. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30868. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30869. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30870. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30871. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30872. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30873. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30874. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30875. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30876. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30877. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30878. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30879. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30880. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30881. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30882. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30883. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30884. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30885. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30886. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30887. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30888. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30889. /**
  30890. * 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
  30891. */
  30892. Texture.UseSerializedUrlIfAny = false;
  30893. __decorate([
  30894. BABYLON.serialize()
  30895. ], Texture.prototype, "url", void 0);
  30896. __decorate([
  30897. BABYLON.serialize()
  30898. ], Texture.prototype, "uOffset", void 0);
  30899. __decorate([
  30900. BABYLON.serialize()
  30901. ], Texture.prototype, "vOffset", void 0);
  30902. __decorate([
  30903. BABYLON.serialize()
  30904. ], Texture.prototype, "uScale", void 0);
  30905. __decorate([
  30906. BABYLON.serialize()
  30907. ], Texture.prototype, "vScale", void 0);
  30908. __decorate([
  30909. BABYLON.serialize()
  30910. ], Texture.prototype, "uAng", void 0);
  30911. __decorate([
  30912. BABYLON.serialize()
  30913. ], Texture.prototype, "vAng", void 0);
  30914. __decorate([
  30915. BABYLON.serialize()
  30916. ], Texture.prototype, "wAng", void 0);
  30917. __decorate([
  30918. BABYLON.serialize()
  30919. ], Texture.prototype, "uRotationCenter", void 0);
  30920. __decorate([
  30921. BABYLON.serialize()
  30922. ], Texture.prototype, "vRotationCenter", void 0);
  30923. __decorate([
  30924. BABYLON.serialize()
  30925. ], Texture.prototype, "wRotationCenter", void 0);
  30926. __decorate([
  30927. BABYLON.serialize()
  30928. ], Texture.prototype, "isBlocking", null);
  30929. return Texture;
  30930. }(BABYLON.BaseTexture));
  30931. BABYLON.Texture = Texture;
  30932. })(BABYLON || (BABYLON = {}));
  30933. //# sourceMappingURL=babylon.texture.js.map
  30934. var BABYLON;
  30935. (function (BABYLON) {
  30936. /**
  30937. * @hidden
  30938. **/
  30939. var _InstancesBatch = /** @class */ (function () {
  30940. function _InstancesBatch() {
  30941. this.mustReturn = false;
  30942. this.visibleInstances = new Array();
  30943. this.renderSelf = new Array();
  30944. }
  30945. return _InstancesBatch;
  30946. }());
  30947. BABYLON._InstancesBatch = _InstancesBatch;
  30948. var Mesh = /** @class */ (function (_super) {
  30949. __extends(Mesh, _super);
  30950. /**
  30951. * @constructor
  30952. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30953. * @param {Scene} scene The scene to add this mesh to.
  30954. * @param {Node} parent The parent of this mesh, if it has one
  30955. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30956. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30957. * When false, achieved by calling a clone(), also passing False.
  30958. * This will make creation of children, recursive.
  30959. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30960. */
  30961. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30962. if (scene === void 0) { scene = null; }
  30963. if (parent === void 0) { parent = null; }
  30964. if (source === void 0) { source = null; }
  30965. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30966. var _this = _super.call(this, name, scene) || this;
  30967. // Members
  30968. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30969. _this.instances = new Array();
  30970. _this._LODLevels = new Array();
  30971. _this._visibleInstances = {};
  30972. _this._renderIdForInstances = new Array();
  30973. _this._batchCache = new _InstancesBatch();
  30974. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30975. // Use by builder only to know what orientation were the mesh build in.
  30976. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30977. _this.overrideMaterialSideOrientation = null;
  30978. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30979. // Will be used to save a source mesh reference, If any
  30980. _this._source = null;
  30981. scene = _this.getScene();
  30982. if (source) {
  30983. // Geometry
  30984. if (source._geometry) {
  30985. source._geometry.applyToMesh(_this);
  30986. }
  30987. // Deep copy
  30988. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30989. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30990. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30991. ], ["_poseMatrix"]);
  30992. // Source mesh
  30993. _this._source = source;
  30994. // Metadata
  30995. if (source.metadata && source.metadata.clone) {
  30996. _this.metadata = source.metadata.clone();
  30997. }
  30998. else {
  30999. _this.metadata = source.metadata;
  31000. }
  31001. // Tags
  31002. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31003. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31004. }
  31005. // Parent
  31006. _this.parent = source.parent;
  31007. // Pivot
  31008. _this.setPivotMatrix(source.getPivotMatrix());
  31009. _this.id = name + "." + source.id;
  31010. // Material
  31011. _this.material = source.material;
  31012. var index;
  31013. if (!doNotCloneChildren) {
  31014. // Children
  31015. var directDescendants = source.getDescendants(true);
  31016. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31017. var child = directDescendants[index_1];
  31018. if (child.clone) {
  31019. child.clone(name + "." + child.name, _this);
  31020. }
  31021. }
  31022. }
  31023. // Physics clone
  31024. var physicsEngine = _this.getScene().getPhysicsEngine();
  31025. if (clonePhysicsImpostor && physicsEngine) {
  31026. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31027. if (impostor) {
  31028. _this.physicsImpostor = impostor.clone(_this);
  31029. }
  31030. }
  31031. // Particles
  31032. for (index = 0; index < scene.particleSystems.length; index++) {
  31033. var system = scene.particleSystems[index];
  31034. if (system.emitter === source) {
  31035. system.clone(system.name, _this);
  31036. }
  31037. }
  31038. _this.refreshBoundingInfo();
  31039. _this.computeWorldMatrix(true);
  31040. }
  31041. // Parent
  31042. if (parent !== null) {
  31043. _this.parent = parent;
  31044. }
  31045. return _this;
  31046. }
  31047. Object.defineProperty(Mesh, "FRONTSIDE", {
  31048. /**
  31049. * Mesh side orientation : usually the external or front surface
  31050. */
  31051. get: function () {
  31052. return Mesh._FRONTSIDE;
  31053. },
  31054. enumerable: true,
  31055. configurable: true
  31056. });
  31057. Object.defineProperty(Mesh, "BACKSIDE", {
  31058. /**
  31059. * Mesh side orientation : usually the internal or back surface
  31060. */
  31061. get: function () {
  31062. return Mesh._BACKSIDE;
  31063. },
  31064. enumerable: true,
  31065. configurable: true
  31066. });
  31067. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31068. /**
  31069. * Mesh side orientation : both internal and external or front and back surfaces
  31070. */
  31071. get: function () {
  31072. return Mesh._DOUBLESIDE;
  31073. },
  31074. enumerable: true,
  31075. configurable: true
  31076. });
  31077. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31078. /**
  31079. * Mesh side orientation : by default, `FRONTSIDE`
  31080. */
  31081. get: function () {
  31082. return Mesh._DEFAULTSIDE;
  31083. },
  31084. enumerable: true,
  31085. configurable: true
  31086. });
  31087. Object.defineProperty(Mesh, "NO_CAP", {
  31088. /**
  31089. * Mesh cap setting : no cap
  31090. */
  31091. get: function () {
  31092. return Mesh._NO_CAP;
  31093. },
  31094. enumerable: true,
  31095. configurable: true
  31096. });
  31097. Object.defineProperty(Mesh, "CAP_START", {
  31098. /**
  31099. * Mesh cap setting : one cap at the beginning of the mesh
  31100. */
  31101. get: function () {
  31102. return Mesh._CAP_START;
  31103. },
  31104. enumerable: true,
  31105. configurable: true
  31106. });
  31107. Object.defineProperty(Mesh, "CAP_END", {
  31108. /**
  31109. * Mesh cap setting : one cap at the end of the mesh
  31110. */
  31111. get: function () {
  31112. return Mesh._CAP_END;
  31113. },
  31114. enumerable: true,
  31115. configurable: true
  31116. });
  31117. Object.defineProperty(Mesh, "CAP_ALL", {
  31118. /**
  31119. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31120. */
  31121. get: function () {
  31122. return Mesh._CAP_ALL;
  31123. },
  31124. enumerable: true,
  31125. configurable: true
  31126. });
  31127. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31128. /**
  31129. * An event triggered before rendering the mesh
  31130. */
  31131. get: function () {
  31132. if (!this._onBeforeRenderObservable) {
  31133. this._onBeforeRenderObservable = new BABYLON.Observable();
  31134. }
  31135. return this._onBeforeRenderObservable;
  31136. },
  31137. enumerable: true,
  31138. configurable: true
  31139. });
  31140. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31141. /**
  31142. * An event triggered after rendering the mesh
  31143. */
  31144. get: function () {
  31145. if (!this._onAfterRenderObservable) {
  31146. this._onAfterRenderObservable = new BABYLON.Observable();
  31147. }
  31148. return this._onAfterRenderObservable;
  31149. },
  31150. enumerable: true,
  31151. configurable: true
  31152. });
  31153. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31154. /**
  31155. * An event triggered before drawing the mesh
  31156. */
  31157. get: function () {
  31158. if (!this._onBeforeDrawObservable) {
  31159. this._onBeforeDrawObservable = new BABYLON.Observable();
  31160. }
  31161. return this._onBeforeDrawObservable;
  31162. },
  31163. enumerable: true,
  31164. configurable: true
  31165. });
  31166. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31167. set: function (callback) {
  31168. if (this._onBeforeDrawObserver) {
  31169. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31170. }
  31171. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31172. },
  31173. enumerable: true,
  31174. configurable: true
  31175. });
  31176. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31177. get: function () {
  31178. return this._morphTargetManager;
  31179. },
  31180. set: function (value) {
  31181. if (this._morphTargetManager === value) {
  31182. return;
  31183. }
  31184. this._morphTargetManager = value;
  31185. this._syncGeometryWithMorphTargetManager();
  31186. },
  31187. enumerable: true,
  31188. configurable: true
  31189. });
  31190. Object.defineProperty(Mesh.prototype, "source", {
  31191. get: function () {
  31192. return this._source;
  31193. },
  31194. enumerable: true,
  31195. configurable: true
  31196. });
  31197. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31198. get: function () {
  31199. return this._unIndexed;
  31200. },
  31201. set: function (value) {
  31202. if (this._unIndexed !== value) {
  31203. this._unIndexed = value;
  31204. this._markSubMeshesAsAttributesDirty();
  31205. }
  31206. },
  31207. enumerable: true,
  31208. configurable: true
  31209. });
  31210. // Methods
  31211. /**
  31212. * Returns the string "Mesh".
  31213. */
  31214. Mesh.prototype.getClassName = function () {
  31215. return "Mesh";
  31216. };
  31217. /**
  31218. * Returns a string.
  31219. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31220. */
  31221. Mesh.prototype.toString = function (fullDetails) {
  31222. var ret = _super.prototype.toString.call(this, fullDetails);
  31223. ret += ", n vertices: " + this.getTotalVertices();
  31224. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31225. if (this.animations) {
  31226. for (var i = 0; i < this.animations.length; i++) {
  31227. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31228. }
  31229. }
  31230. if (fullDetails) {
  31231. if (this._geometry) {
  31232. var ib = this.getIndices();
  31233. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31234. if (vb && ib) {
  31235. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31236. }
  31237. }
  31238. else {
  31239. ret += ", flat shading: UNKNOWN";
  31240. }
  31241. }
  31242. return ret;
  31243. };
  31244. Mesh.prototype._unBindEffect = function () {
  31245. _super.prototype._unBindEffect.call(this);
  31246. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31247. var instance = _a[_i];
  31248. instance._unBindEffect();
  31249. }
  31250. };
  31251. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31252. /**
  31253. * True if the mesh has some Levels Of Details (LOD).
  31254. * Returns a boolean.
  31255. */
  31256. get: function () {
  31257. return this._LODLevels.length > 0;
  31258. },
  31259. enumerable: true,
  31260. configurable: true
  31261. });
  31262. /**
  31263. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31264. * @returns an array of {BABYLON.MeshLODLevel}
  31265. */
  31266. Mesh.prototype.getLODLevels = function () {
  31267. return this._LODLevels;
  31268. };
  31269. Mesh.prototype._sortLODLevels = function () {
  31270. this._LODLevels.sort(function (a, b) {
  31271. if (a.distance < b.distance) {
  31272. return 1;
  31273. }
  31274. if (a.distance > b.distance) {
  31275. return -1;
  31276. }
  31277. return 0;
  31278. });
  31279. };
  31280. /**
  31281. * Add a mesh as LOD level triggered at the given distance.
  31282. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31283. * @param distance The distance from the center of the object to show this level
  31284. * @param mesh The mesh to be added as LOD level (can be null)
  31285. * @return This mesh (for chaining)
  31286. */
  31287. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31288. if (mesh && mesh._masterMesh) {
  31289. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31290. return this;
  31291. }
  31292. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31293. this._LODLevels.push(level);
  31294. if (mesh) {
  31295. mesh._masterMesh = this;
  31296. }
  31297. this._sortLODLevels();
  31298. return this;
  31299. };
  31300. /**
  31301. * Returns the LOD level mesh at the passed distance or null if not found.
  31302. * It is related to the method `addLODLevel(distance, mesh)`.
  31303. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31304. * Returns an object Mesh or `null`.
  31305. */
  31306. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31307. for (var index = 0; index < this._LODLevels.length; index++) {
  31308. var level = this._LODLevels[index];
  31309. if (level.distance === distance) {
  31310. return level.mesh;
  31311. }
  31312. }
  31313. return null;
  31314. };
  31315. /**
  31316. * Remove a mesh from the LOD array
  31317. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31318. * @param {Mesh} mesh The mesh to be removed.
  31319. * @return {Mesh} This mesh (for chaining)
  31320. */
  31321. Mesh.prototype.removeLODLevel = function (mesh) {
  31322. for (var index = 0; index < this._LODLevels.length; index++) {
  31323. if (this._LODLevels[index].mesh === mesh) {
  31324. this._LODLevels.splice(index, 1);
  31325. if (mesh) {
  31326. mesh._masterMesh = null;
  31327. }
  31328. }
  31329. }
  31330. this._sortLODLevels();
  31331. return this;
  31332. };
  31333. /**
  31334. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31335. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31336. */
  31337. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31338. if (!this._LODLevels || this._LODLevels.length === 0) {
  31339. return this;
  31340. }
  31341. var bSphere;
  31342. if (boundingSphere) {
  31343. bSphere = boundingSphere;
  31344. }
  31345. else {
  31346. var boundingInfo = this.getBoundingInfo();
  31347. bSphere = boundingInfo.boundingSphere;
  31348. }
  31349. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31350. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31351. if (this.onLODLevelSelection) {
  31352. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31353. }
  31354. return this;
  31355. }
  31356. for (var index = 0; index < this._LODLevels.length; index++) {
  31357. var level = this._LODLevels[index];
  31358. if (level.distance < distanceToCamera) {
  31359. if (level.mesh) {
  31360. level.mesh._preActivate();
  31361. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31362. }
  31363. if (this.onLODLevelSelection) {
  31364. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31365. }
  31366. return level.mesh;
  31367. }
  31368. }
  31369. if (this.onLODLevelSelection) {
  31370. this.onLODLevelSelection(distanceToCamera, this, this);
  31371. }
  31372. return this;
  31373. };
  31374. Object.defineProperty(Mesh.prototype, "geometry", {
  31375. /**
  31376. * Returns the mesh internal Geometry object.
  31377. */
  31378. get: function () {
  31379. return this._geometry;
  31380. },
  31381. enumerable: true,
  31382. configurable: true
  31383. });
  31384. /**
  31385. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31386. */
  31387. Mesh.prototype.getTotalVertices = function () {
  31388. if (this._geometry === null || this._geometry === undefined) {
  31389. return 0;
  31390. }
  31391. return this._geometry.getTotalVertices();
  31392. };
  31393. /**
  31394. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31395. * 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.
  31396. * You can force the copy with forceCopy === true
  31397. * Returns null if the mesh has no geometry or no vertex buffer.
  31398. * Possible `kind` values :
  31399. * - BABYLON.VertexBuffer.PositionKind
  31400. * - BABYLON.VertexBuffer.UVKind
  31401. * - BABYLON.VertexBuffer.UV2Kind
  31402. * - BABYLON.VertexBuffer.UV3Kind
  31403. * - BABYLON.VertexBuffer.UV4Kind
  31404. * - BABYLON.VertexBuffer.UV5Kind
  31405. * - BABYLON.VertexBuffer.UV6Kind
  31406. * - BABYLON.VertexBuffer.ColorKind
  31407. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31408. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31409. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31410. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31411. */
  31412. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31413. if (!this._geometry) {
  31414. return null;
  31415. }
  31416. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31417. };
  31418. /**
  31419. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31420. * Returns `null` if the mesh has no geometry.
  31421. * Possible `kind` values :
  31422. * - BABYLON.VertexBuffer.PositionKind
  31423. * - BABYLON.VertexBuffer.UVKind
  31424. * - BABYLON.VertexBuffer.UV2Kind
  31425. * - BABYLON.VertexBuffer.UV3Kind
  31426. * - BABYLON.VertexBuffer.UV4Kind
  31427. * - BABYLON.VertexBuffer.UV5Kind
  31428. * - BABYLON.VertexBuffer.UV6Kind
  31429. * - BABYLON.VertexBuffer.ColorKind
  31430. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31431. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31432. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31433. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31434. */
  31435. Mesh.prototype.getVertexBuffer = function (kind) {
  31436. if (!this._geometry) {
  31437. return null;
  31438. }
  31439. return this._geometry.getVertexBuffer(kind);
  31440. };
  31441. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31442. if (!this._geometry) {
  31443. if (this._delayInfo) {
  31444. return this._delayInfo.indexOf(kind) !== -1;
  31445. }
  31446. return false;
  31447. }
  31448. return this._geometry.isVerticesDataPresent(kind);
  31449. };
  31450. /**
  31451. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31452. * Possible `kind` values :
  31453. * - BABYLON.VertexBuffer.PositionKind
  31454. * - BABYLON.VertexBuffer.UVKind
  31455. * - BABYLON.VertexBuffer.UV2Kind
  31456. * - BABYLON.VertexBuffer.UV3Kind
  31457. * - BABYLON.VertexBuffer.UV4Kind
  31458. * - BABYLON.VertexBuffer.UV5Kind
  31459. * - BABYLON.VertexBuffer.UV6Kind
  31460. * - BABYLON.VertexBuffer.ColorKind
  31461. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31462. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31463. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31464. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31465. */
  31466. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31467. if (!this._geometry) {
  31468. if (this._delayInfo) {
  31469. return this._delayInfo.indexOf(kind) !== -1;
  31470. }
  31471. return false;
  31472. }
  31473. return this._geometry.isVertexBufferUpdatable(kind);
  31474. };
  31475. /**
  31476. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31477. * Possible `kind` values :
  31478. * - BABYLON.VertexBuffer.PositionKind
  31479. * - BABYLON.VertexBuffer.UVKind
  31480. * - BABYLON.VertexBuffer.UV2Kind
  31481. * - BABYLON.VertexBuffer.UV3Kind
  31482. * - BABYLON.VertexBuffer.UV4Kind
  31483. * - BABYLON.VertexBuffer.UV5Kind
  31484. * - BABYLON.VertexBuffer.UV6Kind
  31485. * - BABYLON.VertexBuffer.ColorKind
  31486. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31487. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31488. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31489. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31490. */
  31491. Mesh.prototype.getVerticesDataKinds = function () {
  31492. if (!this._geometry) {
  31493. var result = new Array();
  31494. if (this._delayInfo) {
  31495. this._delayInfo.forEach(function (kind, index, array) {
  31496. result.push(kind);
  31497. });
  31498. }
  31499. return result;
  31500. }
  31501. return this._geometry.getVerticesDataKinds();
  31502. };
  31503. /**
  31504. * Returns a positive integer : the total number of indices in this mesh geometry.
  31505. * Returns zero if the mesh has no geometry.
  31506. */
  31507. Mesh.prototype.getTotalIndices = function () {
  31508. if (!this._geometry) {
  31509. return 0;
  31510. }
  31511. return this._geometry.getTotalIndices();
  31512. };
  31513. /**
  31514. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31515. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31516. * Returns an empty array if the mesh has no geometry.
  31517. */
  31518. Mesh.prototype.getIndices = function (copyWhenShared) {
  31519. if (!this._geometry) {
  31520. return [];
  31521. }
  31522. return this._geometry.getIndices(copyWhenShared);
  31523. };
  31524. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31525. get: function () {
  31526. return this._masterMesh !== null && this._masterMesh !== undefined;
  31527. },
  31528. enumerable: true,
  31529. configurable: true
  31530. });
  31531. /**
  31532. * Determine if the current mesh is ready to be rendered
  31533. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31534. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31535. * @returns true if all associated assets are ready (material, textures, shaders)
  31536. */
  31537. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31538. if (completeCheck === void 0) { completeCheck = false; }
  31539. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31540. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31541. return false;
  31542. }
  31543. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31544. return false;
  31545. }
  31546. if (!this.subMeshes || this.subMeshes.length === 0) {
  31547. return true;
  31548. }
  31549. if (!completeCheck) {
  31550. return true;
  31551. }
  31552. var engine = this.getEngine();
  31553. var scene = this.getScene();
  31554. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31555. this.computeWorldMatrix();
  31556. var mat = this.material || scene.defaultMaterial;
  31557. if (mat) {
  31558. if (mat.storeEffectOnSubMeshes) {
  31559. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31560. var subMesh = _a[_i];
  31561. var effectiveMaterial = subMesh.getMaterial();
  31562. if (effectiveMaterial) {
  31563. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31564. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31565. return false;
  31566. }
  31567. }
  31568. else {
  31569. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31570. return false;
  31571. }
  31572. }
  31573. }
  31574. }
  31575. }
  31576. else {
  31577. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31578. return false;
  31579. }
  31580. }
  31581. }
  31582. // Shadows
  31583. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31584. var light = _c[_b];
  31585. var generator = light.getShadowGenerator();
  31586. if (generator) {
  31587. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31588. var subMesh = _e[_d];
  31589. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31590. return false;
  31591. }
  31592. }
  31593. }
  31594. }
  31595. // LOD
  31596. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31597. var lod = _g[_f];
  31598. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31599. return false;
  31600. }
  31601. }
  31602. return true;
  31603. };
  31604. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31605. /**
  31606. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31607. * This property is pertinent only for updatable parametric shapes.
  31608. */
  31609. get: function () {
  31610. return this._areNormalsFrozen;
  31611. },
  31612. enumerable: true,
  31613. configurable: true
  31614. });
  31615. /**
  31616. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31617. * It has no effect at all on other shapes.
  31618. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31619. * Returns the Mesh.
  31620. */
  31621. Mesh.prototype.freezeNormals = function () {
  31622. this._areNormalsFrozen = true;
  31623. return this;
  31624. };
  31625. /**
  31626. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31627. * It has no effect at all on other shapes.
  31628. * It reactivates the mesh normals computation if it was previously frozen.
  31629. * Returns the Mesh.
  31630. */
  31631. Mesh.prototype.unfreezeNormals = function () {
  31632. this._areNormalsFrozen = false;
  31633. return this;
  31634. };
  31635. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31636. /**
  31637. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31638. */
  31639. set: function (count) {
  31640. this._overridenInstanceCount = count;
  31641. },
  31642. enumerable: true,
  31643. configurable: true
  31644. });
  31645. // Methods
  31646. Mesh.prototype._preActivate = function () {
  31647. var sceneRenderId = this.getScene().getRenderId();
  31648. if (this._preActivateId === sceneRenderId) {
  31649. return this;
  31650. }
  31651. this._preActivateId = sceneRenderId;
  31652. this._visibleInstances = null;
  31653. return this;
  31654. };
  31655. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31656. if (this._visibleInstances) {
  31657. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31658. }
  31659. return this;
  31660. };
  31661. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31662. if (!this._visibleInstances) {
  31663. this._visibleInstances = {};
  31664. this._visibleInstances.defaultRenderId = renderId;
  31665. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31666. }
  31667. if (!this._visibleInstances[renderId]) {
  31668. this._visibleInstances[renderId] = new Array();
  31669. }
  31670. this._visibleInstances[renderId].push(instance);
  31671. return this;
  31672. };
  31673. /**
  31674. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31675. * This means the mesh underlying bounding box and sphere are recomputed.
  31676. * Returns the Mesh.
  31677. */
  31678. Mesh.prototype.refreshBoundingInfo = function () {
  31679. return this._refreshBoundingInfo(false);
  31680. };
  31681. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31682. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31683. return this;
  31684. }
  31685. var data = this._getPositionData(applySkeleton);
  31686. if (data) {
  31687. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31688. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31689. }
  31690. if (this.subMeshes) {
  31691. for (var index = 0; index < this.subMeshes.length; index++) {
  31692. this.subMeshes[index].refreshBoundingInfo();
  31693. }
  31694. }
  31695. this._updateBoundingInfo();
  31696. return this;
  31697. };
  31698. Mesh.prototype._getPositionData = function (applySkeleton) {
  31699. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31700. if (data && applySkeleton && this.skeleton) {
  31701. data = BABYLON.Tools.Slice(data);
  31702. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31703. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31704. if (matricesWeightsData && matricesIndicesData) {
  31705. var needExtras = this.numBoneInfluencers > 4;
  31706. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31707. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31708. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31709. var tempVector = BABYLON.Tmp.Vector3[0];
  31710. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31711. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31712. var matWeightIdx = 0;
  31713. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31714. finalMatrix.reset();
  31715. var inf;
  31716. var weight;
  31717. for (inf = 0; inf < 4; inf++) {
  31718. weight = matricesWeightsData[matWeightIdx + inf];
  31719. if (weight > 0) {
  31720. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31721. finalMatrix.addToSelf(tempMatrix);
  31722. }
  31723. }
  31724. if (needExtras) {
  31725. for (inf = 0; inf < 4; inf++) {
  31726. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31727. if (weight > 0) {
  31728. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31729. finalMatrix.addToSelf(tempMatrix);
  31730. }
  31731. }
  31732. }
  31733. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31734. tempVector.toArray(data, index);
  31735. }
  31736. }
  31737. }
  31738. return data;
  31739. };
  31740. Mesh.prototype._createGlobalSubMesh = function (force) {
  31741. var totalVertices = this.getTotalVertices();
  31742. if (!totalVertices || !this.getIndices()) {
  31743. return null;
  31744. }
  31745. // Check if we need to recreate the submeshes
  31746. if (this.subMeshes && this.subMeshes.length > 0) {
  31747. var ib = this.getIndices();
  31748. if (!ib) {
  31749. return null;
  31750. }
  31751. var totalIndices = ib.length;
  31752. var needToRecreate = false;
  31753. if (force) {
  31754. needToRecreate = true;
  31755. }
  31756. else {
  31757. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31758. var submesh = _a[_i];
  31759. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31760. needToRecreate = true;
  31761. break;
  31762. }
  31763. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31764. needToRecreate = true;
  31765. break;
  31766. }
  31767. }
  31768. }
  31769. if (!needToRecreate) {
  31770. return this.subMeshes[0];
  31771. }
  31772. }
  31773. this.releaseSubMeshes();
  31774. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31775. };
  31776. Mesh.prototype.subdivide = function (count) {
  31777. if (count < 1) {
  31778. return;
  31779. }
  31780. var totalIndices = this.getTotalIndices();
  31781. var subdivisionSize = (totalIndices / count) | 0;
  31782. var offset = 0;
  31783. // Ensure that subdivisionSize is a multiple of 3
  31784. while (subdivisionSize % 3 !== 0) {
  31785. subdivisionSize++;
  31786. }
  31787. this.releaseSubMeshes();
  31788. for (var index = 0; index < count; index++) {
  31789. if (offset >= totalIndices) {
  31790. break;
  31791. }
  31792. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31793. offset += subdivisionSize;
  31794. }
  31795. this.synchronizeInstances();
  31796. };
  31797. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31798. if (updatable === void 0) { updatable = false; }
  31799. if (!this._geometry) {
  31800. var vertexData = new BABYLON.VertexData();
  31801. vertexData.set(data, kind);
  31802. var scene = this.getScene();
  31803. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31804. }
  31805. else {
  31806. this._geometry.setVerticesData(kind, data, updatable, stride);
  31807. }
  31808. return this;
  31809. };
  31810. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31811. if (updatable === void 0) { updatable = true; }
  31812. var vb = this.getVertexBuffer(kind);
  31813. if (!vb || vb.isUpdatable() === updatable) {
  31814. return;
  31815. }
  31816. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31817. };
  31818. /**
  31819. * Sets the mesh VertexBuffer.
  31820. * Returns the Mesh.
  31821. */
  31822. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31823. if (!this._geometry) {
  31824. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31825. }
  31826. this._geometry.setVerticesBuffer(buffer);
  31827. return this;
  31828. };
  31829. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31830. if (!this._geometry) {
  31831. return this;
  31832. }
  31833. if (!makeItUnique) {
  31834. this._geometry.updateVerticesData(kind, data, updateExtends);
  31835. }
  31836. else {
  31837. this.makeGeometryUnique();
  31838. this.updateVerticesData(kind, data, updateExtends, false);
  31839. }
  31840. return this;
  31841. };
  31842. /**
  31843. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31844. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31845. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31846. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31847. * Returns the Mesh.
  31848. */
  31849. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31850. if (computeNormals === void 0) { computeNormals = true; }
  31851. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31852. if (!positions) {
  31853. return this;
  31854. }
  31855. positionFunction(positions);
  31856. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31857. if (computeNormals) {
  31858. var indices = this.getIndices();
  31859. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31860. if (!normals) {
  31861. return this;
  31862. }
  31863. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31864. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31865. }
  31866. return this;
  31867. };
  31868. /**
  31869. * Creates a un-shared specific occurence of the geometry for the mesh.
  31870. * Returns the Mesh.
  31871. */
  31872. Mesh.prototype.makeGeometryUnique = function () {
  31873. if (!this._geometry) {
  31874. return this;
  31875. }
  31876. var oldGeometry = this._geometry;
  31877. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31878. oldGeometry.releaseForMesh(this, true);
  31879. geometry.applyToMesh(this);
  31880. return this;
  31881. };
  31882. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31883. if (totalVertices === void 0) { totalVertices = null; }
  31884. if (updatable === void 0) { updatable = false; }
  31885. if (!this._geometry) {
  31886. var vertexData = new BABYLON.VertexData();
  31887. vertexData.indices = indices;
  31888. var scene = this.getScene();
  31889. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31890. }
  31891. else {
  31892. this._geometry.setIndices(indices, totalVertices, updatable);
  31893. }
  31894. return this;
  31895. };
  31896. /**
  31897. * Update the current index buffer
  31898. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31899. * Returns the Mesh.
  31900. */
  31901. Mesh.prototype.updateIndices = function (indices, offset) {
  31902. if (!this._geometry) {
  31903. return this;
  31904. }
  31905. this._geometry.updateIndices(indices, offset);
  31906. return this;
  31907. };
  31908. /**
  31909. * Invert the geometry to move from a right handed system to a left handed one.
  31910. * Returns the Mesh.
  31911. */
  31912. Mesh.prototype.toLeftHanded = function () {
  31913. if (!this._geometry) {
  31914. return this;
  31915. }
  31916. this._geometry.toLeftHanded();
  31917. return this;
  31918. };
  31919. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31920. if (!this._geometry) {
  31921. return this;
  31922. }
  31923. var engine = this.getScene().getEngine();
  31924. // Wireframe
  31925. var indexToBind;
  31926. if (this._unIndexed) {
  31927. indexToBind = null;
  31928. }
  31929. else {
  31930. switch (fillMode) {
  31931. case BABYLON.Material.PointFillMode:
  31932. indexToBind = null;
  31933. break;
  31934. case BABYLON.Material.WireFrameFillMode:
  31935. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31936. break;
  31937. default:
  31938. case BABYLON.Material.TriangleFillMode:
  31939. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31940. break;
  31941. }
  31942. }
  31943. // VBOs
  31944. this._geometry._bind(effect, indexToBind);
  31945. return this;
  31946. };
  31947. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31948. if (alternate === void 0) { alternate = false; }
  31949. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31950. return this;
  31951. }
  31952. if (this._onBeforeDrawObservable) {
  31953. this._onBeforeDrawObservable.notifyObservers(this);
  31954. }
  31955. var scene = this.getScene();
  31956. var engine = scene.getEngine();
  31957. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31958. // or triangles as points
  31959. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31960. }
  31961. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31962. // Triangles as wireframe
  31963. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31964. }
  31965. else {
  31966. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31967. }
  31968. if (scene._isAlternateRenderingEnabled && !alternate) {
  31969. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31970. if (!effect || !scene.activeCamera) {
  31971. return this;
  31972. }
  31973. scene._switchToAlternateCameraConfiguration(true);
  31974. this._effectiveMaterial.bindView(effect);
  31975. this._effectiveMaterial.bindViewProjection(effect);
  31976. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31977. this._draw(subMesh, fillMode, instancesCount, true);
  31978. engine.setViewport(scene.activeCamera.viewport);
  31979. scene._switchToAlternateCameraConfiguration(false);
  31980. this._effectiveMaterial.bindView(effect);
  31981. this._effectiveMaterial.bindViewProjection(effect);
  31982. }
  31983. return this;
  31984. };
  31985. /**
  31986. * Registers for this mesh a javascript function called just before the rendering process.
  31987. * This function is passed the current mesh.
  31988. * Return the Mesh.
  31989. */
  31990. Mesh.prototype.registerBeforeRender = function (func) {
  31991. this.onBeforeRenderObservable.add(func);
  31992. return this;
  31993. };
  31994. /**
  31995. * Disposes a previously registered javascript function called before the rendering.
  31996. * This function is passed the current mesh.
  31997. * Returns the Mesh.
  31998. */
  31999. Mesh.prototype.unregisterBeforeRender = function (func) {
  32000. this.onBeforeRenderObservable.removeCallback(func);
  32001. return this;
  32002. };
  32003. /**
  32004. * Registers for this mesh a javascript function called just after the rendering is complete.
  32005. * This function is passed the current mesh.
  32006. * Returns the Mesh.
  32007. */
  32008. Mesh.prototype.registerAfterRender = function (func) {
  32009. this.onAfterRenderObservable.add(func);
  32010. return this;
  32011. };
  32012. /**
  32013. * Disposes a previously registered javascript function called after the rendering.
  32014. * This function is passed the current mesh.
  32015. * Return the Mesh.
  32016. */
  32017. Mesh.prototype.unregisterAfterRender = function (func) {
  32018. this.onAfterRenderObservable.removeCallback(func);
  32019. return this;
  32020. };
  32021. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32022. var scene = this.getScene();
  32023. this._batchCache.mustReturn = false;
  32024. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32025. this._batchCache.visibleInstances[subMeshId] = null;
  32026. if (this._visibleInstances) {
  32027. var currentRenderId = scene.getRenderId();
  32028. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32029. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32030. var selfRenderId = this._renderId;
  32031. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32032. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32033. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32034. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32035. }
  32036. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32037. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32038. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32039. this._batchCache.mustReturn = true;
  32040. return this._batchCache;
  32041. }
  32042. if (currentRenderId !== selfRenderId) {
  32043. this._batchCache.renderSelf[subMeshId] = false;
  32044. }
  32045. }
  32046. this._renderIdForInstances[subMeshId] = currentRenderId;
  32047. }
  32048. return this._batchCache;
  32049. };
  32050. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32051. var visibleInstances = batch.visibleInstances[subMesh._id];
  32052. if (!visibleInstances) {
  32053. return this;
  32054. }
  32055. var matricesCount = visibleInstances.length + 1;
  32056. var bufferSize = matricesCount * 16 * 4;
  32057. var currentInstancesBufferSize = this._instancesBufferSize;
  32058. var instancesBuffer = this._instancesBuffer;
  32059. while (this._instancesBufferSize < bufferSize) {
  32060. this._instancesBufferSize *= 2;
  32061. }
  32062. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32063. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32064. }
  32065. var offset = 0;
  32066. var instancesCount = 0;
  32067. var world = this.getWorldMatrix();
  32068. if (batch.renderSelf[subMesh._id]) {
  32069. world.copyToArray(this._instancesData, offset);
  32070. offset += 16;
  32071. instancesCount++;
  32072. }
  32073. if (visibleInstances) {
  32074. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32075. var instance = visibleInstances[instanceIndex];
  32076. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32077. offset += 16;
  32078. instancesCount++;
  32079. }
  32080. }
  32081. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32082. if (instancesBuffer) {
  32083. instancesBuffer.dispose();
  32084. }
  32085. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32086. this._instancesBuffer = instancesBuffer;
  32087. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32088. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32089. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32090. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32091. }
  32092. else {
  32093. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32094. }
  32095. this._bind(subMesh, effect, fillMode);
  32096. this._draw(subMesh, fillMode, instancesCount);
  32097. engine.unbindInstanceAttributes();
  32098. return this;
  32099. };
  32100. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32101. var scene = this.getScene();
  32102. var engine = scene.getEngine();
  32103. if (hardwareInstancedRendering) {
  32104. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32105. }
  32106. else {
  32107. if (batch.renderSelf[subMesh._id]) {
  32108. // Draw
  32109. if (onBeforeDraw) {
  32110. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32111. }
  32112. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32113. }
  32114. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32115. if (visibleInstancesForSubMesh) {
  32116. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32117. var instance = visibleInstancesForSubMesh[instanceIndex];
  32118. // World
  32119. var world = instance.getWorldMatrix();
  32120. if (onBeforeDraw) {
  32121. onBeforeDraw(true, world, effectiveMaterial);
  32122. }
  32123. // Draw
  32124. this._draw(subMesh, fillMode);
  32125. }
  32126. }
  32127. }
  32128. return this;
  32129. };
  32130. /**
  32131. * 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
  32132. * @param subMesh defines the subMesh to render
  32133. * @param enableAlphaMode defines if alpha mode can be changed
  32134. * @returns the current mesh
  32135. */
  32136. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32137. // this._checkOcclusionQuery();
  32138. // if (this._isOccluded) {
  32139. // return this;
  32140. // }
  32141. var scene = this.getScene();
  32142. // Managing instances
  32143. var batch = this._getInstancesRenderList(subMesh._id);
  32144. if (batch.mustReturn) {
  32145. return this;
  32146. }
  32147. // Checking geometry state
  32148. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32149. return this;
  32150. }
  32151. if (this._onBeforeRenderObservable) {
  32152. this._onBeforeRenderObservable.notifyObservers(this);
  32153. }
  32154. var engine = scene.getEngine();
  32155. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32156. // Material
  32157. var material = subMesh.getMaterial();
  32158. if (!material) {
  32159. return this;
  32160. }
  32161. this._effectiveMaterial = material;
  32162. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32163. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32164. return this;
  32165. }
  32166. }
  32167. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32168. return this;
  32169. }
  32170. // Alpha mode
  32171. if (enableAlphaMode) {
  32172. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32173. }
  32174. // Outline - step 1
  32175. var savedDepthWrite = engine.getDepthWrite();
  32176. if (this.renderOutline) {
  32177. engine.setDepthWrite(false);
  32178. scene.getOutlineRenderer().render(subMesh, batch);
  32179. engine.setDepthWrite(savedDepthWrite);
  32180. }
  32181. var effect;
  32182. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32183. effect = subMesh.effect;
  32184. }
  32185. else {
  32186. effect = this._effectiveMaterial.getEffect();
  32187. }
  32188. if (!effect) {
  32189. return this;
  32190. }
  32191. var sideOrientation = this.overrideMaterialSideOrientation;
  32192. if (sideOrientation == null) {
  32193. sideOrientation = this._effectiveMaterial.sideOrientation;
  32194. if (this._getWorldMatrixDeterminant() < 0) {
  32195. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32196. }
  32197. }
  32198. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32199. if (this._effectiveMaterial.forceDepthWrite) {
  32200. engine.setDepthWrite(true);
  32201. }
  32202. // Bind
  32203. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32204. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32205. this._bind(subMesh, effect, fillMode);
  32206. }
  32207. var world = this.getWorldMatrix();
  32208. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32209. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32210. }
  32211. else {
  32212. this._effectiveMaterial.bind(world, this);
  32213. }
  32214. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32215. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32216. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32217. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32218. }
  32219. // Draw
  32220. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32221. // Unbind
  32222. this._effectiveMaterial.unbind();
  32223. // Outline - step 2
  32224. if (this.renderOutline && savedDepthWrite) {
  32225. engine.setDepthWrite(true);
  32226. engine.setColorWrite(false);
  32227. scene.getOutlineRenderer().render(subMesh, batch);
  32228. engine.setColorWrite(true);
  32229. }
  32230. // Overlay
  32231. if (this.renderOverlay) {
  32232. var currentMode = engine.getAlphaMode();
  32233. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32234. scene.getOutlineRenderer().render(subMesh, batch, true);
  32235. engine.setAlphaMode(currentMode);
  32236. }
  32237. if (this._onAfterRenderObservable) {
  32238. this._onAfterRenderObservable.notifyObservers(this);
  32239. }
  32240. return this;
  32241. };
  32242. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32243. if (isInstance && effectiveMaterial) {
  32244. effectiveMaterial.bindOnlyWorldMatrix(world);
  32245. }
  32246. };
  32247. /**
  32248. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32249. */
  32250. Mesh.prototype.getEmittedParticleSystems = function () {
  32251. var results = new Array();
  32252. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32253. var particleSystem = this.getScene().particleSystems[index];
  32254. if (particleSystem.emitter === this) {
  32255. results.push(particleSystem);
  32256. }
  32257. }
  32258. return results;
  32259. };
  32260. /**
  32261. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32262. */
  32263. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32264. var results = new Array();
  32265. var descendants = this.getDescendants();
  32266. descendants.push(this);
  32267. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32268. var particleSystem = this.getScene().particleSystems[index];
  32269. var emitter = particleSystem.emitter;
  32270. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32271. results.push(particleSystem);
  32272. }
  32273. }
  32274. return results;
  32275. };
  32276. /**
  32277. * Normalize matrix weights so that all vertices have a total weight set to 1
  32278. */
  32279. Mesh.prototype.cleanMatrixWeights = function () {
  32280. var epsilon = 1e-3;
  32281. var noInfluenceBoneIndex = 0.0;
  32282. if (this.skeleton) {
  32283. noInfluenceBoneIndex = this.skeleton.bones.length;
  32284. }
  32285. else {
  32286. return;
  32287. }
  32288. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32289. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32290. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32291. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32292. var influencers = this.numBoneInfluencers;
  32293. var size = matricesWeights.length;
  32294. for (var i = 0; i < size; i += 4) {
  32295. var weight = 0.0;
  32296. var firstZeroWeight = -1;
  32297. for (var j = 0; j < 4; j++) {
  32298. var w = matricesWeights[i + j];
  32299. weight += w;
  32300. if (w < epsilon && firstZeroWeight < 0) {
  32301. firstZeroWeight = j;
  32302. }
  32303. }
  32304. if (matricesWeightsExtra) {
  32305. for (var j = 0; j < 4; j++) {
  32306. var w = matricesWeightsExtra[i + j];
  32307. weight += w;
  32308. if (w < epsilon && firstZeroWeight < 0) {
  32309. firstZeroWeight = j + 4;
  32310. }
  32311. }
  32312. }
  32313. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32314. firstZeroWeight = influencers - 1;
  32315. }
  32316. if (weight > epsilon) {
  32317. var mweight = 1.0 / weight;
  32318. for (var j = 0; j < 4; j++) {
  32319. matricesWeights[i + j] *= mweight;
  32320. }
  32321. if (matricesWeightsExtra) {
  32322. for (var j = 0; j < 4; j++) {
  32323. matricesWeightsExtra[i + j] *= mweight;
  32324. }
  32325. }
  32326. }
  32327. else {
  32328. if (firstZeroWeight >= 4) {
  32329. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32330. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32331. }
  32332. else {
  32333. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32334. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32335. }
  32336. }
  32337. }
  32338. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32339. if (matricesIndicesExtra) {
  32340. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32341. }
  32342. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32343. if (matricesWeightsExtra) {
  32344. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32345. }
  32346. };
  32347. Mesh.prototype._checkDelayState = function () {
  32348. var scene = this.getScene();
  32349. if (this._geometry) {
  32350. this._geometry.load(scene);
  32351. }
  32352. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32353. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32354. this._queueLoad(scene);
  32355. }
  32356. return this;
  32357. };
  32358. Mesh.prototype._queueLoad = function (scene) {
  32359. var _this = this;
  32360. scene._addPendingData(this);
  32361. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32362. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32363. if (data instanceof ArrayBuffer) {
  32364. _this._delayLoadingFunction(data, _this);
  32365. }
  32366. else {
  32367. _this._delayLoadingFunction(JSON.parse(data), _this);
  32368. }
  32369. _this.instances.forEach(function (instance) {
  32370. instance._syncSubMeshes();
  32371. });
  32372. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32373. scene._removePendingData(_this);
  32374. }, function () { }, scene.database, getBinaryData);
  32375. return this;
  32376. };
  32377. /**
  32378. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32379. */
  32380. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32381. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32382. return false;
  32383. }
  32384. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32385. return false;
  32386. }
  32387. this._checkDelayState();
  32388. return true;
  32389. };
  32390. /**
  32391. * Sets the mesh material by the material or multiMaterial `id` property.
  32392. * The material `id` is a string identifying the material or the multiMaterial.
  32393. * This method returns the Mesh.
  32394. */
  32395. Mesh.prototype.setMaterialByID = function (id) {
  32396. var materials = this.getScene().materials;
  32397. var index;
  32398. for (index = materials.length - 1; index > -1; index--) {
  32399. if (materials[index].id === id) {
  32400. this.material = materials[index];
  32401. return this;
  32402. }
  32403. }
  32404. // Multi
  32405. var multiMaterials = this.getScene().multiMaterials;
  32406. for (index = multiMaterials.length - 1; index > -1; index--) {
  32407. if (multiMaterials[index].id === id) {
  32408. this.material = multiMaterials[index];
  32409. return this;
  32410. }
  32411. }
  32412. return this;
  32413. };
  32414. /**
  32415. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32416. */
  32417. Mesh.prototype.getAnimatables = function () {
  32418. var results = new Array();
  32419. if (this.material) {
  32420. results.push(this.material);
  32421. }
  32422. if (this.skeleton) {
  32423. results.push(this.skeleton);
  32424. }
  32425. return results;
  32426. };
  32427. /**
  32428. * Modifies the mesh geometry according to the passed transformation matrix.
  32429. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32430. * The mesh normals are modified accordingly the same transformation.
  32431. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32432. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32433. * Returns the Mesh.
  32434. */
  32435. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32436. // Position
  32437. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32438. return this;
  32439. }
  32440. var submeshes = this.subMeshes.splice(0);
  32441. this._resetPointsArrayCache();
  32442. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32443. var temp = new Array();
  32444. var index;
  32445. for (index = 0; index < data.length; index += 3) {
  32446. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32447. }
  32448. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32449. // Normals
  32450. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32451. return this;
  32452. }
  32453. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32454. temp = [];
  32455. for (index = 0; index < data.length; index += 3) {
  32456. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32457. }
  32458. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32459. // flip faces?
  32460. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32461. this.flipFaces();
  32462. }
  32463. // Restore submeshes
  32464. this.releaseSubMeshes();
  32465. this.subMeshes = submeshes;
  32466. return this;
  32467. };
  32468. /**
  32469. * Modifies the mesh geometry according to its own current World Matrix.
  32470. * The mesh World Matrix is then reset.
  32471. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32472. * tuto : 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.bakeCurrentTransformIntoVertices = function () {
  32477. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32478. this.scaling.copyFromFloats(1, 1, 1);
  32479. this.position.copyFromFloats(0, 0, 0);
  32480. this.rotation.copyFromFloats(0, 0, 0);
  32481. //only if quaternion is already set
  32482. if (this.rotationQuaternion) {
  32483. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32484. }
  32485. this._worldMatrix = BABYLON.Matrix.Identity();
  32486. return this;
  32487. };
  32488. Object.defineProperty(Mesh.prototype, "_positions", {
  32489. // Cache
  32490. get: function () {
  32491. if (this._geometry) {
  32492. return this._geometry._positions;
  32493. }
  32494. return null;
  32495. },
  32496. enumerable: true,
  32497. configurable: true
  32498. });
  32499. Mesh.prototype._resetPointsArrayCache = function () {
  32500. if (this._geometry) {
  32501. this._geometry._resetPointsArrayCache();
  32502. }
  32503. return this;
  32504. };
  32505. Mesh.prototype._generatePointsArray = function () {
  32506. if (this._geometry) {
  32507. return this._geometry._generatePointsArray();
  32508. }
  32509. return false;
  32510. };
  32511. /**
  32512. * Returns a new Mesh object generated from the current mesh properties.
  32513. * This method must not get confused with createInstance().
  32514. * The parameter `name` is a string, the name given to the new mesh.
  32515. * The optional parameter `newParent` can be any Node object (default `null`).
  32516. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32517. * 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.
  32518. */
  32519. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32520. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32521. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32522. };
  32523. /**
  32524. * Releases resources associated with this mesh.
  32525. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32526. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32527. */
  32528. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32529. var _this = this;
  32530. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32531. this.morphTargetManager = null;
  32532. if (this._geometry) {
  32533. this._geometry.releaseForMesh(this, true);
  32534. }
  32535. if (this._onBeforeDrawObservable) {
  32536. this._onBeforeDrawObservable.clear();
  32537. }
  32538. if (this._onBeforeRenderObservable) {
  32539. this._onBeforeRenderObservable.clear();
  32540. }
  32541. if (this._onAfterRenderObservable) {
  32542. this._onAfterRenderObservable.clear();
  32543. }
  32544. // Sources
  32545. var meshes = this.getScene().meshes;
  32546. meshes.forEach(function (abstractMesh) {
  32547. var mesh = abstractMesh;
  32548. if (mesh._source && mesh._source === _this) {
  32549. mesh._source = null;
  32550. }
  32551. });
  32552. this._source = null;
  32553. // Instances
  32554. if (this._instancesBuffer) {
  32555. this._instancesBuffer.dispose();
  32556. this._instancesBuffer = null;
  32557. }
  32558. while (this.instances.length) {
  32559. this.instances[0].dispose();
  32560. }
  32561. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32562. };
  32563. /**
  32564. * Modifies the mesh geometry according to a displacement map.
  32565. * 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.
  32566. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32567. * This method returns nothing.
  32568. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32569. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32570. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  32571. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32572. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32573. *
  32574. * Returns the Mesh.
  32575. */
  32576. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32577. var _this = this;
  32578. var scene = this.getScene();
  32579. var onload = function (img) {
  32580. // Getting height map data
  32581. var canvas = document.createElement("canvas");
  32582. var context = canvas.getContext("2d");
  32583. var heightMapWidth = img.width;
  32584. var heightMapHeight = img.height;
  32585. canvas.width = heightMapWidth;
  32586. canvas.height = heightMapHeight;
  32587. context.drawImage(img, 0, 0);
  32588. // Create VertexData from map data
  32589. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32590. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32591. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32592. //execute success callback, if set
  32593. if (onSuccess) {
  32594. onSuccess(_this);
  32595. }
  32596. };
  32597. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32598. return this;
  32599. };
  32600. /**
  32601. * Modifies the mesh geometry according to a displacementMap buffer.
  32602. * 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.
  32603. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32604. * This method returns nothing.
  32605. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32606. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32607. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32608. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32609. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32610. *
  32611. * Returns the Mesh.
  32612. */
  32613. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32614. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32615. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32616. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32617. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32618. return this;
  32619. }
  32620. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32621. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32622. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32623. var position = BABYLON.Vector3.Zero();
  32624. var normal = BABYLON.Vector3.Zero();
  32625. var uv = BABYLON.Vector2.Zero();
  32626. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32627. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32628. for (var index = 0; index < positions.length; index += 3) {
  32629. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32630. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32631. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32632. // Compute height
  32633. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32634. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32635. var pos = (u + v * heightMapWidth) * 4;
  32636. var r = buffer[pos] / 255.0;
  32637. var g = buffer[pos + 1] / 255.0;
  32638. var b = buffer[pos + 2] / 255.0;
  32639. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32640. normal.normalize();
  32641. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32642. position = position.add(normal);
  32643. position.toArray(positions, index);
  32644. }
  32645. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32646. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32647. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32648. return this;
  32649. };
  32650. /**
  32651. * Modify the mesh to get a flat shading rendering.
  32652. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32653. * This method returns the Mesh.
  32654. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32655. */
  32656. Mesh.prototype.convertToFlatShadedMesh = function () {
  32657. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32658. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32659. var kinds = this.getVerticesDataKinds();
  32660. var vbs = {};
  32661. var data = {};
  32662. var newdata = {};
  32663. var updatableNormals = false;
  32664. var kindIndex;
  32665. var kind;
  32666. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32667. kind = kinds[kindIndex];
  32668. var vertexBuffer = this.getVertexBuffer(kind);
  32669. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32670. updatableNormals = vertexBuffer.isUpdatable();
  32671. kinds.splice(kindIndex, 1);
  32672. kindIndex--;
  32673. continue;
  32674. }
  32675. vbs[kind] = vertexBuffer;
  32676. data[kind] = vbs[kind].getData();
  32677. newdata[kind] = [];
  32678. }
  32679. // Save previous submeshes
  32680. var previousSubmeshes = this.subMeshes.slice(0);
  32681. var indices = this.getIndices();
  32682. var totalIndices = this.getTotalIndices();
  32683. // Generating unique vertices per face
  32684. var index;
  32685. for (index = 0; index < totalIndices; index++) {
  32686. var vertexIndex = indices[index];
  32687. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32688. kind = kinds[kindIndex];
  32689. var stride = vbs[kind].getStrideSize();
  32690. for (var offset = 0; offset < stride; offset++) {
  32691. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32692. }
  32693. }
  32694. }
  32695. // Updating faces & normal
  32696. var normals = [];
  32697. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32698. for (index = 0; index < totalIndices; index += 3) {
  32699. indices[index] = index;
  32700. indices[index + 1] = index + 1;
  32701. indices[index + 2] = index + 2;
  32702. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32703. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32704. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32705. var p1p2 = p1.subtract(p2);
  32706. var p3p2 = p3.subtract(p2);
  32707. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32708. // Store same normals for every vertex
  32709. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32710. normals.push(normal.x);
  32711. normals.push(normal.y);
  32712. normals.push(normal.z);
  32713. }
  32714. }
  32715. this.setIndices(indices);
  32716. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32717. // Updating vertex buffers
  32718. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32719. kind = kinds[kindIndex];
  32720. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32721. }
  32722. // Updating submeshes
  32723. this.releaseSubMeshes();
  32724. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32725. var previousOne = previousSubmeshes[submeshIndex];
  32726. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32727. }
  32728. this.synchronizeInstances();
  32729. return this;
  32730. };
  32731. /**
  32732. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32733. * In other words, more vertices, no more indices and a single bigger VBO.
  32734. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32735. * Returns the Mesh.
  32736. */
  32737. Mesh.prototype.convertToUnIndexedMesh = function () {
  32738. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32739. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32740. var kinds = this.getVerticesDataKinds();
  32741. var vbs = {};
  32742. var data = {};
  32743. var newdata = {};
  32744. var kindIndex;
  32745. var kind;
  32746. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32747. kind = kinds[kindIndex];
  32748. var vertexBuffer = this.getVertexBuffer(kind);
  32749. vbs[kind] = vertexBuffer;
  32750. data[kind] = vbs[kind].getData();
  32751. newdata[kind] = [];
  32752. }
  32753. // Save previous submeshes
  32754. var previousSubmeshes = this.subMeshes.slice(0);
  32755. var indices = this.getIndices();
  32756. var totalIndices = this.getTotalIndices();
  32757. // Generating unique vertices per face
  32758. var index;
  32759. for (index = 0; index < totalIndices; index++) {
  32760. var vertexIndex = indices[index];
  32761. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32762. kind = kinds[kindIndex];
  32763. var stride = vbs[kind].getStrideSize();
  32764. for (var offset = 0; offset < stride; offset++) {
  32765. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32766. }
  32767. }
  32768. }
  32769. // Updating indices
  32770. for (index = 0; index < totalIndices; index += 3) {
  32771. indices[index] = index;
  32772. indices[index + 1] = index + 1;
  32773. indices[index + 2] = index + 2;
  32774. }
  32775. this.setIndices(indices);
  32776. // Updating vertex buffers
  32777. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32778. kind = kinds[kindIndex];
  32779. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32780. }
  32781. // Updating submeshes
  32782. this.releaseSubMeshes();
  32783. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32784. var previousOne = previousSubmeshes[submeshIndex];
  32785. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32786. }
  32787. this._unIndexed = true;
  32788. this.synchronizeInstances();
  32789. return this;
  32790. };
  32791. /**
  32792. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32793. * This method returns the Mesh.
  32794. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32795. */
  32796. Mesh.prototype.flipFaces = function (flipNormals) {
  32797. if (flipNormals === void 0) { flipNormals = false; }
  32798. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32799. var i;
  32800. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32801. for (i = 0; i < vertex_data.normals.length; i++) {
  32802. vertex_data.normals[i] *= -1;
  32803. }
  32804. }
  32805. if (vertex_data.indices) {
  32806. var temp;
  32807. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32808. // reassign indices
  32809. temp = vertex_data.indices[i + 1];
  32810. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32811. vertex_data.indices[i + 2] = temp;
  32812. }
  32813. }
  32814. vertex_data.applyToMesh(this);
  32815. return this;
  32816. };
  32817. // Instances
  32818. /**
  32819. * Creates a new InstancedMesh object from the mesh model.
  32820. * An instance shares the same properties and the same material than its model.
  32821. * Only these properties of each instance can then be set individually :
  32822. * - position
  32823. * - rotation
  32824. * - rotationQuaternion
  32825. * - setPivotMatrix
  32826. * - scaling
  32827. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32828. * Warning : this method is not supported for Line mesh and LineSystem
  32829. */
  32830. Mesh.prototype.createInstance = function (name) {
  32831. return new BABYLON.InstancedMesh(name, this);
  32832. };
  32833. /**
  32834. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32835. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32836. * This method returns the Mesh.
  32837. */
  32838. Mesh.prototype.synchronizeInstances = function () {
  32839. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32840. var instance = this.instances[instanceIndex];
  32841. instance._syncSubMeshes();
  32842. }
  32843. return this;
  32844. };
  32845. /**
  32846. * Simplify the mesh according to the given array of settings.
  32847. * Function will return immediately and will simplify async. It returns the Mesh.
  32848. * @param settings a collection of simplification settings.
  32849. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32850. * @param type the type of simplification to run.
  32851. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32852. */
  32853. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32854. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32855. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32856. this.getScene().simplificationQueue.addTask({
  32857. settings: settings,
  32858. parallelProcessing: parallelProcessing,
  32859. mesh: this,
  32860. simplificationType: simplificationType,
  32861. successCallback: successCallback
  32862. });
  32863. return this;
  32864. };
  32865. /**
  32866. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32867. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32868. * This should be used together with the simplification to avoid disappearing triangles.
  32869. * Returns the Mesh.
  32870. * @param successCallback an optional success callback to be called after the optimization finished.
  32871. */
  32872. Mesh.prototype.optimizeIndices = function (successCallback) {
  32873. var _this = this;
  32874. var indices = this.getIndices();
  32875. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32876. if (!positions || !indices) {
  32877. return this;
  32878. }
  32879. var vectorPositions = new Array();
  32880. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32881. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32882. }
  32883. var dupes = new Array();
  32884. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32885. var realPos = vectorPositions.length - 1 - iteration;
  32886. var testedPosition = vectorPositions[realPos];
  32887. for (var j = 0; j < realPos; ++j) {
  32888. var againstPosition = vectorPositions[j];
  32889. if (testedPosition.equals(againstPosition)) {
  32890. dupes[realPos] = j;
  32891. break;
  32892. }
  32893. }
  32894. }, function () {
  32895. for (var i = 0; i < indices.length; ++i) {
  32896. indices[i] = dupes[indices[i]] || indices[i];
  32897. }
  32898. //indices are now reordered
  32899. var originalSubMeshes = _this.subMeshes.slice(0);
  32900. _this.setIndices(indices);
  32901. _this.subMeshes = originalSubMeshes;
  32902. if (successCallback) {
  32903. successCallback(_this);
  32904. }
  32905. });
  32906. return this;
  32907. };
  32908. Mesh.prototype.serialize = function (serializationObject) {
  32909. serializationObject.name = this.name;
  32910. serializationObject.id = this.id;
  32911. serializationObject.type = this.getClassName();
  32912. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32913. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32914. }
  32915. serializationObject.position = this.position.asArray();
  32916. if (this.rotationQuaternion) {
  32917. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32918. }
  32919. else if (this.rotation) {
  32920. serializationObject.rotation = this.rotation.asArray();
  32921. }
  32922. serializationObject.scaling = this.scaling.asArray();
  32923. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32924. serializationObject.isEnabled = this.isEnabled(false);
  32925. serializationObject.isVisible = this.isVisible;
  32926. serializationObject.infiniteDistance = this.infiniteDistance;
  32927. serializationObject.pickable = this.isPickable;
  32928. serializationObject.receiveShadows = this.receiveShadows;
  32929. serializationObject.billboardMode = this.billboardMode;
  32930. serializationObject.visibility = this.visibility;
  32931. serializationObject.checkCollisions = this.checkCollisions;
  32932. serializationObject.isBlocker = this.isBlocker;
  32933. // Parent
  32934. if (this.parent) {
  32935. serializationObject.parentId = this.parent.id;
  32936. }
  32937. // Geometry
  32938. serializationObject.isUnIndexed = this.isUnIndexed;
  32939. var geometry = this._geometry;
  32940. if (geometry) {
  32941. var geometryId = geometry.id;
  32942. serializationObject.geometryId = geometryId;
  32943. // SubMeshes
  32944. serializationObject.subMeshes = [];
  32945. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32946. var subMesh = this.subMeshes[subIndex];
  32947. serializationObject.subMeshes.push({
  32948. materialIndex: subMesh.materialIndex,
  32949. verticesStart: subMesh.verticesStart,
  32950. verticesCount: subMesh.verticesCount,
  32951. indexStart: subMesh.indexStart,
  32952. indexCount: subMesh.indexCount
  32953. });
  32954. }
  32955. }
  32956. // Material
  32957. if (this.material) {
  32958. serializationObject.materialId = this.material.id;
  32959. }
  32960. else {
  32961. this.material = null;
  32962. }
  32963. // Morph targets
  32964. if (this.morphTargetManager) {
  32965. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32966. }
  32967. // Skeleton
  32968. if (this.skeleton) {
  32969. serializationObject.skeletonId = this.skeleton.id;
  32970. }
  32971. // Physics
  32972. //TODO implement correct serialization for physics impostors.
  32973. var impostor = this.getPhysicsImpostor();
  32974. if (impostor) {
  32975. serializationObject.physicsMass = impostor.getParam("mass");
  32976. serializationObject.physicsFriction = impostor.getParam("friction");
  32977. serializationObject.physicsRestitution = impostor.getParam("mass");
  32978. serializationObject.physicsImpostor = impostor.type;
  32979. }
  32980. // Metadata
  32981. if (this.metadata) {
  32982. serializationObject.metadata = this.metadata;
  32983. }
  32984. // Instances
  32985. serializationObject.instances = [];
  32986. for (var index = 0; index < this.instances.length; index++) {
  32987. var instance = this.instances[index];
  32988. var serializationInstance = {
  32989. name: instance.name,
  32990. id: instance.id,
  32991. position: instance.position.asArray(),
  32992. scaling: instance.scaling.asArray()
  32993. };
  32994. if (instance.rotationQuaternion) {
  32995. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32996. }
  32997. else if (instance.rotation) {
  32998. serializationInstance.rotation = instance.rotation.asArray();
  32999. }
  33000. serializationObject.instances.push(serializationInstance);
  33001. // Animations
  33002. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33003. serializationInstance.ranges = instance.serializeAnimationRanges();
  33004. }
  33005. //
  33006. // Animations
  33007. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33008. serializationObject.ranges = this.serializeAnimationRanges();
  33009. // Layer mask
  33010. serializationObject.layerMask = this.layerMask;
  33011. // Alpha
  33012. serializationObject.alphaIndex = this.alphaIndex;
  33013. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33014. // Overlay
  33015. serializationObject.overlayAlpha = this.overlayAlpha;
  33016. serializationObject.overlayColor = this.overlayColor.asArray();
  33017. serializationObject.renderOverlay = this.renderOverlay;
  33018. // Fog
  33019. serializationObject.applyFog = this.applyFog;
  33020. // Action Manager
  33021. if (this.actionManager) {
  33022. serializationObject.actions = this.actionManager.serialize(this.name);
  33023. }
  33024. };
  33025. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33026. if (!this.geometry) {
  33027. return;
  33028. }
  33029. this._markSubMeshesAsAttributesDirty();
  33030. var morphTargetManager = this._morphTargetManager;
  33031. if (morphTargetManager && morphTargetManager.vertexCount) {
  33032. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33033. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33034. this.morphTargetManager = null;
  33035. return;
  33036. }
  33037. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33038. var morphTarget = morphTargetManager.getActiveTarget(index);
  33039. var positions = morphTarget.getPositions();
  33040. if (!positions) {
  33041. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33042. return;
  33043. }
  33044. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33045. var normals = morphTarget.getNormals();
  33046. if (normals) {
  33047. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33048. }
  33049. var tangents = morphTarget.getTangents();
  33050. if (tangents) {
  33051. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33052. }
  33053. }
  33054. }
  33055. else {
  33056. var index = 0;
  33057. // Positions
  33058. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33059. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33060. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33061. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33062. }
  33063. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33064. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33065. }
  33066. index++;
  33067. }
  33068. }
  33069. };
  33070. // Statics
  33071. /**
  33072. * Returns a new Mesh object parsed from the source provided.
  33073. * The parameter `parsedMesh` is the source.
  33074. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33075. */
  33076. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33077. var mesh;
  33078. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33079. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33080. }
  33081. else {
  33082. mesh = new Mesh(parsedMesh.name, scene);
  33083. }
  33084. mesh.id = parsedMesh.id;
  33085. if (BABYLON.Tags) {
  33086. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33087. }
  33088. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33089. if (parsedMesh.metadata !== undefined) {
  33090. mesh.metadata = parsedMesh.metadata;
  33091. }
  33092. if (parsedMesh.rotationQuaternion) {
  33093. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33094. }
  33095. else if (parsedMesh.rotation) {
  33096. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33097. }
  33098. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33099. if (parsedMesh.localMatrix) {
  33100. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33101. }
  33102. else if (parsedMesh.pivotMatrix) {
  33103. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33104. }
  33105. mesh.setEnabled(parsedMesh.isEnabled);
  33106. mesh.isVisible = parsedMesh.isVisible;
  33107. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33108. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33109. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33110. if (parsedMesh.applyFog !== undefined) {
  33111. mesh.applyFog = parsedMesh.applyFog;
  33112. }
  33113. if (parsedMesh.pickable !== undefined) {
  33114. mesh.isPickable = parsedMesh.pickable;
  33115. }
  33116. if (parsedMesh.alphaIndex !== undefined) {
  33117. mesh.alphaIndex = parsedMesh.alphaIndex;
  33118. }
  33119. mesh.receiveShadows = parsedMesh.receiveShadows;
  33120. mesh.billboardMode = parsedMesh.billboardMode;
  33121. if (parsedMesh.visibility !== undefined) {
  33122. mesh.visibility = parsedMesh.visibility;
  33123. }
  33124. mesh.checkCollisions = parsedMesh.checkCollisions;
  33125. if (parsedMesh.isBlocker !== undefined) {
  33126. mesh.isBlocker = parsedMesh.isBlocker;
  33127. }
  33128. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33129. // freezeWorldMatrix
  33130. if (parsedMesh.freezeWorldMatrix) {
  33131. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33132. }
  33133. // Parent
  33134. if (parsedMesh.parentId) {
  33135. mesh._waitingParentId = parsedMesh.parentId;
  33136. }
  33137. // Actions
  33138. if (parsedMesh.actions !== undefined) {
  33139. mesh._waitingActions = parsedMesh.actions;
  33140. }
  33141. // Overlay
  33142. if (parsedMesh.overlayAlpha !== undefined) {
  33143. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33144. }
  33145. if (parsedMesh.overlayColor !== undefined) {
  33146. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33147. }
  33148. if (parsedMesh.renderOverlay !== undefined) {
  33149. mesh.renderOverlay = parsedMesh.renderOverlay;
  33150. }
  33151. // Geometry
  33152. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33153. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33154. if (parsedMesh.delayLoadingFile) {
  33155. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33156. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33157. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33158. if (parsedMesh._binaryInfo) {
  33159. mesh._binaryInfo = parsedMesh._binaryInfo;
  33160. }
  33161. mesh._delayInfo = [];
  33162. if (parsedMesh.hasUVs) {
  33163. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33164. }
  33165. if (parsedMesh.hasUVs2) {
  33166. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33167. }
  33168. if (parsedMesh.hasUVs3) {
  33169. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33170. }
  33171. if (parsedMesh.hasUVs4) {
  33172. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33173. }
  33174. if (parsedMesh.hasUVs5) {
  33175. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33176. }
  33177. if (parsedMesh.hasUVs6) {
  33178. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33179. }
  33180. if (parsedMesh.hasColors) {
  33181. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33182. }
  33183. if (parsedMesh.hasMatricesIndices) {
  33184. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33185. }
  33186. if (parsedMesh.hasMatricesWeights) {
  33187. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33188. }
  33189. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33190. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33191. mesh._checkDelayState();
  33192. }
  33193. }
  33194. else {
  33195. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33196. }
  33197. // Material
  33198. if (parsedMesh.materialId) {
  33199. mesh.setMaterialByID(parsedMesh.materialId);
  33200. }
  33201. else {
  33202. mesh.material = null;
  33203. }
  33204. // Morph targets
  33205. if (parsedMesh.morphTargetManagerId > -1) {
  33206. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33207. }
  33208. // Skeleton
  33209. if (parsedMesh.skeletonId > -1) {
  33210. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33211. if (parsedMesh.numBoneInfluencers) {
  33212. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33213. }
  33214. }
  33215. // Animations
  33216. if (parsedMesh.animations) {
  33217. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33218. var parsedAnimation = parsedMesh.animations[animationIndex];
  33219. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33220. }
  33221. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33222. }
  33223. if (parsedMesh.autoAnimate) {
  33224. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33225. }
  33226. // Layer Mask
  33227. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33228. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33229. }
  33230. else {
  33231. mesh.layerMask = 0x0FFFFFFF;
  33232. }
  33233. // Physics
  33234. if (parsedMesh.physicsImpostor) {
  33235. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33236. mass: parsedMesh.physicsMass,
  33237. friction: parsedMesh.physicsFriction,
  33238. restitution: parsedMesh.physicsRestitution
  33239. }, scene);
  33240. }
  33241. // Instances
  33242. if (parsedMesh.instances) {
  33243. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33244. var parsedInstance = parsedMesh.instances[index];
  33245. var instance = mesh.createInstance(parsedInstance.name);
  33246. if (parsedInstance.id) {
  33247. instance.id = parsedInstance.id;
  33248. }
  33249. if (BABYLON.Tags) {
  33250. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33251. }
  33252. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33253. if (parsedInstance.parentId) {
  33254. instance._waitingParentId = parsedInstance.parentId;
  33255. }
  33256. if (parsedInstance.rotationQuaternion) {
  33257. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33258. }
  33259. else if (parsedInstance.rotation) {
  33260. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33261. }
  33262. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33263. instance.checkCollisions = mesh.checkCollisions;
  33264. if (parsedMesh.animations) {
  33265. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33266. parsedAnimation = parsedMesh.animations[animationIndex];
  33267. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33268. }
  33269. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33270. if (parsedMesh.autoAnimate) {
  33271. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33272. }
  33273. }
  33274. }
  33275. }
  33276. return mesh;
  33277. };
  33278. /**
  33279. * Creates a ribbon mesh.
  33280. * Please consider using the same method from the MeshBuilder class instead.
  33281. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33282. *
  33283. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33284. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33285. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33286. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33287. * 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.
  33288. * 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.
  33289. * 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
  33290. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33291. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33292. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33293. */
  33294. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33295. if (closeArray === void 0) { closeArray = false; }
  33296. if (updatable === void 0) { updatable = false; }
  33297. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33298. pathArray: pathArray,
  33299. closeArray: closeArray,
  33300. closePath: closePath,
  33301. offset: offset,
  33302. updatable: updatable,
  33303. sideOrientation: sideOrientation,
  33304. instance: instance
  33305. }, scene);
  33306. };
  33307. /**
  33308. * Creates a plane polygonal mesh. By default, this is a disc.
  33309. * Please consider using the same method from the MeshBuilder class instead.
  33310. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33311. * 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.
  33312. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33313. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33315. */
  33316. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33317. if (scene === void 0) { scene = null; }
  33318. var options = {
  33319. radius: radius,
  33320. tessellation: tessellation,
  33321. sideOrientation: sideOrientation,
  33322. updatable: updatable
  33323. };
  33324. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33325. };
  33326. /**
  33327. * Creates a box mesh.
  33328. * Please consider using the same method from the MeshBuilder class instead.
  33329. * The parameter `size` sets the size (float) of each box side (default 1).
  33330. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33331. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33332. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33333. */
  33334. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33335. if (scene === void 0) { scene = null; }
  33336. var options = {
  33337. size: size,
  33338. sideOrientation: sideOrientation,
  33339. updatable: updatable
  33340. };
  33341. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33342. };
  33343. /**
  33344. * Creates a sphere mesh.
  33345. * Please consider using the same method from the MeshBuilder class instead.
  33346. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33347. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33348. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33349. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33350. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33351. */
  33352. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33353. var options = {
  33354. segments: segments,
  33355. diameterX: diameter,
  33356. diameterY: diameter,
  33357. diameterZ: diameter,
  33358. sideOrientation: sideOrientation,
  33359. updatable: updatable
  33360. };
  33361. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33362. };
  33363. /**
  33364. * Creates a cylinder or a cone mesh.
  33365. * Please consider using the same method from the MeshBuilder class instead.
  33366. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33367. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33368. * 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.
  33369. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33370. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33371. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33372. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33373. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33374. */
  33375. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33376. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33377. if (scene !== undefined) {
  33378. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33379. updatable = scene;
  33380. }
  33381. scene = subdivisions;
  33382. subdivisions = 1;
  33383. }
  33384. var options = {
  33385. height: height,
  33386. diameterTop: diameterTop,
  33387. diameterBottom: diameterBottom,
  33388. tessellation: tessellation,
  33389. subdivisions: subdivisions,
  33390. sideOrientation: sideOrientation,
  33391. updatable: updatable
  33392. };
  33393. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33394. };
  33395. // Torus (Code from SharpDX.org)
  33396. /**
  33397. * Creates a torus mesh.
  33398. * Please consider using the same method from the MeshBuilder class instead.
  33399. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33400. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33401. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33402. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33403. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33405. */
  33406. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33407. var options = {
  33408. diameter: diameter,
  33409. thickness: thickness,
  33410. tessellation: tessellation,
  33411. sideOrientation: sideOrientation,
  33412. updatable: updatable
  33413. };
  33414. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33415. };
  33416. /**
  33417. * Creates a torus knot mesh.
  33418. * Please consider using the same method from the MeshBuilder class instead.
  33419. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33420. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33421. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33422. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33423. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33424. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33425. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33426. */
  33427. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33428. var options = {
  33429. radius: radius,
  33430. tube: tube,
  33431. radialSegments: radialSegments,
  33432. tubularSegments: tubularSegments,
  33433. p: p,
  33434. q: q,
  33435. sideOrientation: sideOrientation,
  33436. updatable: updatable
  33437. };
  33438. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33439. };
  33440. /**
  33441. * Creates a line mesh.
  33442. * Please consider using the same method from the MeshBuilder class instead.
  33443. * 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.
  33444. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33445. * The parameter `points` is an array successive Vector3.
  33446. * 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
  33447. * When updating an instance, remember that only point positions can change, not the number of points.
  33448. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33449. */
  33450. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33451. if (scene === void 0) { scene = null; }
  33452. if (updatable === void 0) { updatable = false; }
  33453. if (instance === void 0) { instance = null; }
  33454. var options = {
  33455. points: points,
  33456. updatable: updatable,
  33457. instance: instance
  33458. };
  33459. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33460. };
  33461. /**
  33462. * Creates a dashed line mesh.
  33463. * Please consider using the same method from the MeshBuilder class instead.
  33464. * 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.
  33465. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33466. * The parameter `points` is an array successive Vector3.
  33467. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33468. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33469. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33470. * 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
  33471. * When updating an instance, remember that only point positions can change, not the number of points.
  33472. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33473. */
  33474. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33475. if (scene === void 0) { scene = null; }
  33476. var options = {
  33477. points: points,
  33478. dashSize: dashSize,
  33479. gapSize: gapSize,
  33480. dashNb: dashNb,
  33481. updatable: updatable,
  33482. instance: instance
  33483. };
  33484. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33485. };
  33486. /**
  33487. * Creates a polygon mesh.
  33488. * Please consider using the same method from the MeshBuilder class instead.
  33489. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33490. * 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.
  33491. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33493. * Remember you can only change the shape positions, not their number when updating a polygon.
  33494. */
  33495. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33496. var options = {
  33497. shape: shape,
  33498. holes: holes,
  33499. updatable: updatable,
  33500. sideOrientation: sideOrientation
  33501. };
  33502. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33503. };
  33504. /**
  33505. * Creates an extruded polygon mesh, with depth in the Y direction.
  33506. * Please consider using the same method from the MeshBuilder class instead.
  33507. */
  33508. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33509. var options = {
  33510. shape: shape,
  33511. holes: holes,
  33512. depth: depth,
  33513. updatable: updatable,
  33514. sideOrientation: sideOrientation
  33515. };
  33516. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33517. };
  33518. /**
  33519. * Creates an extruded shape mesh.
  33520. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33521. * Please consider using the same method from the MeshBuilder class instead.
  33522. *
  33523. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33524. * 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
  33525. * extruded along the Z axis.
  33526. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33527. * 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.
  33528. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33529. * 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
  33530. * 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
  33531. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33532. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33533. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33535. */
  33536. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33537. if (scene === void 0) { scene = null; }
  33538. var options = {
  33539. shape: shape,
  33540. path: path,
  33541. scale: scale,
  33542. rotation: rotation,
  33543. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33544. sideOrientation: sideOrientation,
  33545. instance: instance,
  33546. updatable: updatable
  33547. };
  33548. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33549. };
  33550. /**
  33551. * Creates an custom extruded shape mesh.
  33552. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33553. * Please consider using the same method from the MeshBuilder class instead.
  33554. *
  33555. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33556. * 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
  33557. * extruded along the Z axis.
  33558. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33559. * 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
  33560. * and the distance of this point from the begining of the path :
  33561. * ```javascript
  33562. * var rotationFunction = function(i, distance) {
  33563. * // do things
  33564. * return rotationValue; }
  33565. * ```
  33566. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33567. * 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
  33568. * and the distance of this point from the begining of the path :
  33569. * ```javascript
  33570. * var scaleFunction = function(i, distance) {
  33571. * // do things
  33572. * return scaleValue;}
  33573. * ```
  33574. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33575. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33576. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  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.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33585. var options = {
  33586. shape: shape,
  33587. path: path,
  33588. scaleFunction: scaleFunction,
  33589. rotationFunction: rotationFunction,
  33590. ribbonCloseArray: ribbonCloseArray,
  33591. ribbonClosePath: ribbonClosePath,
  33592. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33593. sideOrientation: sideOrientation,
  33594. instance: instance,
  33595. updatable: updatable
  33596. };
  33597. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33598. };
  33599. /**
  33600. * Creates lathe mesh.
  33601. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33602. * Please consider using the same method from the MeshBuilder class instead.
  33603. * 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
  33604. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33605. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33606. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33607. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33608. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33609. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33610. */
  33611. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33612. var options = {
  33613. shape: shape,
  33614. radius: radius,
  33615. tessellation: tessellation,
  33616. sideOrientation: sideOrientation,
  33617. updatable: updatable
  33618. };
  33619. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33620. };
  33621. /**
  33622. * Creates a plane mesh.
  33623. * Please consider using the same method from the MeshBuilder class instead.
  33624. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33625. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33626. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33628. */
  33629. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33630. var options = {
  33631. size: size,
  33632. width: size,
  33633. height: size,
  33634. sideOrientation: sideOrientation,
  33635. updatable: updatable
  33636. };
  33637. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33638. };
  33639. /**
  33640. * Creates a ground mesh.
  33641. * Please consider using the same method from the MeshBuilder class instead.
  33642. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33643. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33645. */
  33646. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33647. var options = {
  33648. width: width,
  33649. height: height,
  33650. subdivisions: subdivisions,
  33651. updatable: updatable
  33652. };
  33653. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33654. };
  33655. /**
  33656. * Creates a tiled ground mesh.
  33657. * Please consider using the same method from the MeshBuilder class instead.
  33658. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33659. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33660. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33661. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33662. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33663. * numbers of subdivisions on the ground width and height of each tile.
  33664. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33665. */
  33666. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33667. var options = {
  33668. xmin: xmin,
  33669. zmin: zmin,
  33670. xmax: xmax,
  33671. zmax: zmax,
  33672. subdivisions: subdivisions,
  33673. precision: precision,
  33674. updatable: updatable
  33675. };
  33676. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33677. };
  33678. /**
  33679. * Creates a ground mesh from a height map.
  33680. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33681. * Please consider using the same method from the MeshBuilder class instead.
  33682. * The parameter `url` sets the URL of the height map image resource.
  33683. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33684. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33685. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33686. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33687. * 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).
  33688. * This function is passed the newly built mesh :
  33689. * ```javascript
  33690. * function(mesh) { // do things
  33691. * return; }
  33692. * ```
  33693. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33694. */
  33695. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33696. var options = {
  33697. width: width,
  33698. height: height,
  33699. subdivisions: subdivisions,
  33700. minHeight: minHeight,
  33701. maxHeight: maxHeight,
  33702. updatable: updatable,
  33703. onReady: onReady
  33704. };
  33705. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33706. };
  33707. /**
  33708. * Creates a tube mesh.
  33709. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33710. * Please consider using the same method from the MeshBuilder class instead.
  33711. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33712. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33713. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33714. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33715. * 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.
  33716. * It must return a radius value (positive float) :
  33717. * ```javascript
  33718. * var radiusFunction = function(i, distance) {
  33719. * // do things
  33720. * return radius; }
  33721. * ```
  33722. * 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
  33723. * 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
  33724. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33725. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33726. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33727. */
  33728. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33729. var options = {
  33730. path: path,
  33731. radius: radius,
  33732. tessellation: tessellation,
  33733. radiusFunction: radiusFunction,
  33734. arc: 1,
  33735. cap: cap,
  33736. updatable: updatable,
  33737. sideOrientation: sideOrientation,
  33738. instance: instance
  33739. };
  33740. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33741. };
  33742. /**
  33743. * Creates a polyhedron mesh.
  33744. * Please consider using the same method from the MeshBuilder class instead.
  33745. * 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
  33746. * to choose the wanted type.
  33747. * The parameter `size` (positive float, default 1) sets the polygon size.
  33748. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33749. * 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`.
  33750. * 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
  33751. * 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)`).
  33752. * 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
  33753. * 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.
  33754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33755. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33757. */
  33758. Mesh.CreatePolyhedron = function (name, options, scene) {
  33759. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33760. };
  33761. /**
  33762. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33763. * Please consider using the same method from the MeshBuilder class instead.
  33764. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33765. * 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`).
  33766. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33767. * 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.
  33768. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33769. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33770. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33771. */
  33772. Mesh.CreateIcoSphere = function (name, options, scene) {
  33773. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33774. };
  33775. /**
  33776. * Creates a decal mesh.
  33777. * Please consider using the same method from the MeshBuilder class instead.
  33778. * 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.
  33779. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33780. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33781. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33782. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33783. */
  33784. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33785. var options = {
  33786. position: position,
  33787. normal: normal,
  33788. size: size,
  33789. angle: angle
  33790. };
  33791. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33792. };
  33793. // Skeletons
  33794. /**
  33795. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33796. */
  33797. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33798. if (!this._sourcePositions) {
  33799. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33800. if (!source) {
  33801. return this._sourcePositions;
  33802. }
  33803. this._sourcePositions = new Float32Array(source);
  33804. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33805. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33806. }
  33807. }
  33808. return this._sourcePositions;
  33809. };
  33810. /**
  33811. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33812. */
  33813. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33814. if (!this._sourceNormals) {
  33815. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33816. if (!source) {
  33817. return this._sourceNormals;
  33818. }
  33819. this._sourceNormals = new Float32Array(source);
  33820. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33821. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33822. }
  33823. }
  33824. return this._sourceNormals;
  33825. };
  33826. /**
  33827. * Updates the vertex buffer by applying transformation from the bones.
  33828. * Returns the Mesh.
  33829. *
  33830. * @param {skeleton} skeleton to apply
  33831. */
  33832. Mesh.prototype.applySkeleton = function (skeleton) {
  33833. if (!this.geometry) {
  33834. return this;
  33835. }
  33836. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33837. return this;
  33838. }
  33839. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33840. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33841. return this;
  33842. }
  33843. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33844. return this;
  33845. }
  33846. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33847. return this;
  33848. }
  33849. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33850. return this;
  33851. }
  33852. if (!this._sourcePositions) {
  33853. var submeshes = this.subMeshes.slice();
  33854. this.setPositionsForCPUSkinning();
  33855. this.subMeshes = submeshes;
  33856. }
  33857. if (!this._sourceNormals) {
  33858. this.setNormalsForCPUSkinning();
  33859. }
  33860. // positionsData checks for not being Float32Array will only pass at most once
  33861. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33862. if (!positionsData) {
  33863. return this;
  33864. }
  33865. if (!(positionsData instanceof Float32Array)) {
  33866. positionsData = new Float32Array(positionsData);
  33867. }
  33868. // normalsData checks for not being Float32Array will only pass at most once
  33869. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33870. if (!normalsData) {
  33871. return this;
  33872. }
  33873. if (!(normalsData instanceof Float32Array)) {
  33874. normalsData = new Float32Array(normalsData);
  33875. }
  33876. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33877. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33878. if (!matricesWeightsData || !matricesIndicesData) {
  33879. return this;
  33880. }
  33881. var needExtras = this.numBoneInfluencers > 4;
  33882. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33883. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33884. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33885. var tempVector3 = BABYLON.Vector3.Zero();
  33886. var finalMatrix = new BABYLON.Matrix();
  33887. var tempMatrix = new BABYLON.Matrix();
  33888. var matWeightIdx = 0;
  33889. var inf;
  33890. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33891. var weight;
  33892. for (inf = 0; inf < 4; inf++) {
  33893. weight = matricesWeightsData[matWeightIdx + inf];
  33894. if (weight > 0) {
  33895. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33896. finalMatrix.addToSelf(tempMatrix);
  33897. }
  33898. }
  33899. if (needExtras) {
  33900. for (inf = 0; inf < 4; inf++) {
  33901. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33902. if (weight > 0) {
  33903. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33904. finalMatrix.addToSelf(tempMatrix);
  33905. }
  33906. }
  33907. }
  33908. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33909. tempVector3.toArray(positionsData, index);
  33910. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33911. tempVector3.toArray(normalsData, index);
  33912. finalMatrix.reset();
  33913. }
  33914. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33915. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33916. return this;
  33917. };
  33918. // Tools
  33919. /**
  33920. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33921. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33922. */
  33923. Mesh.MinMax = function (meshes) {
  33924. var minVector = null;
  33925. var maxVector = null;
  33926. meshes.forEach(function (mesh, index, array) {
  33927. var boundingInfo = mesh.getBoundingInfo();
  33928. var boundingBox = boundingInfo.boundingBox;
  33929. if (!minVector || !maxVector) {
  33930. minVector = boundingBox.minimumWorld;
  33931. maxVector = boundingBox.maximumWorld;
  33932. }
  33933. else {
  33934. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33935. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33936. }
  33937. });
  33938. if (!minVector || !maxVector) {
  33939. return {
  33940. min: BABYLON.Vector3.Zero(),
  33941. max: BABYLON.Vector3.Zero()
  33942. };
  33943. }
  33944. return {
  33945. min: minVector,
  33946. max: maxVector
  33947. };
  33948. };
  33949. /**
  33950. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33951. */
  33952. Mesh.Center = function (meshesOrMinMaxVector) {
  33953. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33954. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33955. };
  33956. /**
  33957. * Merge the array of meshes into a single mesh for performance reasons.
  33958. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33959. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33960. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33961. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33962. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33963. */
  33964. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33965. if (disposeSource === void 0) { disposeSource = true; }
  33966. var index;
  33967. if (!allow32BitsIndices) {
  33968. var totalVertices = 0;
  33969. // Counting vertices
  33970. for (index = 0; index < meshes.length; index++) {
  33971. if (meshes[index]) {
  33972. totalVertices += meshes[index].getTotalVertices();
  33973. if (totalVertices > 65536) {
  33974. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33975. return null;
  33976. }
  33977. }
  33978. }
  33979. }
  33980. // Merge
  33981. var vertexData = null;
  33982. var otherVertexData;
  33983. var indiceArray = new Array();
  33984. var source = null;
  33985. for (index = 0; index < meshes.length; index++) {
  33986. if (meshes[index]) {
  33987. meshes[index].computeWorldMatrix(true);
  33988. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33989. otherVertexData.transform(meshes[index].getWorldMatrix());
  33990. if (vertexData) {
  33991. vertexData.merge(otherVertexData);
  33992. }
  33993. else {
  33994. vertexData = otherVertexData;
  33995. source = meshes[index];
  33996. }
  33997. if (subdivideWithSubMeshes) {
  33998. indiceArray.push(meshes[index].getTotalIndices());
  33999. }
  34000. }
  34001. }
  34002. source = source;
  34003. if (!meshSubclass) {
  34004. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34005. }
  34006. vertexData.applyToMesh(meshSubclass);
  34007. // Setting properties
  34008. meshSubclass.material = source.material;
  34009. meshSubclass.checkCollisions = source.checkCollisions;
  34010. // Cleaning
  34011. if (disposeSource) {
  34012. for (index = 0; index < meshes.length; index++) {
  34013. if (meshes[index]) {
  34014. meshes[index].dispose();
  34015. }
  34016. }
  34017. }
  34018. // Subdivide
  34019. if (subdivideWithSubMeshes) {
  34020. //-- removal of global submesh
  34021. meshSubclass.releaseSubMeshes();
  34022. index = 0;
  34023. var offset = 0;
  34024. //-- apply subdivision according to index table
  34025. while (index < indiceArray.length) {
  34026. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34027. offset += indiceArray[index];
  34028. index++;
  34029. }
  34030. }
  34031. return meshSubclass;
  34032. };
  34033. // Consts
  34034. Mesh._FRONTSIDE = 0;
  34035. Mesh._BACKSIDE = 1;
  34036. Mesh._DOUBLESIDE = 2;
  34037. Mesh._DEFAULTSIDE = 0;
  34038. Mesh._NO_CAP = 0;
  34039. Mesh._CAP_START = 1;
  34040. Mesh._CAP_END = 2;
  34041. Mesh._CAP_ALL = 3;
  34042. return Mesh;
  34043. }(BABYLON.AbstractMesh));
  34044. BABYLON.Mesh = Mesh;
  34045. })(BABYLON || (BABYLON = {}));
  34046. //# sourceMappingURL=babylon.mesh.js.map
  34047. var BABYLON;
  34048. (function (BABYLON) {
  34049. var BaseSubMesh = /** @class */ (function () {
  34050. function BaseSubMesh() {
  34051. }
  34052. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34053. get: function () {
  34054. return this._materialEffect;
  34055. },
  34056. enumerable: true,
  34057. configurable: true
  34058. });
  34059. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34060. if (defines === void 0) { defines = null; }
  34061. if (this._materialEffect === effect) {
  34062. if (!effect) {
  34063. this._materialDefines = null;
  34064. }
  34065. return;
  34066. }
  34067. this._materialDefines = defines;
  34068. this._materialEffect = effect;
  34069. };
  34070. return BaseSubMesh;
  34071. }());
  34072. BABYLON.BaseSubMesh = BaseSubMesh;
  34073. var SubMesh = /** @class */ (function (_super) {
  34074. __extends(SubMesh, _super);
  34075. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34076. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34077. var _this = _super.call(this) || this;
  34078. _this.materialIndex = materialIndex;
  34079. _this.verticesStart = verticesStart;
  34080. _this.verticesCount = verticesCount;
  34081. _this.indexStart = indexStart;
  34082. _this.indexCount = indexCount;
  34083. _this._renderId = 0;
  34084. _this._mesh = mesh;
  34085. _this._renderingMesh = renderingMesh || mesh;
  34086. mesh.subMeshes.push(_this);
  34087. _this._trianglePlanes = [];
  34088. _this._id = mesh.subMeshes.length - 1;
  34089. if (createBoundingBox) {
  34090. _this.refreshBoundingInfo();
  34091. mesh.computeWorldMatrix(true);
  34092. }
  34093. return _this;
  34094. }
  34095. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34096. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34097. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34098. };
  34099. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34100. get: function () {
  34101. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34102. },
  34103. enumerable: true,
  34104. configurable: true
  34105. });
  34106. /**
  34107. * Returns the submesh BoudingInfo object.
  34108. */
  34109. SubMesh.prototype.getBoundingInfo = function () {
  34110. if (this.IsGlobal) {
  34111. return this._mesh.getBoundingInfo();
  34112. }
  34113. return this._boundingInfo;
  34114. };
  34115. /**
  34116. * Sets the submesh BoundingInfo.
  34117. * Return the SubMesh.
  34118. */
  34119. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34120. this._boundingInfo = boundingInfo;
  34121. return this;
  34122. };
  34123. /**
  34124. * Returns the mesh of the current submesh.
  34125. */
  34126. SubMesh.prototype.getMesh = function () {
  34127. return this._mesh;
  34128. };
  34129. /**
  34130. * Returns the rendering mesh of the submesh.
  34131. */
  34132. SubMesh.prototype.getRenderingMesh = function () {
  34133. return this._renderingMesh;
  34134. };
  34135. /**
  34136. * Returns the submesh material.
  34137. */
  34138. SubMesh.prototype.getMaterial = function () {
  34139. var rootMaterial = this._renderingMesh.material;
  34140. if (rootMaterial === null || rootMaterial === undefined) {
  34141. return this._mesh.getScene().defaultMaterial;
  34142. }
  34143. else if (rootMaterial.getSubMaterial) {
  34144. var multiMaterial = rootMaterial;
  34145. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34146. if (this._currentMaterial !== effectiveMaterial) {
  34147. this._currentMaterial = effectiveMaterial;
  34148. this._materialDefines = null;
  34149. }
  34150. return effectiveMaterial;
  34151. }
  34152. return rootMaterial;
  34153. };
  34154. // Methods
  34155. /**
  34156. * Sets a new updated BoundingInfo object to the submesh.
  34157. * Returns the SubMesh.
  34158. */
  34159. SubMesh.prototype.refreshBoundingInfo = function () {
  34160. this._lastColliderWorldVertices = null;
  34161. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34162. return this;
  34163. }
  34164. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34165. if (!data) {
  34166. this._boundingInfo = this._mesh.getBoundingInfo();
  34167. return this;
  34168. }
  34169. var indices = this._renderingMesh.getIndices();
  34170. var extend;
  34171. //is this the only submesh?
  34172. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34173. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34174. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34175. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34176. }
  34177. else {
  34178. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34179. }
  34180. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34181. return this;
  34182. };
  34183. SubMesh.prototype._checkCollision = function (collider) {
  34184. var boundingInfo = this.getBoundingInfo();
  34185. return boundingInfo._checkCollision(collider);
  34186. };
  34187. /**
  34188. * Updates the submesh BoundingInfo.
  34189. * Returns the Submesh.
  34190. */
  34191. SubMesh.prototype.updateBoundingInfo = function (world) {
  34192. var boundingInfo = this.getBoundingInfo();
  34193. if (!boundingInfo) {
  34194. this.refreshBoundingInfo();
  34195. boundingInfo = this.getBoundingInfo();
  34196. }
  34197. boundingInfo.update(world);
  34198. return this;
  34199. };
  34200. /**
  34201. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34202. * Boolean returned.
  34203. */
  34204. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34205. var boundingInfo = this.getBoundingInfo();
  34206. if (!boundingInfo) {
  34207. return false;
  34208. }
  34209. return boundingInfo.isInFrustum(frustumPlanes);
  34210. };
  34211. /**
  34212. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34213. * Boolean returned.
  34214. */
  34215. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34216. var boundingInfo = this.getBoundingInfo();
  34217. if (!boundingInfo) {
  34218. return false;
  34219. }
  34220. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34221. };
  34222. /**
  34223. * Renders the submesh.
  34224. * Returns it.
  34225. */
  34226. SubMesh.prototype.render = function (enableAlphaMode) {
  34227. this._renderingMesh.render(this, enableAlphaMode);
  34228. return this;
  34229. };
  34230. /**
  34231. * Returns a new Index Buffer.
  34232. * Type returned : WebGLBuffer.
  34233. */
  34234. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34235. if (!this._linesIndexBuffer) {
  34236. var linesIndices = [];
  34237. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34238. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34239. }
  34240. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34241. this.linesIndexCount = linesIndices.length;
  34242. }
  34243. return this._linesIndexBuffer;
  34244. };
  34245. /**
  34246. * True is the passed Ray intersects the submesh bounding box.
  34247. * Boolean returned.
  34248. */
  34249. SubMesh.prototype.canIntersects = function (ray) {
  34250. var boundingInfo = this.getBoundingInfo();
  34251. if (!boundingInfo) {
  34252. return false;
  34253. }
  34254. return ray.intersectsBox(boundingInfo.boundingBox);
  34255. };
  34256. /**
  34257. * Returns an object IntersectionInfo.
  34258. */
  34259. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34260. var intersectInfo = null;
  34261. var material = this.getMaterial();
  34262. if (!material) {
  34263. return null;
  34264. }
  34265. switch (material.fillMode) {
  34266. case BABYLON.Material.PointListDrawMode:
  34267. case BABYLON.Material.LineListDrawMode:
  34268. case BABYLON.Material.LineLoopDrawMode:
  34269. case BABYLON.Material.LineStripDrawMode:
  34270. case BABYLON.Material.TriangleFanDrawMode:
  34271. case BABYLON.Material.TriangleStripDrawMode:
  34272. return null;
  34273. }
  34274. // LineMesh first as it's also a Mesh...
  34275. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34276. var lineMesh = this._mesh;
  34277. // Line test
  34278. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34279. var p0 = positions[indices[index]];
  34280. var p1 = positions[indices[index + 1]];
  34281. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34282. if (length < 0) {
  34283. continue;
  34284. }
  34285. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34286. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34287. if (fastCheck) {
  34288. break;
  34289. }
  34290. }
  34291. }
  34292. }
  34293. else {
  34294. // Triangles test
  34295. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34296. var p0 = positions[indices[index]];
  34297. var p1 = positions[indices[index + 1]];
  34298. var p2 = positions[indices[index + 2]];
  34299. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34300. if (currentIntersectInfo) {
  34301. if (currentIntersectInfo.distance < 0) {
  34302. continue;
  34303. }
  34304. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34305. intersectInfo = currentIntersectInfo;
  34306. intersectInfo.faceId = index / 3;
  34307. if (fastCheck) {
  34308. break;
  34309. }
  34310. }
  34311. }
  34312. }
  34313. }
  34314. return intersectInfo;
  34315. };
  34316. SubMesh.prototype._rebuild = function () {
  34317. if (this._linesIndexBuffer) {
  34318. this._linesIndexBuffer = null;
  34319. }
  34320. };
  34321. // Clone
  34322. /**
  34323. * Creates a new Submesh from the passed Mesh.
  34324. */
  34325. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34326. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34327. if (!this.IsGlobal) {
  34328. var boundingInfo = this.getBoundingInfo();
  34329. if (!boundingInfo) {
  34330. return result;
  34331. }
  34332. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34333. }
  34334. return result;
  34335. };
  34336. // Dispose
  34337. /**
  34338. * Disposes the Submesh.
  34339. * Returns nothing.
  34340. */
  34341. SubMesh.prototype.dispose = function () {
  34342. if (this._linesIndexBuffer) {
  34343. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34344. this._linesIndexBuffer = null;
  34345. }
  34346. // Remove from mesh
  34347. var index = this._mesh.subMeshes.indexOf(this);
  34348. this._mesh.subMeshes.splice(index, 1);
  34349. };
  34350. // Statics
  34351. /**
  34352. * Creates a new Submesh from the passed parameters :
  34353. * - materialIndex (integer) : the index of the main mesh material.
  34354. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34355. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34356. * - mesh (Mesh) : the main mesh to create the submesh from.
  34357. * - renderingMesh (optional Mesh) : rendering mesh.
  34358. */
  34359. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34360. var minVertexIndex = Number.MAX_VALUE;
  34361. var maxVertexIndex = -Number.MAX_VALUE;
  34362. renderingMesh = (renderingMesh || mesh);
  34363. var indices = renderingMesh.getIndices();
  34364. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34365. var vertexIndex = indices[index];
  34366. if (vertexIndex < minVertexIndex)
  34367. minVertexIndex = vertexIndex;
  34368. if (vertexIndex > maxVertexIndex)
  34369. maxVertexIndex = vertexIndex;
  34370. }
  34371. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34372. };
  34373. return SubMesh;
  34374. }(BaseSubMesh));
  34375. BABYLON.SubMesh = SubMesh;
  34376. })(BABYLON || (BABYLON = {}));
  34377. //# sourceMappingURL=babylon.subMesh.js.map
  34378. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34379. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34380. s = arguments[i];
  34381. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34382. t[p] = s[p];
  34383. }
  34384. return t;
  34385. };
  34386. var BABYLON;
  34387. (function (BABYLON) {
  34388. /**
  34389. * Manages the defines for the Material
  34390. */
  34391. var MaterialDefines = /** @class */ (function () {
  34392. function MaterialDefines() {
  34393. this._isDirty = true;
  34394. /** @hidden */
  34395. this._areLightsDirty = true;
  34396. /** @hidden */
  34397. this._areAttributesDirty = true;
  34398. /** @hidden */
  34399. this._areTexturesDirty = true;
  34400. /** @hidden */
  34401. this._areFresnelDirty = true;
  34402. /** @hidden */
  34403. this._areMiscDirty = true;
  34404. /** @hidden */
  34405. this._areImageProcessingDirty = true;
  34406. /** @hidden */
  34407. this._normals = false;
  34408. /** @hidden */
  34409. this._uvs = false;
  34410. /** @hidden */
  34411. this._needNormals = false;
  34412. /** @hidden */
  34413. this._needUVs = false;
  34414. }
  34415. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34416. /**
  34417. * Specifies if the material needs to be re-calculated
  34418. */
  34419. get: function () {
  34420. return this._isDirty;
  34421. },
  34422. enumerable: true,
  34423. configurable: true
  34424. });
  34425. /**
  34426. * Marks the material to indicate that it has been re-calculated
  34427. */
  34428. MaterialDefines.prototype.markAsProcessed = function () {
  34429. this._isDirty = false;
  34430. this._areAttributesDirty = false;
  34431. this._areTexturesDirty = false;
  34432. this._areFresnelDirty = false;
  34433. this._areLightsDirty = false;
  34434. this._areMiscDirty = false;
  34435. this._areImageProcessingDirty = false;
  34436. };
  34437. /**
  34438. * Marks the material to indicate that it needs to be re-calculated
  34439. */
  34440. MaterialDefines.prototype.markAsUnprocessed = function () {
  34441. this._isDirty = true;
  34442. };
  34443. /**
  34444. * Marks the material to indicate all of its defines need to be re-calculated
  34445. */
  34446. MaterialDefines.prototype.markAllAsDirty = function () {
  34447. this._areTexturesDirty = true;
  34448. this._areAttributesDirty = true;
  34449. this._areLightsDirty = true;
  34450. this._areFresnelDirty = true;
  34451. this._areMiscDirty = true;
  34452. this._areImageProcessingDirty = true;
  34453. this._isDirty = true;
  34454. };
  34455. /**
  34456. * Marks the material to indicate that image processing needs to be re-calculated
  34457. */
  34458. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34459. this._areImageProcessingDirty = true;
  34460. this._isDirty = true;
  34461. };
  34462. /**
  34463. * Marks the material to indicate the lights need to be re-calculated
  34464. */
  34465. MaterialDefines.prototype.markAsLightDirty = function () {
  34466. this._areLightsDirty = true;
  34467. this._isDirty = true;
  34468. };
  34469. /**
  34470. * Marks the attribute state as changed
  34471. */
  34472. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34473. this._areAttributesDirty = true;
  34474. this._isDirty = true;
  34475. };
  34476. /**
  34477. * Marks the texture state as changed
  34478. */
  34479. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34480. this._areTexturesDirty = true;
  34481. this._isDirty = true;
  34482. };
  34483. /**
  34484. * Marks the fresnel state as changed
  34485. */
  34486. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34487. this._areFresnelDirty = true;
  34488. this._isDirty = true;
  34489. };
  34490. /**
  34491. * Marks the misc state as changed
  34492. */
  34493. MaterialDefines.prototype.markAsMiscDirty = function () {
  34494. this._areMiscDirty = true;
  34495. this._isDirty = true;
  34496. };
  34497. /**
  34498. * Rebuilds the material defines
  34499. */
  34500. MaterialDefines.prototype.rebuild = function () {
  34501. if (this._keys) {
  34502. delete this._keys;
  34503. }
  34504. this._keys = [];
  34505. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34506. var key = _a[_i];
  34507. if (key[0] === "_") {
  34508. continue;
  34509. }
  34510. this._keys.push(key);
  34511. }
  34512. };
  34513. /**
  34514. * Specifies if two material defines are equal
  34515. * @param other - A material define instance to compare to
  34516. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34517. */
  34518. MaterialDefines.prototype.isEqual = function (other) {
  34519. if (this._keys.length !== other._keys.length) {
  34520. return false;
  34521. }
  34522. for (var index = 0; index < this._keys.length; index++) {
  34523. var prop = this._keys[index];
  34524. if (this[prop] !== other[prop]) {
  34525. return false;
  34526. }
  34527. }
  34528. return true;
  34529. };
  34530. /**
  34531. * Clones this instance's defines to another instance
  34532. * @param other - material defines to clone values to
  34533. */
  34534. MaterialDefines.prototype.cloneTo = function (other) {
  34535. if (this._keys.length !== other._keys.length) {
  34536. other._keys = this._keys.slice(0);
  34537. }
  34538. for (var index = 0; index < this._keys.length; index++) {
  34539. var prop = this._keys[index];
  34540. other[prop] = this[prop];
  34541. }
  34542. };
  34543. /**
  34544. * Resets the material define values
  34545. */
  34546. MaterialDefines.prototype.reset = function () {
  34547. for (var index = 0; index < this._keys.length; index++) {
  34548. var prop = this._keys[index];
  34549. var type = typeof this[prop];
  34550. switch (type) {
  34551. case "number":
  34552. this[prop] = 0;
  34553. break;
  34554. case "string":
  34555. this[prop] = "";
  34556. break;
  34557. default:
  34558. this[prop] = false;
  34559. break;
  34560. }
  34561. }
  34562. };
  34563. /**
  34564. * Converts the material define values to a string
  34565. * @returns - String of material define information
  34566. */
  34567. MaterialDefines.prototype.toString = function () {
  34568. var result = "";
  34569. for (var index = 0; index < this._keys.length; index++) {
  34570. var prop = this._keys[index];
  34571. var value = this[prop];
  34572. var type = typeof value;
  34573. switch (type) {
  34574. case "number":
  34575. case "string":
  34576. result += "#define " + prop + " " + value + "\n";
  34577. break;
  34578. default:
  34579. if (value) {
  34580. result += "#define " + prop + "\n";
  34581. }
  34582. break;
  34583. }
  34584. }
  34585. return result;
  34586. };
  34587. return MaterialDefines;
  34588. }());
  34589. BABYLON.MaterialDefines = MaterialDefines;
  34590. /**
  34591. * Base class for the main features of a material in Babylon.js
  34592. */
  34593. var Material = /** @class */ (function () {
  34594. /**
  34595. * Creates a material instance
  34596. * @param name defines the name of the material
  34597. * @param scene defines the scene to reference
  34598. * @param doNotAdd specifies if the material should be added to the scene
  34599. */
  34600. function Material(name, scene, doNotAdd) {
  34601. /**
  34602. * Specifies if the ready state should be checked on each call
  34603. */
  34604. this.checkReadyOnEveryCall = false;
  34605. /**
  34606. * Specifies if the ready state should be checked once
  34607. */
  34608. this.checkReadyOnlyOnce = false;
  34609. /**
  34610. * The state of the material
  34611. */
  34612. this.state = "";
  34613. /**
  34614. * The alpha value of the material
  34615. */
  34616. this._alpha = 1.0;
  34617. /**
  34618. * Specifies if back face culling is enabled
  34619. */
  34620. this._backFaceCulling = true;
  34621. /**
  34622. * Specifies if the material should be serialized
  34623. */
  34624. this.doNotSerialize = false;
  34625. /**
  34626. * Specifies if the effect should be stored on sub meshes
  34627. */
  34628. this.storeEffectOnSubMeshes = false;
  34629. /**
  34630. * An event triggered when the material is disposed
  34631. */
  34632. this.onDisposeObservable = new BABYLON.Observable();
  34633. /**
  34634. * Stores the value of the alpha mode
  34635. */
  34636. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34637. /**
  34638. * Stores the state of the need depth pre-pass value
  34639. */
  34640. this._needDepthPrePass = false;
  34641. /**
  34642. * Specifies if depth writing should be disabled
  34643. */
  34644. this.disableDepthWrite = false;
  34645. /**
  34646. * Specifies if depth writing should be forced
  34647. */
  34648. this.forceDepthWrite = false;
  34649. /**
  34650. * Specifies if there should be a separate pass for culling
  34651. */
  34652. this.separateCullingPass = false;
  34653. /**
  34654. * Stores the state specifing if fog should be enabled
  34655. */
  34656. this._fogEnabled = true;
  34657. /**
  34658. * Stores the size of points
  34659. */
  34660. this.pointSize = 1.0;
  34661. /**
  34662. * Stores the z offset value
  34663. */
  34664. this.zOffset = 0;
  34665. /**
  34666. * Specifies if the material was previously ready
  34667. */
  34668. this._wasPreviouslyReady = false;
  34669. /**
  34670. * Stores the fill mode state
  34671. */
  34672. this._fillMode = Material.TriangleFillMode;
  34673. this.name = name;
  34674. this.id = name || BABYLON.Tools.RandomId();
  34675. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34676. this.uniqueId = this._scene.getUniqueId();
  34677. if (this._scene.useRightHandedSystem) {
  34678. this.sideOrientation = Material.ClockWiseSideOrientation;
  34679. }
  34680. else {
  34681. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34682. }
  34683. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34684. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34685. if (!doNotAdd) {
  34686. this._scene.materials.push(this);
  34687. }
  34688. }
  34689. Object.defineProperty(Material, "TriangleFillMode", {
  34690. /**
  34691. * Returns the triangle fill mode
  34692. */
  34693. get: function () {
  34694. return Material._TriangleFillMode;
  34695. },
  34696. enumerable: true,
  34697. configurable: true
  34698. });
  34699. Object.defineProperty(Material, "WireFrameFillMode", {
  34700. /**
  34701. * Returns the wireframe mode
  34702. */
  34703. get: function () {
  34704. return Material._WireFrameFillMode;
  34705. },
  34706. enumerable: true,
  34707. configurable: true
  34708. });
  34709. Object.defineProperty(Material, "PointFillMode", {
  34710. /**
  34711. * Returns the point fill mode
  34712. */
  34713. get: function () {
  34714. return Material._PointFillMode;
  34715. },
  34716. enumerable: true,
  34717. configurable: true
  34718. });
  34719. Object.defineProperty(Material, "PointListDrawMode", {
  34720. /**
  34721. * Returns the point list draw mode
  34722. */
  34723. get: function () {
  34724. return Material._PointListDrawMode;
  34725. },
  34726. enumerable: true,
  34727. configurable: true
  34728. });
  34729. Object.defineProperty(Material, "LineListDrawMode", {
  34730. /**
  34731. * Returns the line list draw mode
  34732. */
  34733. get: function () {
  34734. return Material._LineListDrawMode;
  34735. },
  34736. enumerable: true,
  34737. configurable: true
  34738. });
  34739. Object.defineProperty(Material, "LineLoopDrawMode", {
  34740. /**
  34741. * Returns the line loop draw mode
  34742. */
  34743. get: function () {
  34744. return Material._LineLoopDrawMode;
  34745. },
  34746. enumerable: true,
  34747. configurable: true
  34748. });
  34749. Object.defineProperty(Material, "LineStripDrawMode", {
  34750. /**
  34751. * Returns the line strip draw mode
  34752. */
  34753. get: function () {
  34754. return Material._LineStripDrawMode;
  34755. },
  34756. enumerable: true,
  34757. configurable: true
  34758. });
  34759. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34760. /**
  34761. * Returns the triangle strip draw mode
  34762. */
  34763. get: function () {
  34764. return Material._TriangleStripDrawMode;
  34765. },
  34766. enumerable: true,
  34767. configurable: true
  34768. });
  34769. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34770. /**
  34771. * Returns the triangle fan draw mode
  34772. */
  34773. get: function () {
  34774. return Material._TriangleFanDrawMode;
  34775. },
  34776. enumerable: true,
  34777. configurable: true
  34778. });
  34779. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34780. /**
  34781. * Returns the clock-wise side orientation
  34782. */
  34783. get: function () {
  34784. return Material._ClockWiseSideOrientation;
  34785. },
  34786. enumerable: true,
  34787. configurable: true
  34788. });
  34789. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34790. /**
  34791. * Returns the counter clock-wise side orientation
  34792. */
  34793. get: function () {
  34794. return Material._CounterClockWiseSideOrientation;
  34795. },
  34796. enumerable: true,
  34797. configurable: true
  34798. });
  34799. Object.defineProperty(Material, "TextureDirtyFlag", {
  34800. /**
  34801. * Returns the dirty texture flag value
  34802. */
  34803. get: function () {
  34804. return Material._TextureDirtyFlag;
  34805. },
  34806. enumerable: true,
  34807. configurable: true
  34808. });
  34809. Object.defineProperty(Material, "LightDirtyFlag", {
  34810. /**
  34811. * Returns the dirty light flag value
  34812. */
  34813. get: function () {
  34814. return Material._LightDirtyFlag;
  34815. },
  34816. enumerable: true,
  34817. configurable: true
  34818. });
  34819. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34820. /**
  34821. * Returns the dirty fresnel flag value
  34822. */
  34823. get: function () {
  34824. return Material._FresnelDirtyFlag;
  34825. },
  34826. enumerable: true,
  34827. configurable: true
  34828. });
  34829. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34830. /**
  34831. * Returns the dirty attributes flag value
  34832. */
  34833. get: function () {
  34834. return Material._AttributesDirtyFlag;
  34835. },
  34836. enumerable: true,
  34837. configurable: true
  34838. });
  34839. Object.defineProperty(Material, "MiscDirtyFlag", {
  34840. /**
  34841. * Returns the dirty misc flag value
  34842. */
  34843. get: function () {
  34844. return Material._MiscDirtyFlag;
  34845. },
  34846. enumerable: true,
  34847. configurable: true
  34848. });
  34849. Object.defineProperty(Material.prototype, "alpha", {
  34850. /**
  34851. * Gets the alpha value of the material
  34852. */
  34853. get: function () {
  34854. return this._alpha;
  34855. },
  34856. /**
  34857. * Sets the alpha value of the material
  34858. */
  34859. set: function (value) {
  34860. if (this._alpha === value) {
  34861. return;
  34862. }
  34863. this._alpha = value;
  34864. this.markAsDirty(Material.MiscDirtyFlag);
  34865. },
  34866. enumerable: true,
  34867. configurable: true
  34868. });
  34869. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34870. /**
  34871. * Gets the back-face culling state
  34872. */
  34873. get: function () {
  34874. return this._backFaceCulling;
  34875. },
  34876. /**
  34877. * Sets the back-face culling state
  34878. */
  34879. set: function (value) {
  34880. if (this._backFaceCulling === value) {
  34881. return;
  34882. }
  34883. this._backFaceCulling = value;
  34884. this.markAsDirty(Material.TextureDirtyFlag);
  34885. },
  34886. enumerable: true,
  34887. configurable: true
  34888. });
  34889. Object.defineProperty(Material.prototype, "onDispose", {
  34890. /**
  34891. * Called during a dispose event
  34892. */
  34893. set: function (callback) {
  34894. if (this._onDisposeObserver) {
  34895. this.onDisposeObservable.remove(this._onDisposeObserver);
  34896. }
  34897. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34898. },
  34899. enumerable: true,
  34900. configurable: true
  34901. });
  34902. Object.defineProperty(Material.prototype, "onBindObservable", {
  34903. /**
  34904. * An event triggered when the material is bound
  34905. */
  34906. get: function () {
  34907. if (!this._onBindObservable) {
  34908. this._onBindObservable = new BABYLON.Observable();
  34909. }
  34910. return this._onBindObservable;
  34911. },
  34912. enumerable: true,
  34913. configurable: true
  34914. });
  34915. Object.defineProperty(Material.prototype, "onBind", {
  34916. /**
  34917. * Called during a bind event
  34918. */
  34919. set: function (callback) {
  34920. if (this._onBindObserver) {
  34921. this.onBindObservable.remove(this._onBindObserver);
  34922. }
  34923. this._onBindObserver = this.onBindObservable.add(callback);
  34924. },
  34925. enumerable: true,
  34926. configurable: true
  34927. });
  34928. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34929. /**
  34930. * An event triggered when the material is unbound
  34931. */
  34932. get: function () {
  34933. if (!this._onUnBindObservable) {
  34934. this._onUnBindObservable = new BABYLON.Observable();
  34935. }
  34936. return this._onUnBindObservable;
  34937. },
  34938. enumerable: true,
  34939. configurable: true
  34940. });
  34941. Object.defineProperty(Material.prototype, "alphaMode", {
  34942. /**
  34943. * Gets the value of the alpha mode
  34944. */
  34945. get: function () {
  34946. return this._alphaMode;
  34947. },
  34948. /**
  34949. * Sets the value of the alpha mode.
  34950. *
  34951. * | Value | Type | Description |
  34952. * | --- | --- | --- |
  34953. * | 0 | ALPHA_DISABLE | |
  34954. * | 1 | ALPHA_ADD | |
  34955. * | 2 | ALPHA_COMBINE | |
  34956. * | 3 | ALPHA_SUBTRACT | |
  34957. * | 4 | ALPHA_MULTIPLY | |
  34958. * | 5 | ALPHA_MAXIMIZED | |
  34959. * | 6 | ALPHA_ONEONE | |
  34960. * | 7 | ALPHA_PREMULTIPLIED | |
  34961. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34962. * | 9 | ALPHA_INTERPOLATE | |
  34963. * | 10 | ALPHA_SCREENMODE | |
  34964. *
  34965. */
  34966. set: function (value) {
  34967. if (this._alphaMode === value) {
  34968. return;
  34969. }
  34970. this._alphaMode = value;
  34971. this.markAsDirty(Material.TextureDirtyFlag);
  34972. },
  34973. enumerable: true,
  34974. configurable: true
  34975. });
  34976. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34977. /**
  34978. * Gets the depth pre-pass value
  34979. */
  34980. get: function () {
  34981. return this._needDepthPrePass;
  34982. },
  34983. /**
  34984. * Sets the need depth pre-pass value
  34985. */
  34986. set: function (value) {
  34987. if (this._needDepthPrePass === value) {
  34988. return;
  34989. }
  34990. this._needDepthPrePass = value;
  34991. if (this._needDepthPrePass) {
  34992. this.checkReadyOnEveryCall = true;
  34993. }
  34994. },
  34995. enumerable: true,
  34996. configurable: true
  34997. });
  34998. Object.defineProperty(Material.prototype, "fogEnabled", {
  34999. /**
  35000. * Gets the value of the fog enabled state
  35001. */
  35002. get: function () {
  35003. return this._fogEnabled;
  35004. },
  35005. /**
  35006. * Sets the state for enabling fog
  35007. */
  35008. set: function (value) {
  35009. if (this._fogEnabled === value) {
  35010. return;
  35011. }
  35012. this._fogEnabled = value;
  35013. this.markAsDirty(Material.MiscDirtyFlag);
  35014. },
  35015. enumerable: true,
  35016. configurable: true
  35017. });
  35018. Object.defineProperty(Material.prototype, "wireframe", {
  35019. /**
  35020. * Gets a value specifying if wireframe mode is enabled
  35021. */
  35022. get: function () {
  35023. switch (this._fillMode) {
  35024. case Material.WireFrameFillMode:
  35025. case Material.LineListDrawMode:
  35026. case Material.LineLoopDrawMode:
  35027. case Material.LineStripDrawMode:
  35028. return true;
  35029. }
  35030. return this._scene.forceWireframe;
  35031. },
  35032. /**
  35033. * Sets the state of wireframe mode
  35034. */
  35035. set: function (value) {
  35036. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35037. },
  35038. enumerable: true,
  35039. configurable: true
  35040. });
  35041. Object.defineProperty(Material.prototype, "pointsCloud", {
  35042. /**
  35043. * Gets the value specifying if point clouds are enabled
  35044. */
  35045. get: function () {
  35046. switch (this._fillMode) {
  35047. case Material.PointFillMode:
  35048. case Material.PointListDrawMode:
  35049. return true;
  35050. }
  35051. return this._scene.forcePointsCloud;
  35052. },
  35053. /**
  35054. * Sets the state of point cloud mode
  35055. */
  35056. set: function (value) {
  35057. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35058. },
  35059. enumerable: true,
  35060. configurable: true
  35061. });
  35062. Object.defineProperty(Material.prototype, "fillMode", {
  35063. /**
  35064. * Gets the material fill mode
  35065. */
  35066. get: function () {
  35067. return this._fillMode;
  35068. },
  35069. /**
  35070. * Sets the material fill mode
  35071. */
  35072. set: function (value) {
  35073. if (this._fillMode === value) {
  35074. return;
  35075. }
  35076. this._fillMode = value;
  35077. this.markAsDirty(Material.MiscDirtyFlag);
  35078. },
  35079. enumerable: true,
  35080. configurable: true
  35081. });
  35082. /**
  35083. * Returns a string representation of the current material
  35084. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35085. * @returns a string with material information
  35086. */
  35087. Material.prototype.toString = function (fullDetails) {
  35088. var ret = "Name: " + this.name;
  35089. if (fullDetails) {
  35090. }
  35091. return ret;
  35092. };
  35093. /**
  35094. * Gets the class name of the material
  35095. * @returns a string with the class name of the material
  35096. */
  35097. Material.prototype.getClassName = function () {
  35098. return "Material";
  35099. };
  35100. Object.defineProperty(Material.prototype, "isFrozen", {
  35101. /**
  35102. * Specifies if updates for the material been locked
  35103. */
  35104. get: function () {
  35105. return this.checkReadyOnlyOnce;
  35106. },
  35107. enumerable: true,
  35108. configurable: true
  35109. });
  35110. /**
  35111. * Locks updates for the material
  35112. */
  35113. Material.prototype.freeze = function () {
  35114. this.checkReadyOnlyOnce = true;
  35115. };
  35116. /**
  35117. * Unlocks updates for the material
  35118. */
  35119. Material.prototype.unfreeze = function () {
  35120. this.checkReadyOnlyOnce = false;
  35121. };
  35122. /**
  35123. * Specifies if the material is ready to be used
  35124. * @param mesh defines the mesh to check
  35125. * @param useInstances specifies if instances should be used
  35126. * @returns a boolean indicating if the material is ready to be used
  35127. */
  35128. Material.prototype.isReady = function (mesh, useInstances) {
  35129. return true;
  35130. };
  35131. /**
  35132. * Specifies that the submesh is ready to be used
  35133. * @param mesh defines the mesh to check
  35134. * @param subMesh defines which submesh to check
  35135. * @param useInstances specifies that instances should be used
  35136. * @returns a boolean indicating that the submesh is ready or not
  35137. */
  35138. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35139. return false;
  35140. };
  35141. /**
  35142. * Returns the material effect
  35143. * @returns the effect associated with the material
  35144. */
  35145. Material.prototype.getEffect = function () {
  35146. return this._effect;
  35147. };
  35148. /**
  35149. * Returns the current scene
  35150. * @returns a Scene
  35151. */
  35152. Material.prototype.getScene = function () {
  35153. return this._scene;
  35154. };
  35155. /**
  35156. * Specifies if the material will require alpha blending
  35157. * @returns a boolean specifying if alpha blending is needed
  35158. */
  35159. Material.prototype.needAlphaBlending = function () {
  35160. return (this.alpha < 1.0);
  35161. };
  35162. /**
  35163. * Specifies if the mesh will require alpha blending
  35164. * @param mesh defines the mesh to check
  35165. * @returns a boolean specifying if alpha blending is needed for the mesh
  35166. */
  35167. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35168. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35169. };
  35170. /**
  35171. * Specifies if this material should be rendered in alpha test mode
  35172. * @returns a boolean specifying if an alpha test is needed.
  35173. */
  35174. Material.prototype.needAlphaTesting = function () {
  35175. return false;
  35176. };
  35177. /**
  35178. * Gets the texture used for the alpha test
  35179. * @returns the texture to use for alpha testing
  35180. */
  35181. Material.prototype.getAlphaTestTexture = function () {
  35182. return null;
  35183. };
  35184. /**
  35185. * Marks the material to indicate that it needs to be re-calculated
  35186. */
  35187. Material.prototype.markDirty = function () {
  35188. this._wasPreviouslyReady = false;
  35189. };
  35190. /** @hidden */
  35191. Material.prototype._preBind = function (effect, overrideOrientation) {
  35192. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35193. var engine = this._scene.getEngine();
  35194. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35195. var reverse = orientation === Material.ClockWiseSideOrientation;
  35196. engine.enableEffect(effect ? effect : this._effect);
  35197. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35198. return reverse;
  35199. };
  35200. /**
  35201. * Binds the material to the mesh
  35202. * @param world defines the world transformation matrix
  35203. * @param mesh defines the mesh to bind the material to
  35204. */
  35205. Material.prototype.bind = function (world, mesh) {
  35206. };
  35207. /**
  35208. * Binds the submesh to the material
  35209. * @param world defines the world transformation matrix
  35210. * @param mesh defines the mesh containing the submesh
  35211. * @param subMesh defines the submesh to bind the material to
  35212. */
  35213. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35214. };
  35215. /**
  35216. * Binds the world matrix to the material
  35217. * @param world defines the world transformation matrix
  35218. */
  35219. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35220. };
  35221. /**
  35222. * Binds the scene's uniform buffer to the effect.
  35223. * @param effect defines the effect to bind to the scene uniform buffer
  35224. * @param sceneUbo defines the uniform buffer storing scene data
  35225. */
  35226. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35227. sceneUbo.bindToEffect(effect, "Scene");
  35228. };
  35229. /**
  35230. * Binds the view matrix to the effect
  35231. * @param effect defines the effect to bind the view matrix to
  35232. */
  35233. Material.prototype.bindView = function (effect) {
  35234. if (!this._useUBO) {
  35235. effect.setMatrix("view", this.getScene().getViewMatrix());
  35236. }
  35237. else {
  35238. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35239. }
  35240. };
  35241. /**
  35242. * Binds the view projection matrix to the effect
  35243. * @param effect defines the effect to bind the view projection matrix to
  35244. */
  35245. Material.prototype.bindViewProjection = function (effect) {
  35246. if (!this._useUBO) {
  35247. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35248. }
  35249. else {
  35250. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35251. }
  35252. };
  35253. /**
  35254. * Specifies if material alpha testing should be turned on for the mesh
  35255. * @param mesh defines the mesh to check
  35256. */
  35257. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35258. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35259. };
  35260. /**
  35261. * Processes to execute after binding the material to a mesh
  35262. * @param mesh defines the rendered mesh
  35263. */
  35264. Material.prototype._afterBind = function (mesh) {
  35265. this._scene._cachedMaterial = this;
  35266. if (mesh) {
  35267. this._scene._cachedVisibility = mesh.visibility;
  35268. }
  35269. else {
  35270. this._scene._cachedVisibility = 1;
  35271. }
  35272. if (this._onBindObservable && mesh) {
  35273. this._onBindObservable.notifyObservers(mesh);
  35274. }
  35275. if (this.disableDepthWrite) {
  35276. var engine = this._scene.getEngine();
  35277. this._cachedDepthWriteState = engine.getDepthWrite();
  35278. engine.setDepthWrite(false);
  35279. }
  35280. };
  35281. /**
  35282. * Unbinds the material from the mesh
  35283. */
  35284. Material.prototype.unbind = function () {
  35285. if (this._onUnBindObservable) {
  35286. this._onUnBindObservable.notifyObservers(this);
  35287. }
  35288. if (this.disableDepthWrite) {
  35289. var engine = this._scene.getEngine();
  35290. engine.setDepthWrite(this._cachedDepthWriteState);
  35291. }
  35292. };
  35293. /**
  35294. * Gets the active textures from the material
  35295. * @returns an array of textures
  35296. */
  35297. Material.prototype.getActiveTextures = function () {
  35298. return [];
  35299. };
  35300. /**
  35301. * Specifies if the material uses a texture
  35302. * @param texture defines the texture to check against the material
  35303. * @returns a boolean specifying if the material uses the texture
  35304. */
  35305. Material.prototype.hasTexture = function (texture) {
  35306. return false;
  35307. };
  35308. /**
  35309. * Makes a duplicate of the material, and gives it a new name
  35310. * @param name defines the new name for the duplicated material
  35311. * @returns the cloned material
  35312. */
  35313. Material.prototype.clone = function (name) {
  35314. return null;
  35315. };
  35316. /**
  35317. * Gets the meshes bound to the material
  35318. * @returns an array of meshes bound to the material
  35319. */
  35320. Material.prototype.getBindedMeshes = function () {
  35321. var result = new Array();
  35322. for (var index = 0; index < this._scene.meshes.length; index++) {
  35323. var mesh = this._scene.meshes[index];
  35324. if (mesh.material === this) {
  35325. result.push(mesh);
  35326. }
  35327. }
  35328. return result;
  35329. };
  35330. /**
  35331. * Force shader compilation
  35332. * @param mesh defines the mesh associated with this material
  35333. * @param onCompiled defines a function to execute once the material is compiled
  35334. * @param options defines the options to configure the compilation
  35335. */
  35336. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35337. var _this = this;
  35338. var localOptions = __assign({ clipPlane: false }, options);
  35339. var subMesh = new BABYLON.BaseSubMesh();
  35340. var scene = this.getScene();
  35341. var checkReady = function () {
  35342. if (!_this._scene || !_this._scene.getEngine()) {
  35343. return;
  35344. }
  35345. if (subMesh._materialDefines) {
  35346. subMesh._materialDefines._renderId = -1;
  35347. }
  35348. var clipPlaneState = scene.clipPlane;
  35349. if (localOptions.clipPlane) {
  35350. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35351. }
  35352. if (_this.storeEffectOnSubMeshes) {
  35353. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35354. if (onCompiled) {
  35355. onCompiled(_this);
  35356. }
  35357. }
  35358. else {
  35359. setTimeout(checkReady, 16);
  35360. }
  35361. }
  35362. else {
  35363. if (_this.isReady(mesh)) {
  35364. if (onCompiled) {
  35365. onCompiled(_this);
  35366. }
  35367. }
  35368. else {
  35369. setTimeout(checkReady, 16);
  35370. }
  35371. }
  35372. if (localOptions.clipPlane) {
  35373. scene.clipPlane = clipPlaneState;
  35374. }
  35375. };
  35376. checkReady();
  35377. };
  35378. /**
  35379. * Force shader compilation
  35380. * @param mesh defines the mesh that will use this material
  35381. * @param options defines additional options for compiling the shaders
  35382. * @returns a promise that resolves when the compilation completes
  35383. */
  35384. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35385. var _this = this;
  35386. return new Promise(function (resolve) {
  35387. _this.forceCompilation(mesh, function () {
  35388. resolve();
  35389. }, options);
  35390. });
  35391. };
  35392. /**
  35393. * Marks a define in the material to indicate that it needs to be re-computed
  35394. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35395. */
  35396. Material.prototype.markAsDirty = function (flag) {
  35397. if (flag & Material.TextureDirtyFlag) {
  35398. this._markAllSubMeshesAsTexturesDirty();
  35399. }
  35400. if (flag & Material.LightDirtyFlag) {
  35401. this._markAllSubMeshesAsLightsDirty();
  35402. }
  35403. if (flag & Material.FresnelDirtyFlag) {
  35404. this._markAllSubMeshesAsFresnelDirty();
  35405. }
  35406. if (flag & Material.AttributesDirtyFlag) {
  35407. this._markAllSubMeshesAsAttributesDirty();
  35408. }
  35409. if (flag & Material.MiscDirtyFlag) {
  35410. this._markAllSubMeshesAsMiscDirty();
  35411. }
  35412. this.getScene().resetCachedMaterial();
  35413. };
  35414. /**
  35415. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35416. * @param func defines a function which checks material defines against the submeshes
  35417. */
  35418. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35419. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35420. var mesh = _a[_i];
  35421. if (!mesh.subMeshes) {
  35422. continue;
  35423. }
  35424. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35425. var subMesh = _c[_b];
  35426. if (subMesh.getMaterial() !== this) {
  35427. continue;
  35428. }
  35429. if (!subMesh._materialDefines) {
  35430. continue;
  35431. }
  35432. func(subMesh._materialDefines);
  35433. }
  35434. }
  35435. };
  35436. /**
  35437. * Indicates that image processing needs to be re-calculated for all submeshes
  35438. */
  35439. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35440. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35441. };
  35442. /**
  35443. * Indicates that textures need to be re-calculated for all submeshes
  35444. */
  35445. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35446. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35447. };
  35448. /**
  35449. * Indicates that fresnel needs to be re-calculated for all submeshes
  35450. */
  35451. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35452. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35453. };
  35454. /**
  35455. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35456. */
  35457. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35458. this._markAllSubMeshesAsDirty(function (defines) {
  35459. defines.markAsFresnelDirty();
  35460. defines.markAsMiscDirty();
  35461. });
  35462. };
  35463. /**
  35464. * Indicates that lights need to be re-calculated for all submeshes
  35465. */
  35466. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35467. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35468. };
  35469. /**
  35470. * Indicates that attributes need to be re-calculated for all submeshes
  35471. */
  35472. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35473. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35474. };
  35475. /**
  35476. * Indicates that misc needs to be re-calculated for all submeshes
  35477. */
  35478. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35479. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35480. };
  35481. /**
  35482. * Indicates that textures and misc need to be re-calculated for all submeshes
  35483. */
  35484. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35485. this._markAllSubMeshesAsDirty(function (defines) {
  35486. defines.markAsTexturesDirty();
  35487. defines.markAsMiscDirty();
  35488. });
  35489. };
  35490. /**
  35491. * Disposes the material
  35492. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35493. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35494. */
  35495. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35496. // Animations
  35497. this.getScene().stopAnimation(this);
  35498. this.getScene().freeProcessedMaterials();
  35499. // Remove from scene
  35500. var index = this._scene.materials.indexOf(this);
  35501. if (index >= 0) {
  35502. this._scene.materials.splice(index, 1);
  35503. }
  35504. // Remove from meshes
  35505. for (index = 0; index < this._scene.meshes.length; index++) {
  35506. var mesh = this._scene.meshes[index];
  35507. if (mesh.material === this) {
  35508. mesh.material = null;
  35509. if (mesh.geometry) {
  35510. var geometry = (mesh.geometry);
  35511. if (this.storeEffectOnSubMeshes) {
  35512. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35513. var subMesh = _a[_i];
  35514. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35515. if (forceDisposeEffect && subMesh._materialEffect) {
  35516. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35517. }
  35518. }
  35519. }
  35520. else {
  35521. geometry._releaseVertexArrayObject(this._effect);
  35522. }
  35523. }
  35524. }
  35525. }
  35526. this._uniformBuffer.dispose();
  35527. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35528. if (forceDisposeEffect && this._effect) {
  35529. if (!this.storeEffectOnSubMeshes) {
  35530. this._scene.getEngine()._releaseEffect(this._effect);
  35531. }
  35532. this._effect = null;
  35533. }
  35534. // Callback
  35535. this.onDisposeObservable.notifyObservers(this);
  35536. this.onDisposeObservable.clear();
  35537. if (this._onBindObservable) {
  35538. this._onBindObservable.clear();
  35539. }
  35540. if (this._onUnBindObservable) {
  35541. this._onUnBindObservable.clear();
  35542. }
  35543. };
  35544. /**
  35545. * Serializes this material
  35546. * @returns the serialized material object
  35547. */
  35548. Material.prototype.serialize = function () {
  35549. return BABYLON.SerializationHelper.Serialize(this);
  35550. };
  35551. /**
  35552. * Creates a MultiMaterial from parsed MultiMaterial data.
  35553. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35554. * @param scene defines the hosting scene
  35555. * @returns a new MultiMaterial
  35556. */
  35557. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35558. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35559. multiMaterial.id = parsedMultiMaterial.id;
  35560. if (BABYLON.Tags) {
  35561. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35562. }
  35563. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35564. var subMatId = parsedMultiMaterial.materials[matIndex];
  35565. if (subMatId) {
  35566. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35567. }
  35568. else {
  35569. multiMaterial.subMaterials.push(null);
  35570. }
  35571. }
  35572. return multiMaterial;
  35573. };
  35574. /**
  35575. * Creates a material from parsed material data
  35576. * @param parsedMaterial defines parsed material data
  35577. * @param scene defines the hosting scene
  35578. * @param rootUrl defines the root URL to use to load textures
  35579. * @returns a new material
  35580. */
  35581. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35582. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35583. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35584. }
  35585. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35586. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35587. if (!BABYLON.LegacyPBRMaterial) {
  35588. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35589. return;
  35590. }
  35591. }
  35592. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35593. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35594. };
  35595. // Triangle views
  35596. Material._TriangleFillMode = 0;
  35597. Material._WireFrameFillMode = 1;
  35598. Material._PointFillMode = 2;
  35599. // Draw modes
  35600. Material._PointListDrawMode = 3;
  35601. Material._LineListDrawMode = 4;
  35602. Material._LineLoopDrawMode = 5;
  35603. Material._LineStripDrawMode = 6;
  35604. Material._TriangleStripDrawMode = 7;
  35605. Material._TriangleFanDrawMode = 8;
  35606. /**
  35607. * Stores the clock-wise side orientation
  35608. */
  35609. Material._ClockWiseSideOrientation = 0;
  35610. /**
  35611. * Stores the counter clock-wise side orientation
  35612. */
  35613. Material._CounterClockWiseSideOrientation = 1;
  35614. /**
  35615. * The dirty texture flag value
  35616. */
  35617. Material._TextureDirtyFlag = 1;
  35618. /**
  35619. * The dirty light flag value
  35620. */
  35621. Material._LightDirtyFlag = 2;
  35622. /**
  35623. * The dirty fresnel flag value
  35624. */
  35625. Material._FresnelDirtyFlag = 4;
  35626. /**
  35627. * The dirty attribute flag value
  35628. */
  35629. Material._AttributesDirtyFlag = 8;
  35630. /**
  35631. * The dirty misc flag value
  35632. */
  35633. Material._MiscDirtyFlag = 16;
  35634. __decorate([
  35635. BABYLON.serialize()
  35636. ], Material.prototype, "id", void 0);
  35637. __decorate([
  35638. BABYLON.serialize()
  35639. ], Material.prototype, "uniqueId", void 0);
  35640. __decorate([
  35641. BABYLON.serialize()
  35642. ], Material.prototype, "name", void 0);
  35643. __decorate([
  35644. BABYLON.serialize()
  35645. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35646. __decorate([
  35647. BABYLON.serialize()
  35648. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35649. __decorate([
  35650. BABYLON.serialize()
  35651. ], Material.prototype, "state", void 0);
  35652. __decorate([
  35653. BABYLON.serialize("alpha")
  35654. ], Material.prototype, "_alpha", void 0);
  35655. __decorate([
  35656. BABYLON.serialize("backFaceCulling")
  35657. ], Material.prototype, "_backFaceCulling", void 0);
  35658. __decorate([
  35659. BABYLON.serialize()
  35660. ], Material.prototype, "sideOrientation", void 0);
  35661. __decorate([
  35662. BABYLON.serialize("alphaMode")
  35663. ], Material.prototype, "_alphaMode", void 0);
  35664. __decorate([
  35665. BABYLON.serialize()
  35666. ], Material.prototype, "_needDepthPrePass", void 0);
  35667. __decorate([
  35668. BABYLON.serialize()
  35669. ], Material.prototype, "disableDepthWrite", void 0);
  35670. __decorate([
  35671. BABYLON.serialize()
  35672. ], Material.prototype, "forceDepthWrite", void 0);
  35673. __decorate([
  35674. BABYLON.serialize()
  35675. ], Material.prototype, "separateCullingPass", void 0);
  35676. __decorate([
  35677. BABYLON.serialize("fogEnabled")
  35678. ], Material.prototype, "_fogEnabled", void 0);
  35679. __decorate([
  35680. BABYLON.serialize()
  35681. ], Material.prototype, "pointSize", void 0);
  35682. __decorate([
  35683. BABYLON.serialize()
  35684. ], Material.prototype, "zOffset", void 0);
  35685. __decorate([
  35686. BABYLON.serialize()
  35687. ], Material.prototype, "wireframe", null);
  35688. __decorate([
  35689. BABYLON.serialize()
  35690. ], Material.prototype, "pointsCloud", null);
  35691. __decorate([
  35692. BABYLON.serialize()
  35693. ], Material.prototype, "fillMode", null);
  35694. return Material;
  35695. }());
  35696. BABYLON.Material = Material;
  35697. })(BABYLON || (BABYLON = {}));
  35698. //# sourceMappingURL=babylon.material.js.map
  35699. var BABYLON;
  35700. (function (BABYLON) {
  35701. var UniformBuffer = /** @class */ (function () {
  35702. /**
  35703. * Uniform buffer objects.
  35704. *
  35705. * Handles blocks of uniform on the GPU.
  35706. *
  35707. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35708. *
  35709. * For more information, please refer to :
  35710. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35711. */
  35712. function UniformBuffer(engine, data, dynamic) {
  35713. this._engine = engine;
  35714. this._noUBO = !engine.supportsUniformBuffers;
  35715. this._dynamic = dynamic;
  35716. this._data = data || [];
  35717. this._uniformLocations = {};
  35718. this._uniformSizes = {};
  35719. this._uniformLocationPointer = 0;
  35720. this._needSync = false;
  35721. if (this._noUBO) {
  35722. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35723. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35724. this.updateFloat = this._updateFloatForEffect;
  35725. this.updateFloat2 = this._updateFloat2ForEffect;
  35726. this.updateFloat3 = this._updateFloat3ForEffect;
  35727. this.updateFloat4 = this._updateFloat4ForEffect;
  35728. this.updateMatrix = this._updateMatrixForEffect;
  35729. this.updateVector3 = this._updateVector3ForEffect;
  35730. this.updateVector4 = this._updateVector4ForEffect;
  35731. this.updateColor3 = this._updateColor3ForEffect;
  35732. this.updateColor4 = this._updateColor4ForEffect;
  35733. }
  35734. else {
  35735. this._engine._uniformBuffers.push(this);
  35736. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35737. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35738. this.updateFloat = this._updateFloatForUniform;
  35739. this.updateFloat2 = this._updateFloat2ForUniform;
  35740. this.updateFloat3 = this._updateFloat3ForUniform;
  35741. this.updateFloat4 = this._updateFloat4ForUniform;
  35742. this.updateMatrix = this._updateMatrixForUniform;
  35743. this.updateVector3 = this._updateVector3ForUniform;
  35744. this.updateVector4 = this._updateVector4ForUniform;
  35745. this.updateColor3 = this._updateColor3ForUniform;
  35746. this.updateColor4 = this._updateColor4ForUniform;
  35747. }
  35748. }
  35749. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35750. // Properties
  35751. /**
  35752. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35753. * or just falling back on setUniformXXX calls.
  35754. */
  35755. get: function () {
  35756. return !this._noUBO;
  35757. },
  35758. enumerable: true,
  35759. configurable: true
  35760. });
  35761. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35762. /**
  35763. * Indicates if the WebGL underlying uniform buffer is in sync
  35764. * with the javascript cache data.
  35765. */
  35766. get: function () {
  35767. return !this._needSync;
  35768. },
  35769. enumerable: true,
  35770. configurable: true
  35771. });
  35772. /**
  35773. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35774. * Also, a dynamic UniformBuffer will disable cache verification and always
  35775. * update the underlying WebGL uniform buffer to the GPU.
  35776. */
  35777. UniformBuffer.prototype.isDynamic = function () {
  35778. return this._dynamic !== undefined;
  35779. };
  35780. /**
  35781. * The data cache on JS side.
  35782. */
  35783. UniformBuffer.prototype.getData = function () {
  35784. return this._bufferData;
  35785. };
  35786. /**
  35787. * The underlying WebGL Uniform buffer.
  35788. */
  35789. UniformBuffer.prototype.getBuffer = function () {
  35790. return this._buffer;
  35791. };
  35792. /**
  35793. * std140 layout specifies how to align data within an UBO structure.
  35794. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35795. * for specs.
  35796. */
  35797. UniformBuffer.prototype._fillAlignment = function (size) {
  35798. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35799. // and 4x4 matrices
  35800. // TODO : change if other types are used
  35801. var alignment;
  35802. if (size <= 2) {
  35803. alignment = size;
  35804. }
  35805. else {
  35806. alignment = 4;
  35807. }
  35808. if ((this._uniformLocationPointer % alignment) !== 0) {
  35809. var oldPointer = this._uniformLocationPointer;
  35810. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35811. var diff = this._uniformLocationPointer - oldPointer;
  35812. for (var i = 0; i < diff; i++) {
  35813. this._data.push(0);
  35814. }
  35815. }
  35816. };
  35817. /**
  35818. * Adds an uniform in the buffer.
  35819. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35820. * for the layout to be correct !
  35821. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35822. * @param {number|number[]} size Data size, or data directly.
  35823. */
  35824. UniformBuffer.prototype.addUniform = function (name, size) {
  35825. if (this._noUBO) {
  35826. return;
  35827. }
  35828. if (this._uniformLocations[name] !== undefined) {
  35829. // Already existing uniform
  35830. return;
  35831. }
  35832. // This function must be called in the order of the shader layout !
  35833. // size can be the size of the uniform, or data directly
  35834. var data;
  35835. if (size instanceof Array) {
  35836. data = size;
  35837. size = data.length;
  35838. }
  35839. else {
  35840. size = size;
  35841. data = [];
  35842. // Fill with zeros
  35843. for (var i = 0; i < size; i++) {
  35844. data.push(0);
  35845. }
  35846. }
  35847. this._fillAlignment(size);
  35848. this._uniformSizes[name] = size;
  35849. this._uniformLocations[name] = this._uniformLocationPointer;
  35850. this._uniformLocationPointer += size;
  35851. for (var i = 0; i < size; i++) {
  35852. this._data.push(data[i]);
  35853. }
  35854. this._needSync = true;
  35855. };
  35856. /**
  35857. * Wrapper for addUniform.
  35858. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35859. * @param {Matrix} mat A 4x4 matrix.
  35860. */
  35861. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35862. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35863. };
  35864. /**
  35865. * Wrapper for addUniform.
  35866. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35867. * @param {number} x
  35868. * @param {number} y
  35869. */
  35870. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35871. var temp = [x, y];
  35872. this.addUniform(name, temp);
  35873. };
  35874. /**
  35875. * Wrapper for addUniform.
  35876. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35877. * @param {number} x
  35878. * @param {number} y
  35879. * @param {number} z
  35880. */
  35881. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35882. var temp = [x, y, z];
  35883. this.addUniform(name, temp);
  35884. };
  35885. /**
  35886. * Wrapper for addUniform.
  35887. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35888. * @param {Color3} color
  35889. */
  35890. UniformBuffer.prototype.addColor3 = function (name, color) {
  35891. var temp = new Array();
  35892. color.toArray(temp);
  35893. this.addUniform(name, temp);
  35894. };
  35895. /**
  35896. * Wrapper for addUniform.
  35897. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35898. * @param {Color3} color
  35899. * @param {number} alpha
  35900. */
  35901. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35902. var temp = new Array();
  35903. color.toArray(temp);
  35904. temp.push(alpha);
  35905. this.addUniform(name, temp);
  35906. };
  35907. /**
  35908. * Wrapper for addUniform.
  35909. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35910. * @param {Vector3} vector
  35911. */
  35912. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35913. var temp = new Array();
  35914. vector.toArray(temp);
  35915. this.addUniform(name, temp);
  35916. };
  35917. /**
  35918. * Wrapper for addUniform.
  35919. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35920. */
  35921. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35922. this.addUniform(name, 12);
  35923. };
  35924. /**
  35925. * Wrapper for addUniform.
  35926. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35927. */
  35928. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35929. this.addUniform(name, 8);
  35930. };
  35931. /**
  35932. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35933. */
  35934. UniformBuffer.prototype.create = function () {
  35935. if (this._noUBO) {
  35936. return;
  35937. }
  35938. if (this._buffer) {
  35939. return; // nothing to do
  35940. }
  35941. // See spec, alignment must be filled as a vec4
  35942. this._fillAlignment(4);
  35943. this._bufferData = new Float32Array(this._data);
  35944. this._rebuild();
  35945. this._needSync = true;
  35946. };
  35947. UniformBuffer.prototype._rebuild = function () {
  35948. if (this._noUBO) {
  35949. return;
  35950. }
  35951. if (this._dynamic) {
  35952. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35953. }
  35954. else {
  35955. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35956. }
  35957. };
  35958. /**
  35959. * Updates the WebGL Uniform Buffer on the GPU.
  35960. * If the `dynamic` flag is set to true, no cache comparison is done.
  35961. * Otherwise, the buffer will be updated only if the cache differs.
  35962. */
  35963. UniformBuffer.prototype.update = function () {
  35964. if (!this._buffer) {
  35965. this.create();
  35966. return;
  35967. }
  35968. if (!this._dynamic && !this._needSync) {
  35969. return;
  35970. }
  35971. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35972. this._needSync = false;
  35973. };
  35974. /**
  35975. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35976. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35977. * @param {number[]|Float32Array} data Flattened data
  35978. * @param {number} size Size of the data.
  35979. */
  35980. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35981. var location = this._uniformLocations[uniformName];
  35982. if (location === undefined) {
  35983. if (this._buffer) {
  35984. // Cannot add an uniform if the buffer is already created
  35985. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35986. return;
  35987. }
  35988. this.addUniform(uniformName, size);
  35989. location = this._uniformLocations[uniformName];
  35990. }
  35991. if (!this._buffer) {
  35992. this.create();
  35993. }
  35994. if (!this._dynamic) {
  35995. // Cache for static uniform buffers
  35996. var changed = false;
  35997. for (var i = 0; i < size; i++) {
  35998. if (this._bufferData[location + i] !== data[i]) {
  35999. changed = true;
  36000. this._bufferData[location + i] = data[i];
  36001. }
  36002. }
  36003. this._needSync = this._needSync || changed;
  36004. }
  36005. else {
  36006. // No cache for dynamic
  36007. for (var i = 0; i < size; i++) {
  36008. this._bufferData[location + i] = data[i];
  36009. }
  36010. }
  36011. };
  36012. // Update methods
  36013. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36014. // To match std140, matrix must be realigned
  36015. for (var i = 0; i < 3; i++) {
  36016. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36017. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36018. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36019. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36020. }
  36021. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36022. };
  36023. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36024. this._currentEffect.setMatrix3x3(name, matrix);
  36025. };
  36026. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36027. this._currentEffect.setMatrix2x2(name, matrix);
  36028. };
  36029. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36030. // To match std140, matrix must be realigned
  36031. for (var i = 0; i < 2; i++) {
  36032. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36033. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36034. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36035. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36036. }
  36037. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36038. };
  36039. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36040. this._currentEffect.setFloat(name, x);
  36041. };
  36042. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36043. UniformBuffer._tempBuffer[0] = x;
  36044. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36045. };
  36046. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36047. if (suffix === void 0) { suffix = ""; }
  36048. this._currentEffect.setFloat2(name + suffix, x, y);
  36049. };
  36050. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36051. if (suffix === void 0) { suffix = ""; }
  36052. UniformBuffer._tempBuffer[0] = x;
  36053. UniformBuffer._tempBuffer[1] = y;
  36054. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36055. };
  36056. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36057. if (suffix === void 0) { suffix = ""; }
  36058. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36059. };
  36060. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36061. if (suffix === void 0) { suffix = ""; }
  36062. UniformBuffer._tempBuffer[0] = x;
  36063. UniformBuffer._tempBuffer[1] = y;
  36064. UniformBuffer._tempBuffer[2] = z;
  36065. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36066. };
  36067. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36068. if (suffix === void 0) { suffix = ""; }
  36069. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36070. };
  36071. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36072. if (suffix === void 0) { suffix = ""; }
  36073. UniformBuffer._tempBuffer[0] = x;
  36074. UniformBuffer._tempBuffer[1] = y;
  36075. UniformBuffer._tempBuffer[2] = z;
  36076. UniformBuffer._tempBuffer[3] = w;
  36077. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36078. };
  36079. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36080. this._currentEffect.setMatrix(name, mat);
  36081. };
  36082. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36083. this.updateUniform(name, mat.toArray(), 16);
  36084. };
  36085. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36086. this._currentEffect.setVector3(name, vector);
  36087. };
  36088. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36089. vector.toArray(UniformBuffer._tempBuffer);
  36090. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36091. };
  36092. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36093. this._currentEffect.setVector4(name, vector);
  36094. };
  36095. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36096. vector.toArray(UniformBuffer._tempBuffer);
  36097. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36098. };
  36099. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36100. if (suffix === void 0) { suffix = ""; }
  36101. this._currentEffect.setColor3(name + suffix, color);
  36102. };
  36103. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36104. if (suffix === void 0) { suffix = ""; }
  36105. color.toArray(UniformBuffer._tempBuffer);
  36106. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36107. };
  36108. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36109. if (suffix === void 0) { suffix = ""; }
  36110. this._currentEffect.setColor4(name + suffix, color, alpha);
  36111. };
  36112. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36113. if (suffix === void 0) { suffix = ""; }
  36114. color.toArray(UniformBuffer._tempBuffer);
  36115. UniformBuffer._tempBuffer[3] = alpha;
  36116. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36117. };
  36118. /**
  36119. * Sets a sampler uniform on the effect.
  36120. * @param {string} name Name of the sampler.
  36121. * @param {Texture} texture
  36122. */
  36123. UniformBuffer.prototype.setTexture = function (name, texture) {
  36124. this._currentEffect.setTexture(name, texture);
  36125. };
  36126. /**
  36127. * Directly updates the value of the uniform in the cache AND on the GPU.
  36128. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36129. * @param {number[]|Float32Array} data Flattened data
  36130. */
  36131. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36132. this.updateUniform(uniformName, data, data.length);
  36133. this.update();
  36134. };
  36135. /**
  36136. * Binds this uniform buffer to an effect.
  36137. * @param {Effect} effect
  36138. * @param {string} name Name of the uniform block in the shader.
  36139. */
  36140. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36141. this._currentEffect = effect;
  36142. if (this._noUBO || !this._buffer) {
  36143. return;
  36144. }
  36145. effect.bindUniformBuffer(this._buffer, name);
  36146. };
  36147. /**
  36148. * Disposes the uniform buffer.
  36149. */
  36150. UniformBuffer.prototype.dispose = function () {
  36151. if (this._noUBO) {
  36152. return;
  36153. }
  36154. var index = this._engine._uniformBuffers.indexOf(this);
  36155. if (index !== -1) {
  36156. this._engine._uniformBuffers.splice(index, 1);
  36157. }
  36158. if (!this._buffer) {
  36159. return;
  36160. }
  36161. if (this._engine._releaseBuffer(this._buffer)) {
  36162. this._buffer = null;
  36163. }
  36164. };
  36165. // Pool for avoiding memory leaks
  36166. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36167. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36168. return UniformBuffer;
  36169. }());
  36170. BABYLON.UniformBuffer = UniformBuffer;
  36171. })(BABYLON || (BABYLON = {}));
  36172. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36173. var BABYLON;
  36174. (function (BABYLON) {
  36175. /**
  36176. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36177. */
  36178. var VertexData = /** @class */ (function () {
  36179. function VertexData() {
  36180. }
  36181. /**
  36182. * Uses the passed data array to set the set the values for the specified kind of data
  36183. * @param data a linear array of floating numbers
  36184. * @param kind the type of data that is being set, eg positions, colors etc
  36185. */
  36186. VertexData.prototype.set = function (data, kind) {
  36187. switch (kind) {
  36188. case BABYLON.VertexBuffer.PositionKind:
  36189. this.positions = data;
  36190. break;
  36191. case BABYLON.VertexBuffer.NormalKind:
  36192. this.normals = data;
  36193. break;
  36194. case BABYLON.VertexBuffer.TangentKind:
  36195. this.tangents = data;
  36196. break;
  36197. case BABYLON.VertexBuffer.UVKind:
  36198. this.uvs = data;
  36199. break;
  36200. case BABYLON.VertexBuffer.UV2Kind:
  36201. this.uvs2 = data;
  36202. break;
  36203. case BABYLON.VertexBuffer.UV3Kind:
  36204. this.uvs3 = data;
  36205. break;
  36206. case BABYLON.VertexBuffer.UV4Kind:
  36207. this.uvs4 = data;
  36208. break;
  36209. case BABYLON.VertexBuffer.UV5Kind:
  36210. this.uvs5 = data;
  36211. break;
  36212. case BABYLON.VertexBuffer.UV6Kind:
  36213. this.uvs6 = data;
  36214. break;
  36215. case BABYLON.VertexBuffer.ColorKind:
  36216. this.colors = data;
  36217. break;
  36218. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36219. this.matricesIndices = data;
  36220. break;
  36221. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36222. this.matricesWeights = data;
  36223. break;
  36224. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36225. this.matricesIndicesExtra = data;
  36226. break;
  36227. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36228. this.matricesWeightsExtra = data;
  36229. break;
  36230. }
  36231. };
  36232. /**
  36233. * Associates the vertexData to the passed Mesh.
  36234. * Sets it as updatable or not (default `false`)
  36235. * @param mesh the mesh the vertexData is applied to
  36236. * @param updatable when used and having the value true allows new data to update the vertexData
  36237. * @returns the VertexData
  36238. */
  36239. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36240. this._applyTo(mesh, updatable);
  36241. return this;
  36242. };
  36243. /**
  36244. * Associates the vertexData to the passed Geometry.
  36245. * Sets it as updatable or not (default `false`)
  36246. * @param geometry the geometry the vertexData is applied to
  36247. * @param updatable when used and having the value true allows new data to update the vertexData
  36248. * @returns VertexData
  36249. */
  36250. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36251. this._applyTo(geometry, updatable);
  36252. return this;
  36253. };
  36254. /**
  36255. * Updates the associated mesh
  36256. * @param mesh the mesh to be updated
  36257. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36258. * @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
  36259. * @returns VertexData
  36260. */
  36261. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36262. this._update(mesh);
  36263. return this;
  36264. };
  36265. /**
  36266. * Updates the associated geometry
  36267. * @param geometry the geometry to be updated
  36268. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36269. * @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
  36270. * @returns VertexData.
  36271. */
  36272. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36273. this._update(geometry);
  36274. return this;
  36275. };
  36276. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36277. if (updatable === void 0) { updatable = false; }
  36278. if (this.positions) {
  36279. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36280. }
  36281. if (this.normals) {
  36282. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36283. }
  36284. if (this.tangents) {
  36285. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36286. }
  36287. if (this.uvs) {
  36288. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36289. }
  36290. if (this.uvs2) {
  36291. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36292. }
  36293. if (this.uvs3) {
  36294. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36295. }
  36296. if (this.uvs4) {
  36297. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36298. }
  36299. if (this.uvs5) {
  36300. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36301. }
  36302. if (this.uvs6) {
  36303. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36304. }
  36305. if (this.colors) {
  36306. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36307. }
  36308. if (this.matricesIndices) {
  36309. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36310. }
  36311. if (this.matricesWeights) {
  36312. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36313. }
  36314. if (this.matricesIndicesExtra) {
  36315. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36316. }
  36317. if (this.matricesWeightsExtra) {
  36318. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36319. }
  36320. if (this.indices) {
  36321. meshOrGeometry.setIndices(this.indices, null, updatable);
  36322. }
  36323. else {
  36324. meshOrGeometry.setIndices([], null);
  36325. }
  36326. return this;
  36327. };
  36328. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36329. if (this.positions) {
  36330. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36331. }
  36332. if (this.normals) {
  36333. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36334. }
  36335. if (this.tangents) {
  36336. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36337. }
  36338. if (this.uvs) {
  36339. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36340. }
  36341. if (this.uvs2) {
  36342. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36343. }
  36344. if (this.uvs3) {
  36345. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36346. }
  36347. if (this.uvs4) {
  36348. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36349. }
  36350. if (this.uvs5) {
  36351. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36352. }
  36353. if (this.uvs6) {
  36354. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36355. }
  36356. if (this.colors) {
  36357. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36358. }
  36359. if (this.matricesIndices) {
  36360. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36361. }
  36362. if (this.matricesWeights) {
  36363. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36364. }
  36365. if (this.matricesIndicesExtra) {
  36366. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36367. }
  36368. if (this.matricesWeightsExtra) {
  36369. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36370. }
  36371. if (this.indices) {
  36372. meshOrGeometry.setIndices(this.indices, null);
  36373. }
  36374. return this;
  36375. };
  36376. /**
  36377. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36378. * @param matrix the transforming matrix
  36379. * @returns the VertexData
  36380. */
  36381. VertexData.prototype.transform = function (matrix) {
  36382. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36383. var transformed = BABYLON.Vector3.Zero();
  36384. var index;
  36385. if (this.positions) {
  36386. var position = BABYLON.Vector3.Zero();
  36387. for (index = 0; index < this.positions.length; index += 3) {
  36388. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36389. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36390. this.positions[index] = transformed.x;
  36391. this.positions[index + 1] = transformed.y;
  36392. this.positions[index + 2] = transformed.z;
  36393. }
  36394. }
  36395. if (this.normals) {
  36396. var normal = BABYLON.Vector3.Zero();
  36397. for (index = 0; index < this.normals.length; index += 3) {
  36398. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36399. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36400. this.normals[index] = transformed.x;
  36401. this.normals[index + 1] = transformed.y;
  36402. this.normals[index + 2] = transformed.z;
  36403. }
  36404. }
  36405. if (this.tangents) {
  36406. var tangent = BABYLON.Vector4.Zero();
  36407. var tangentTransformed = BABYLON.Vector4.Zero();
  36408. for (index = 0; index < this.tangents.length; index += 4) {
  36409. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36410. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36411. this.tangents[index] = tangentTransformed.x;
  36412. this.tangents[index + 1] = tangentTransformed.y;
  36413. this.tangents[index + 2] = tangentTransformed.z;
  36414. this.tangents[index + 3] = tangentTransformed.w;
  36415. }
  36416. }
  36417. if (flip && this.indices) {
  36418. for (index = 0; index < this.indices.length; index += 3) {
  36419. var tmp = this.indices[index + 1];
  36420. this.indices[index + 1] = this.indices[index + 2];
  36421. this.indices[index + 2] = tmp;
  36422. }
  36423. }
  36424. return this;
  36425. };
  36426. /**
  36427. * Merges the passed VertexData into the current one
  36428. * @param other the VertexData to be merged into the current one
  36429. * @returns the modified VertexData
  36430. */
  36431. VertexData.prototype.merge = function (other) {
  36432. this._validate();
  36433. other._validate();
  36434. if (!this.normals !== !other.normals ||
  36435. !this.tangents !== !other.tangents ||
  36436. !this.uvs !== !other.uvs ||
  36437. !this.uvs2 !== !other.uvs2 ||
  36438. !this.uvs3 !== !other.uvs3 ||
  36439. !this.uvs4 !== !other.uvs4 ||
  36440. !this.uvs5 !== !other.uvs5 ||
  36441. !this.uvs6 !== !other.uvs6 ||
  36442. !this.colors !== !other.colors ||
  36443. !this.matricesIndices !== !other.matricesIndices ||
  36444. !this.matricesWeights !== !other.matricesWeights ||
  36445. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36446. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36447. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36448. }
  36449. if (other.indices) {
  36450. if (!this.indices) {
  36451. this.indices = [];
  36452. }
  36453. var offset = this.positions ? this.positions.length / 3 : 0;
  36454. for (var index = 0; index < other.indices.length; index++) {
  36455. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36456. this.indices.push(other.indices[index] + offset);
  36457. }
  36458. }
  36459. this.positions = this._mergeElement(this.positions, other.positions);
  36460. this.normals = this._mergeElement(this.normals, other.normals);
  36461. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36462. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36463. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36464. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36465. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36466. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36467. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36468. this.colors = this._mergeElement(this.colors, other.colors);
  36469. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36470. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36471. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36472. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36473. return this;
  36474. };
  36475. VertexData.prototype._mergeElement = function (source, other) {
  36476. if (!source) {
  36477. return other;
  36478. }
  36479. if (!other) {
  36480. return source;
  36481. }
  36482. var len = other.length + source.length;
  36483. var isSrcTypedArray = source instanceof Float32Array;
  36484. var isOthTypedArray = other instanceof Float32Array;
  36485. // use non-loop method when the source is Float32Array
  36486. if (isSrcTypedArray) {
  36487. var ret32 = new Float32Array(len);
  36488. ret32.set(source);
  36489. ret32.set(other, source.length);
  36490. return ret32;
  36491. // source is number[], when other is also use concat
  36492. }
  36493. else if (!isOthTypedArray) {
  36494. return source.concat(other);
  36495. // source is a number[], but other is a Float32Array, loop required
  36496. }
  36497. else {
  36498. var ret = source.slice(0); // copy source to a separate array
  36499. for (var i = 0, len = other.length; i < len; i++) {
  36500. ret.push(other[i]);
  36501. }
  36502. return ret;
  36503. }
  36504. };
  36505. VertexData.prototype._validate = function () {
  36506. if (!this.positions) {
  36507. throw new Error("Positions are required");
  36508. }
  36509. var getElementCount = function (kind, values) {
  36510. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36511. if ((values.length % stride) !== 0) {
  36512. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36513. }
  36514. return values.length / stride;
  36515. };
  36516. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36517. var validateElementCount = function (kind, values) {
  36518. var elementCount = getElementCount(kind, values);
  36519. if (elementCount !== positionsElementCount) {
  36520. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36521. }
  36522. };
  36523. if (this.normals)
  36524. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36525. if (this.tangents)
  36526. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36527. if (this.uvs)
  36528. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36529. if (this.uvs2)
  36530. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36531. if (this.uvs3)
  36532. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36533. if (this.uvs4)
  36534. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36535. if (this.uvs5)
  36536. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36537. if (this.uvs6)
  36538. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36539. if (this.colors)
  36540. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36541. if (this.matricesIndices)
  36542. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36543. if (this.matricesWeights)
  36544. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36545. if (this.matricesIndicesExtra)
  36546. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36547. if (this.matricesWeightsExtra)
  36548. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36549. };
  36550. /**
  36551. * Serializes the VertexData
  36552. * @returns a serialized object
  36553. */
  36554. VertexData.prototype.serialize = function () {
  36555. var serializationObject = this.serialize();
  36556. if (this.positions) {
  36557. serializationObject.positions = this.positions;
  36558. }
  36559. if (this.normals) {
  36560. serializationObject.normals = this.normals;
  36561. }
  36562. if (this.tangents) {
  36563. serializationObject.tangents = this.tangents;
  36564. }
  36565. if (this.uvs) {
  36566. serializationObject.uvs = this.uvs;
  36567. }
  36568. if (this.uvs2) {
  36569. serializationObject.uvs2 = this.uvs2;
  36570. }
  36571. if (this.uvs3) {
  36572. serializationObject.uvs3 = this.uvs3;
  36573. }
  36574. if (this.uvs4) {
  36575. serializationObject.uvs4 = this.uvs4;
  36576. }
  36577. if (this.uvs5) {
  36578. serializationObject.uvs5 = this.uvs5;
  36579. }
  36580. if (this.uvs6) {
  36581. serializationObject.uvs6 = this.uvs6;
  36582. }
  36583. if (this.colors) {
  36584. serializationObject.colors = this.colors;
  36585. }
  36586. if (this.matricesIndices) {
  36587. serializationObject.matricesIndices = this.matricesIndices;
  36588. serializationObject.matricesIndices._isExpanded = true;
  36589. }
  36590. if (this.matricesWeights) {
  36591. serializationObject.matricesWeights = this.matricesWeights;
  36592. }
  36593. if (this.matricesIndicesExtra) {
  36594. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36595. serializationObject.matricesIndicesExtra._isExpanded = true;
  36596. }
  36597. if (this.matricesWeightsExtra) {
  36598. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36599. }
  36600. serializationObject.indices = this.indices;
  36601. return serializationObject;
  36602. };
  36603. // Statics
  36604. /**
  36605. * Extracts the vertexData from a mesh
  36606. * @param mesh the mesh from which to extract the VertexData
  36607. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36608. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36609. * @returns the object VertexData associated to the passed mesh
  36610. */
  36611. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36612. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36613. };
  36614. /**
  36615. * Extracts the vertexData from the geometry
  36616. * @param geometry the geometry from which to extract the VertexData
  36617. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36618. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36619. * @returns the object VertexData associated to the passed mesh
  36620. */
  36621. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36622. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36623. };
  36624. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36625. var result = new VertexData();
  36626. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36627. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36628. }
  36629. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36630. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36631. }
  36632. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36633. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36634. }
  36635. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36636. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36637. }
  36638. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36639. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36640. }
  36641. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36642. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36643. }
  36644. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36645. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36646. }
  36647. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36648. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36649. }
  36650. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36651. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36652. }
  36653. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36654. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36655. }
  36656. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36657. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36658. }
  36659. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36660. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36661. }
  36662. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36663. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36664. }
  36665. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36666. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36667. }
  36668. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36669. return result;
  36670. };
  36671. /**
  36672. * Creates the VertexData for a Ribbon
  36673. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36674. * * pathArray array of paths, each of which an array of successive Vector3
  36675. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36676. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36677. * * 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
  36678. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36679. * * 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)
  36680. * * 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)
  36681. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36682. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36683. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36684. * @returns the VertexData of the ribbon
  36685. */
  36686. VertexData.CreateRibbon = function (options) {
  36687. var pathArray = options.pathArray;
  36688. var closeArray = options.closeArray || false;
  36689. var closePath = options.closePath || false;
  36690. var invertUV = options.invertUV || false;
  36691. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36692. var offset = options.offset || defaultOffset;
  36693. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36694. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36695. var customUV = options.uvs;
  36696. var customColors = options.colors;
  36697. var positions = [];
  36698. var indices = [];
  36699. var normals = [];
  36700. var uvs = [];
  36701. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36702. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36703. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36704. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36705. var minlg; // minimal length among all paths from pathArray
  36706. var lg = []; // array of path lengths : nb of vertex per path
  36707. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36708. var p; // path iterator
  36709. var i; // point iterator
  36710. var j; // point iterator
  36711. // if single path in pathArray
  36712. if (pathArray.length < 2) {
  36713. var ar1 = [];
  36714. var ar2 = [];
  36715. for (i = 0; i < pathArray[0].length - offset; i++) {
  36716. ar1.push(pathArray[0][i]);
  36717. ar2.push(pathArray[0][i + offset]);
  36718. }
  36719. pathArray = [ar1, ar2];
  36720. }
  36721. // positions and horizontal distances (u)
  36722. var idc = 0;
  36723. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36724. var path;
  36725. var l;
  36726. minlg = pathArray[0].length;
  36727. var vectlg;
  36728. var dist;
  36729. for (p = 0; p < pathArray.length; p++) {
  36730. uTotalDistance[p] = 0;
  36731. us[p] = [0];
  36732. path = pathArray[p];
  36733. l = path.length;
  36734. minlg = (minlg < l) ? minlg : l;
  36735. j = 0;
  36736. while (j < l) {
  36737. positions.push(path[j].x, path[j].y, path[j].z);
  36738. if (j > 0) {
  36739. vectlg = path[j].subtract(path[j - 1]).length();
  36740. dist = vectlg + uTotalDistance[p];
  36741. us[p].push(dist);
  36742. uTotalDistance[p] = dist;
  36743. }
  36744. j++;
  36745. }
  36746. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36747. j--;
  36748. positions.push(path[0].x, path[0].y, path[0].z);
  36749. vectlg = path[j].subtract(path[0]).length();
  36750. dist = vectlg + uTotalDistance[p];
  36751. us[p].push(dist);
  36752. uTotalDistance[p] = dist;
  36753. }
  36754. lg[p] = l + closePathCorr;
  36755. idx[p] = idc;
  36756. idc += (l + closePathCorr);
  36757. }
  36758. // vertical distances (v)
  36759. var path1;
  36760. var path2;
  36761. var vertex1 = null;
  36762. var vertex2 = null;
  36763. for (i = 0; i < minlg + closePathCorr; i++) {
  36764. vTotalDistance[i] = 0;
  36765. vs[i] = [0];
  36766. for (p = 0; p < pathArray.length - 1; p++) {
  36767. path1 = pathArray[p];
  36768. path2 = pathArray[p + 1];
  36769. if (i === minlg) { // closePath
  36770. vertex1 = path1[0];
  36771. vertex2 = path2[0];
  36772. }
  36773. else {
  36774. vertex1 = path1[i];
  36775. vertex2 = path2[i];
  36776. }
  36777. vectlg = vertex2.subtract(vertex1).length();
  36778. dist = vectlg + vTotalDistance[i];
  36779. vs[i].push(dist);
  36780. vTotalDistance[i] = dist;
  36781. }
  36782. if (closeArray && vertex2 && vertex1) {
  36783. path1 = pathArray[p];
  36784. path2 = pathArray[0];
  36785. if (i === minlg) { // closePath
  36786. vertex2 = path2[0];
  36787. }
  36788. vectlg = vertex2.subtract(vertex1).length();
  36789. dist = vectlg + vTotalDistance[i];
  36790. vTotalDistance[i] = dist;
  36791. }
  36792. }
  36793. // uvs
  36794. var u;
  36795. var v;
  36796. if (customUV) {
  36797. for (p = 0; p < customUV.length; p++) {
  36798. uvs.push(customUV[p].x, customUV[p].y);
  36799. }
  36800. }
  36801. else {
  36802. for (p = 0; p < pathArray.length; p++) {
  36803. for (i = 0; i < minlg + closePathCorr; i++) {
  36804. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36805. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36806. if (invertUV) {
  36807. uvs.push(v, u);
  36808. }
  36809. else {
  36810. uvs.push(u, v);
  36811. }
  36812. }
  36813. }
  36814. }
  36815. // indices
  36816. p = 0; // path index
  36817. var pi = 0; // positions array index
  36818. var l1 = lg[p] - 1; // path1 length
  36819. var l2 = lg[p + 1] - 1; // path2 length
  36820. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36821. var shft = idx[1] - idx[0]; // shift
  36822. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36823. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36824. // 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
  36825. indices.push(pi, pi + shft, pi + 1);
  36826. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36827. pi += 1;
  36828. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36829. p++;
  36830. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36831. shft = idx[0] - idx[p];
  36832. l1 = lg[p] - 1;
  36833. l2 = lg[0] - 1;
  36834. }
  36835. else {
  36836. shft = idx[p + 1] - idx[p];
  36837. l1 = lg[p] - 1;
  36838. l2 = lg[p + 1] - 1;
  36839. }
  36840. pi = idx[p];
  36841. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36842. }
  36843. }
  36844. // normals
  36845. VertexData.ComputeNormals(positions, indices, normals);
  36846. if (closePath) { // update both the first and last vertex normals to their average value
  36847. var indexFirst = 0;
  36848. var indexLast = 0;
  36849. for (p = 0; p < pathArray.length; p++) {
  36850. indexFirst = idx[p] * 3;
  36851. if (p + 1 < pathArray.length) {
  36852. indexLast = (idx[p + 1] - 1) * 3;
  36853. }
  36854. else {
  36855. indexLast = normals.length - 3;
  36856. }
  36857. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36858. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36859. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36860. normals[indexLast] = normals[indexFirst];
  36861. normals[indexLast + 1] = normals[indexFirst + 1];
  36862. normals[indexLast + 2] = normals[indexFirst + 2];
  36863. }
  36864. }
  36865. // sides
  36866. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36867. // Colors
  36868. var colors = null;
  36869. if (customColors) {
  36870. colors = new Float32Array(customColors.length * 4);
  36871. for (var c = 0; c < customColors.length; c++) {
  36872. colors[c * 4] = customColors[c].r;
  36873. colors[c * 4 + 1] = customColors[c].g;
  36874. colors[c * 4 + 2] = customColors[c].b;
  36875. colors[c * 4 + 3] = customColors[c].a;
  36876. }
  36877. }
  36878. // Result
  36879. var vertexData = new VertexData();
  36880. var positions32 = new Float32Array(positions);
  36881. var normals32 = new Float32Array(normals);
  36882. var uvs32 = new Float32Array(uvs);
  36883. vertexData.indices = indices;
  36884. vertexData.positions = positions32;
  36885. vertexData.normals = normals32;
  36886. vertexData.uvs = uvs32;
  36887. if (colors) {
  36888. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36889. }
  36890. if (closePath) {
  36891. vertexData._idx = idx;
  36892. }
  36893. return vertexData;
  36894. };
  36895. /**
  36896. * Creates the VertexData for a box
  36897. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36898. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36899. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36900. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36901. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36902. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36903. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36904. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36905. * * 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)
  36906. * * 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)
  36907. * @returns the VertexData of the box
  36908. */
  36909. VertexData.CreateBox = function (options) {
  36910. var normalsSource = [
  36911. new BABYLON.Vector3(0, 0, 1),
  36912. new BABYLON.Vector3(0, 0, -1),
  36913. new BABYLON.Vector3(1, 0, 0),
  36914. new BABYLON.Vector3(-1, 0, 0),
  36915. new BABYLON.Vector3(0, 1, 0),
  36916. new BABYLON.Vector3(0, -1, 0)
  36917. ];
  36918. var indices = [];
  36919. var positions = [];
  36920. var normals = [];
  36921. var uvs = [];
  36922. var width = options.width || options.size || 1;
  36923. var height = options.height || options.size || 1;
  36924. var depth = options.depth || options.size || 1;
  36925. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36926. var faceUV = options.faceUV || new Array(6);
  36927. var faceColors = options.faceColors;
  36928. var colors = [];
  36929. // default face colors and UV if undefined
  36930. for (var f = 0; f < 6; f++) {
  36931. if (faceUV[f] === undefined) {
  36932. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36933. }
  36934. if (faceColors && faceColors[f] === undefined) {
  36935. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36936. }
  36937. }
  36938. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36939. // Create each face in turn.
  36940. for (var index = 0; index < normalsSource.length; index++) {
  36941. var normal = normalsSource[index];
  36942. // Get two vectors perpendicular to the face normal and to each other.
  36943. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36944. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36945. // Six indices (two triangles) per face.
  36946. var verticesLength = positions.length / 3;
  36947. indices.push(verticesLength);
  36948. indices.push(verticesLength + 1);
  36949. indices.push(verticesLength + 2);
  36950. indices.push(verticesLength);
  36951. indices.push(verticesLength + 2);
  36952. indices.push(verticesLength + 3);
  36953. // Four vertices per face.
  36954. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36955. positions.push(vertex.x, vertex.y, vertex.z);
  36956. normals.push(normal.x, normal.y, normal.z);
  36957. uvs.push(faceUV[index].z, faceUV[index].w);
  36958. if (faceColors) {
  36959. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36960. }
  36961. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36962. positions.push(vertex.x, vertex.y, vertex.z);
  36963. normals.push(normal.x, normal.y, normal.z);
  36964. uvs.push(faceUV[index].x, faceUV[index].w);
  36965. if (faceColors) {
  36966. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36967. }
  36968. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36969. positions.push(vertex.x, vertex.y, vertex.z);
  36970. normals.push(normal.x, normal.y, normal.z);
  36971. uvs.push(faceUV[index].x, faceUV[index].y);
  36972. if (faceColors) {
  36973. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36974. }
  36975. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36976. positions.push(vertex.x, vertex.y, vertex.z);
  36977. normals.push(normal.x, normal.y, normal.z);
  36978. uvs.push(faceUV[index].z, faceUV[index].y);
  36979. if (faceColors) {
  36980. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36981. }
  36982. }
  36983. // sides
  36984. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36985. // Result
  36986. var vertexData = new VertexData();
  36987. vertexData.indices = indices;
  36988. vertexData.positions = positions;
  36989. vertexData.normals = normals;
  36990. vertexData.uvs = uvs;
  36991. if (faceColors) {
  36992. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36993. vertexData.colors = totalColors;
  36994. }
  36995. return vertexData;
  36996. };
  36997. /**
  36998. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36999. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37000. * * segments sets the number of horizontal strips optional, default 32
  37001. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37002. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37003. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37004. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37005. * * 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
  37006. * * 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
  37007. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37008. * * 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)
  37009. * * 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)
  37010. * @returns the VertexData of the ellipsoid
  37011. */
  37012. VertexData.CreateSphere = function (options) {
  37013. var segments = options.segments || 32;
  37014. var diameterX = options.diameterX || options.diameter || 1;
  37015. var diameterY = options.diameterY || options.diameter || 1;
  37016. var diameterZ = options.diameterZ || options.diameter || 1;
  37017. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37018. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37019. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37020. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37021. var totalZRotationSteps = 2 + segments;
  37022. var totalYRotationSteps = 2 * totalZRotationSteps;
  37023. var indices = [];
  37024. var positions = [];
  37025. var normals = [];
  37026. var uvs = [];
  37027. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37028. var normalizedZ = zRotationStep / totalZRotationSteps;
  37029. var angleZ = normalizedZ * Math.PI * slice;
  37030. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37031. var normalizedY = yRotationStep / totalYRotationSteps;
  37032. var angleY = normalizedY * Math.PI * 2 * arc;
  37033. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37034. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37035. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37036. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37037. var vertex = complete.multiply(radius);
  37038. var normal = complete.divide(radius).normalize();
  37039. positions.push(vertex.x, vertex.y, vertex.z);
  37040. normals.push(normal.x, normal.y, normal.z);
  37041. uvs.push(normalizedY, normalizedZ);
  37042. }
  37043. if (zRotationStep > 0) {
  37044. var verticesCount = positions.length / 3;
  37045. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37046. indices.push((firstIndex));
  37047. indices.push((firstIndex + 1));
  37048. indices.push(firstIndex + totalYRotationSteps + 1);
  37049. indices.push((firstIndex + totalYRotationSteps + 1));
  37050. indices.push((firstIndex + 1));
  37051. indices.push((firstIndex + totalYRotationSteps + 2));
  37052. }
  37053. }
  37054. }
  37055. // Sides
  37056. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37057. // Result
  37058. var vertexData = new VertexData();
  37059. vertexData.indices = indices;
  37060. vertexData.positions = positions;
  37061. vertexData.normals = normals;
  37062. vertexData.uvs = uvs;
  37063. return vertexData;
  37064. };
  37065. /**
  37066. * Creates the VertexData for a cylinder, cone or prism
  37067. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37068. * * height sets the height (y direction) of the cylinder, optional, default 2
  37069. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37070. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37071. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37072. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37073. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37074. * * 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
  37075. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37076. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37077. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37078. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37079. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37080. * * 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)
  37081. * * 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)
  37082. * @returns the VertexData of the cylinder, cone or prism
  37083. */
  37084. VertexData.CreateCylinder = function (options) {
  37085. var height = options.height || 2;
  37086. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37087. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37088. var tessellation = options.tessellation || 24;
  37089. var subdivisions = options.subdivisions || 1;
  37090. var hasRings = options.hasRings ? true : false;
  37091. var enclose = options.enclose ? true : false;
  37092. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37093. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37094. var faceUV = options.faceUV || new Array(3);
  37095. var faceColors = options.faceColors;
  37096. // default face colors and UV if undefined
  37097. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37098. var ringNb = (hasRings) ? subdivisions : 1;
  37099. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37100. var f;
  37101. for (f = 0; f < surfaceNb; f++) {
  37102. if (faceColors && faceColors[f] === undefined) {
  37103. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37104. }
  37105. }
  37106. for (f = 0; f < surfaceNb; f++) {
  37107. if (faceUV && faceUV[f] === undefined) {
  37108. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37109. }
  37110. }
  37111. var indices = new Array();
  37112. var positions = new Array();
  37113. var normals = new Array();
  37114. var uvs = new Array();
  37115. var colors = new Array();
  37116. var angle_step = Math.PI * 2 * arc / tessellation;
  37117. var angle;
  37118. var h;
  37119. var radius;
  37120. var tan = (diameterBottom - diameterTop) / 2 / height;
  37121. var ringVertex = BABYLON.Vector3.Zero();
  37122. var ringNormal = BABYLON.Vector3.Zero();
  37123. var ringFirstVertex = BABYLON.Vector3.Zero();
  37124. var ringFirstNormal = BABYLON.Vector3.Zero();
  37125. var quadNormal = BABYLON.Vector3.Zero();
  37126. var Y = BABYLON.Axis.Y;
  37127. // positions, normals, uvs
  37128. var i;
  37129. var j;
  37130. var r;
  37131. var ringIdx = 1;
  37132. var s = 1; // surface index
  37133. var cs = 0;
  37134. var v = 0;
  37135. for (i = 0; i <= subdivisions; i++) {
  37136. h = i / subdivisions;
  37137. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37138. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37139. for (r = 0; r < ringIdx; r++) {
  37140. if (hasRings) {
  37141. s += r;
  37142. }
  37143. if (enclose) {
  37144. s += 2 * r;
  37145. }
  37146. for (j = 0; j <= tessellation; j++) {
  37147. angle = j * angle_step;
  37148. // position
  37149. ringVertex.x = Math.cos(-angle) * radius;
  37150. ringVertex.y = -height / 2 + h * height;
  37151. ringVertex.z = Math.sin(-angle) * radius;
  37152. // normal
  37153. if (diameterTop === 0 && i === subdivisions) {
  37154. // if no top cap, reuse former normals
  37155. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37156. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37157. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37158. }
  37159. else {
  37160. ringNormal.x = ringVertex.x;
  37161. ringNormal.z = ringVertex.z;
  37162. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37163. ringNormal.normalize();
  37164. }
  37165. // keep first ring vertex values for enclose
  37166. if (j === 0) {
  37167. ringFirstVertex.copyFrom(ringVertex);
  37168. ringFirstNormal.copyFrom(ringNormal);
  37169. }
  37170. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37171. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37172. if (hasRings) {
  37173. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37174. }
  37175. else {
  37176. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37177. }
  37178. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37179. if (faceColors) {
  37180. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37181. }
  37182. }
  37183. // if enclose, add four vertices and their dedicated normals
  37184. if (arc !== 1 && enclose) {
  37185. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37186. positions.push(0, ringVertex.y, 0);
  37187. positions.push(0, ringVertex.y, 0);
  37188. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37189. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37190. quadNormal.normalize();
  37191. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37192. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37193. quadNormal.normalize();
  37194. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37195. if (hasRings) {
  37196. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37197. }
  37198. else {
  37199. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37200. }
  37201. uvs.push(faceUV[s + 1].x, v);
  37202. uvs.push(faceUV[s + 1].z, v);
  37203. if (hasRings) {
  37204. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37205. }
  37206. else {
  37207. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37208. }
  37209. uvs.push(faceUV[s + 2].x, v);
  37210. uvs.push(faceUV[s + 2].z, v);
  37211. if (faceColors) {
  37212. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37213. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37214. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37215. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37216. }
  37217. }
  37218. if (cs !== s) {
  37219. cs = s;
  37220. }
  37221. }
  37222. }
  37223. // indices
  37224. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37225. var s;
  37226. i = 0;
  37227. for (s = 0; s < subdivisions; s++) {
  37228. var i0 = 0;
  37229. var i1 = 0;
  37230. var i2 = 0;
  37231. var i3 = 0;
  37232. for (j = 0; j < tessellation; j++) {
  37233. i0 = i * (e + 1) + j;
  37234. i1 = (i + 1) * (e + 1) + j;
  37235. i2 = i * (e + 1) + (j + 1);
  37236. i3 = (i + 1) * (e + 1) + (j + 1);
  37237. indices.push(i0, i1, i2);
  37238. indices.push(i3, i2, i1);
  37239. }
  37240. if (arc !== 1 && enclose) { // if enclose, add two quads
  37241. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37242. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37243. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37244. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37245. }
  37246. i = (hasRings) ? (i + 2) : (i + 1);
  37247. }
  37248. // Caps
  37249. var createCylinderCap = function (isTop) {
  37250. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37251. if (radius === 0) {
  37252. return;
  37253. }
  37254. // Cap positions, normals & uvs
  37255. var angle;
  37256. var circleVector;
  37257. var i;
  37258. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37259. var c = null;
  37260. if (faceColors) {
  37261. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37262. }
  37263. // cap center
  37264. var vbase = positions.length / 3;
  37265. var offset = isTop ? height / 2 : -height / 2;
  37266. var center = new BABYLON.Vector3(0, offset, 0);
  37267. positions.push(center.x, center.y, center.z);
  37268. normals.push(0, isTop ? 1 : -1, 0);
  37269. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37270. if (c) {
  37271. colors.push(c.r, c.g, c.b, c.a);
  37272. }
  37273. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37274. for (i = 0; i <= tessellation; i++) {
  37275. angle = Math.PI * 2 * i * arc / tessellation;
  37276. var cos = Math.cos(-angle);
  37277. var sin = Math.sin(-angle);
  37278. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37279. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37280. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37281. normals.push(0, isTop ? 1 : -1, 0);
  37282. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37283. if (c) {
  37284. colors.push(c.r, c.g, c.b, c.a);
  37285. }
  37286. }
  37287. // Cap indices
  37288. for (i = 0; i < tessellation; i++) {
  37289. if (!isTop) {
  37290. indices.push(vbase);
  37291. indices.push(vbase + (i + 1));
  37292. indices.push(vbase + (i + 2));
  37293. }
  37294. else {
  37295. indices.push(vbase);
  37296. indices.push(vbase + (i + 2));
  37297. indices.push(vbase + (i + 1));
  37298. }
  37299. }
  37300. };
  37301. // add caps to geometry
  37302. createCylinderCap(false);
  37303. createCylinderCap(true);
  37304. // Sides
  37305. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37306. var vertexData = new VertexData();
  37307. vertexData.indices = indices;
  37308. vertexData.positions = positions;
  37309. vertexData.normals = normals;
  37310. vertexData.uvs = uvs;
  37311. if (faceColors) {
  37312. vertexData.colors = colors;
  37313. }
  37314. return vertexData;
  37315. };
  37316. /**
  37317. * Creates the VertexData for a torus
  37318. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37319. * * diameter the diameter of the torus, optional default 1
  37320. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37321. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37322. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37323. * * 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)
  37324. * * 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)
  37325. * @returns the VertexData of the torus
  37326. */
  37327. VertexData.CreateTorus = function (options) {
  37328. var indices = [];
  37329. var positions = [];
  37330. var normals = [];
  37331. var uvs = [];
  37332. var diameter = options.diameter || 1;
  37333. var thickness = options.thickness || 0.5;
  37334. var tessellation = options.tessellation || 16;
  37335. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37336. var stride = tessellation + 1;
  37337. for (var i = 0; i <= tessellation; i++) {
  37338. var u = i / tessellation;
  37339. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37340. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37341. for (var j = 0; j <= tessellation; j++) {
  37342. var v = 1 - j / tessellation;
  37343. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37344. var dx = Math.cos(innerAngle);
  37345. var dy = Math.sin(innerAngle);
  37346. // Create a vertex.
  37347. var normal = new BABYLON.Vector3(dx, dy, 0);
  37348. var position = normal.scale(thickness / 2);
  37349. var textureCoordinate = new BABYLON.Vector2(u, v);
  37350. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37351. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37352. positions.push(position.x, position.y, position.z);
  37353. normals.push(normal.x, normal.y, normal.z);
  37354. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37355. // And create indices for two triangles.
  37356. var nextI = (i + 1) % stride;
  37357. var nextJ = (j + 1) % stride;
  37358. indices.push(i * stride + j);
  37359. indices.push(i * stride + nextJ);
  37360. indices.push(nextI * stride + j);
  37361. indices.push(i * stride + nextJ);
  37362. indices.push(nextI * stride + nextJ);
  37363. indices.push(nextI * stride + j);
  37364. }
  37365. }
  37366. // Sides
  37367. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37368. // Result
  37369. var vertexData = new VertexData();
  37370. vertexData.indices = indices;
  37371. vertexData.positions = positions;
  37372. vertexData.normals = normals;
  37373. vertexData.uvs = uvs;
  37374. return vertexData;
  37375. };
  37376. /**
  37377. * Creates the VertexData of the LineSystem
  37378. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37379. * - lines an array of lines, each line being an array of successive Vector3
  37380. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37381. * @returns the VertexData of the LineSystem
  37382. */
  37383. VertexData.CreateLineSystem = function (options) {
  37384. var indices = [];
  37385. var positions = [];
  37386. var lines = options.lines;
  37387. var colors = options.colors;
  37388. var vertexColors = [];
  37389. var idx = 0;
  37390. for (var l = 0; l < lines.length; l++) {
  37391. var points = lines[l];
  37392. for (var index = 0; index < points.length; index++) {
  37393. positions.push(points[index].x, points[index].y, points[index].z);
  37394. if (colors) {
  37395. var color = colors[l];
  37396. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37397. }
  37398. if (index > 0) {
  37399. indices.push(idx - 1);
  37400. indices.push(idx);
  37401. }
  37402. idx++;
  37403. }
  37404. }
  37405. var vertexData = new VertexData();
  37406. vertexData.indices = indices;
  37407. vertexData.positions = positions;
  37408. if (colors) {
  37409. vertexData.colors = vertexColors;
  37410. }
  37411. return vertexData;
  37412. };
  37413. /**
  37414. * Create the VertexData for a DashedLines
  37415. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37416. * - points an array successive Vector3
  37417. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37418. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37419. * - dashNb the intended total number of dashes, optional, default 200
  37420. * @returns the VertexData for the DashedLines
  37421. */
  37422. VertexData.CreateDashedLines = function (options) {
  37423. var dashSize = options.dashSize || 3;
  37424. var gapSize = options.gapSize || 1;
  37425. var dashNb = options.dashNb || 200;
  37426. var points = options.points;
  37427. var positions = new Array();
  37428. var indices = new Array();
  37429. var curvect = BABYLON.Vector3.Zero();
  37430. var lg = 0;
  37431. var nb = 0;
  37432. var shft = 0;
  37433. var dashshft = 0;
  37434. var curshft = 0;
  37435. var idx = 0;
  37436. var i = 0;
  37437. for (i = 0; i < points.length - 1; i++) {
  37438. points[i + 1].subtractToRef(points[i], curvect);
  37439. lg += curvect.length();
  37440. }
  37441. shft = lg / dashNb;
  37442. dashshft = dashSize * shft / (dashSize + gapSize);
  37443. for (i = 0; i < points.length - 1; i++) {
  37444. points[i + 1].subtractToRef(points[i], curvect);
  37445. nb = Math.floor(curvect.length() / shft);
  37446. curvect.normalize();
  37447. for (var j = 0; j < nb; j++) {
  37448. curshft = shft * j;
  37449. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37450. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37451. indices.push(idx, idx + 1);
  37452. idx += 2;
  37453. }
  37454. }
  37455. // Result
  37456. var vertexData = new VertexData();
  37457. vertexData.positions = positions;
  37458. vertexData.indices = indices;
  37459. return vertexData;
  37460. };
  37461. /**
  37462. * Creates the VertexData for a Ground
  37463. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37464. * - width the width (x direction) of the ground, optional, default 1
  37465. * - height the height (z direction) of the ground, optional, default 1
  37466. * - subdivisions the number of subdivisions per side, optional, default 1
  37467. * @returns the VertexData of the Ground
  37468. */
  37469. VertexData.CreateGround = function (options) {
  37470. var indices = [];
  37471. var positions = [];
  37472. var normals = [];
  37473. var uvs = [];
  37474. var row, col;
  37475. var width = options.width || 1;
  37476. var height = options.height || 1;
  37477. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37478. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37479. for (row = 0; row <= subdivisionsY; row++) {
  37480. for (col = 0; col <= subdivisionsX; col++) {
  37481. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37482. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37483. positions.push(position.x, position.y, position.z);
  37484. normals.push(normal.x, normal.y, normal.z);
  37485. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37486. }
  37487. }
  37488. for (row = 0; row < subdivisionsY; row++) {
  37489. for (col = 0; col < subdivisionsX; col++) {
  37490. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37491. indices.push(col + 1 + row * (subdivisionsX + 1));
  37492. indices.push(col + row * (subdivisionsX + 1));
  37493. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37494. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37495. indices.push(col + row * (subdivisionsX + 1));
  37496. }
  37497. }
  37498. // Result
  37499. var vertexData = new VertexData();
  37500. vertexData.indices = indices;
  37501. vertexData.positions = positions;
  37502. vertexData.normals = normals;
  37503. vertexData.uvs = uvs;
  37504. return vertexData;
  37505. };
  37506. /**
  37507. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37508. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37509. * * xmin the ground minimum X coordinate, optional, default -1
  37510. * * zmin the ground minimum Z coordinate, optional, default -1
  37511. * * xmax the ground maximum X coordinate, optional, default 1
  37512. * * zmax the ground maximum Z coordinate, optional, default 1
  37513. * * 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}
  37514. * * 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}
  37515. * @returns the VertexData of the TiledGround
  37516. */
  37517. VertexData.CreateTiledGround = function (options) {
  37518. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37519. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37520. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37521. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37522. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37523. var precision = options.precision || { w: 1, h: 1 };
  37524. var indices = new Array();
  37525. var positions = new Array();
  37526. var normals = new Array();
  37527. var uvs = new Array();
  37528. var row, col, tileRow, tileCol;
  37529. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37530. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37531. precision.w = (precision.w < 1) ? 1 : precision.w;
  37532. precision.h = (precision.h < 1) ? 1 : precision.h;
  37533. var tileSize = {
  37534. 'w': (xmax - xmin) / subdivisions.w,
  37535. 'h': (zmax - zmin) / subdivisions.h
  37536. };
  37537. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37538. // Indices
  37539. var base = positions.length / 3;
  37540. var rowLength = precision.w + 1;
  37541. for (row = 0; row < precision.h; row++) {
  37542. for (col = 0; col < precision.w; col++) {
  37543. var square = [
  37544. base + col + row * rowLength,
  37545. base + (col + 1) + row * rowLength,
  37546. base + (col + 1) + (row + 1) * rowLength,
  37547. base + col + (row + 1) * rowLength
  37548. ];
  37549. indices.push(square[1]);
  37550. indices.push(square[2]);
  37551. indices.push(square[3]);
  37552. indices.push(square[0]);
  37553. indices.push(square[1]);
  37554. indices.push(square[3]);
  37555. }
  37556. }
  37557. // Position, normals and uvs
  37558. var position = BABYLON.Vector3.Zero();
  37559. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37560. for (row = 0; row <= precision.h; row++) {
  37561. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37562. for (col = 0; col <= precision.w; col++) {
  37563. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37564. position.y = 0;
  37565. positions.push(position.x, position.y, position.z);
  37566. normals.push(normal.x, normal.y, normal.z);
  37567. uvs.push(col / precision.w, row / precision.h);
  37568. }
  37569. }
  37570. }
  37571. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37572. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37573. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37574. }
  37575. }
  37576. // Result
  37577. var vertexData = new VertexData();
  37578. vertexData.indices = indices;
  37579. vertexData.positions = positions;
  37580. vertexData.normals = normals;
  37581. vertexData.uvs = uvs;
  37582. return vertexData;
  37583. };
  37584. /**
  37585. * Creates the VertexData of the Ground designed from a heightmap
  37586. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37587. * * width the width (x direction) of the ground
  37588. * * height the height (z direction) of the ground
  37589. * * subdivisions the number of subdivisions per side
  37590. * * minHeight the minimum altitude on the ground, optional, default 0
  37591. * * maxHeight the maximum altitude on the ground, optional default 1
  37592. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37593. * * buffer the array holding the image color data
  37594. * * bufferWidth the width of image
  37595. * * bufferHeight the height of image
  37596. * @returns the VertexData of the Ground designed from a heightmap
  37597. */
  37598. VertexData.CreateGroundFromHeightMap = function (options) {
  37599. var indices = [];
  37600. var positions = [];
  37601. var normals = [];
  37602. var uvs = [];
  37603. var row, col;
  37604. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37605. // Vertices
  37606. for (row = 0; row <= options.subdivisions; row++) {
  37607. for (col = 0; col <= options.subdivisions; col++) {
  37608. 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));
  37609. // Compute height
  37610. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37611. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37612. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37613. var r = options.buffer[pos] / 255.0;
  37614. var g = options.buffer[pos + 1] / 255.0;
  37615. var b = options.buffer[pos + 2] / 255.0;
  37616. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37617. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37618. // Add vertex
  37619. positions.push(position.x, position.y, position.z);
  37620. normals.push(0, 0, 0);
  37621. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37622. }
  37623. }
  37624. // Indices
  37625. for (row = 0; row < options.subdivisions; row++) {
  37626. for (col = 0; col < options.subdivisions; col++) {
  37627. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37628. indices.push(col + 1 + row * (options.subdivisions + 1));
  37629. indices.push(col + row * (options.subdivisions + 1));
  37630. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37631. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37632. indices.push(col + row * (options.subdivisions + 1));
  37633. }
  37634. }
  37635. // Normals
  37636. VertexData.ComputeNormals(positions, indices, normals);
  37637. // Result
  37638. var vertexData = new VertexData();
  37639. vertexData.indices = indices;
  37640. vertexData.positions = positions;
  37641. vertexData.normals = normals;
  37642. vertexData.uvs = uvs;
  37643. return vertexData;
  37644. };
  37645. /**
  37646. * Creates the VertexData for a Plane
  37647. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37648. * * size sets the width and height of the plane to the value of size, optional default 1
  37649. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37650. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37651. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37652. * * 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)
  37653. * * 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)
  37654. * @returns the VertexData of the box
  37655. */
  37656. VertexData.CreatePlane = function (options) {
  37657. var indices = [];
  37658. var positions = [];
  37659. var normals = [];
  37660. var uvs = [];
  37661. var width = options.width || options.size || 1;
  37662. var height = options.height || options.size || 1;
  37663. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37664. // Vertices
  37665. var halfWidth = width / 2.0;
  37666. var halfHeight = height / 2.0;
  37667. positions.push(-halfWidth, -halfHeight, 0);
  37668. normals.push(0, 0, -1.0);
  37669. uvs.push(0.0, 0.0);
  37670. positions.push(halfWidth, -halfHeight, 0);
  37671. normals.push(0, 0, -1.0);
  37672. uvs.push(1.0, 0.0);
  37673. positions.push(halfWidth, halfHeight, 0);
  37674. normals.push(0, 0, -1.0);
  37675. uvs.push(1.0, 1.0);
  37676. positions.push(-halfWidth, halfHeight, 0);
  37677. normals.push(0, 0, -1.0);
  37678. uvs.push(0.0, 1.0);
  37679. // Indices
  37680. indices.push(0);
  37681. indices.push(1);
  37682. indices.push(2);
  37683. indices.push(0);
  37684. indices.push(2);
  37685. indices.push(3);
  37686. // Sides
  37687. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37688. // Result
  37689. var vertexData = new VertexData();
  37690. vertexData.indices = indices;
  37691. vertexData.positions = positions;
  37692. vertexData.normals = normals;
  37693. vertexData.uvs = uvs;
  37694. return vertexData;
  37695. };
  37696. /**
  37697. * Creates the VertexData of the Disc or regular Polygon
  37698. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37699. * * radius the radius of the disc, optional default 0.5
  37700. * * tessellation the number of polygon sides, optional, default 64
  37701. * * 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
  37702. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37703. * * 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)
  37704. * * 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)
  37705. * @returns the VertexData of the box
  37706. */
  37707. VertexData.CreateDisc = function (options) {
  37708. var positions = new Array();
  37709. var indices = new Array();
  37710. var normals = new Array();
  37711. var uvs = new Array();
  37712. var radius = options.radius || 0.5;
  37713. var tessellation = options.tessellation || 64;
  37714. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37715. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37716. // positions and uvs
  37717. positions.push(0, 0, 0); // disc center first
  37718. uvs.push(0.5, 0.5);
  37719. var theta = Math.PI * 2 * arc;
  37720. var step = theta / tessellation;
  37721. for (var a = 0; a < theta; a += step) {
  37722. var x = Math.cos(a);
  37723. var y = Math.sin(a);
  37724. var u = (x + 1) / 2;
  37725. var v = (1 - y) / 2;
  37726. positions.push(radius * x, radius * y, 0);
  37727. uvs.push(u, v);
  37728. }
  37729. if (arc === 1) {
  37730. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37731. uvs.push(uvs[2], uvs[3]);
  37732. }
  37733. //indices
  37734. var vertexNb = positions.length / 3;
  37735. for (var i = 1; i < vertexNb - 1; i++) {
  37736. indices.push(i + 1, 0, i);
  37737. }
  37738. // result
  37739. VertexData.ComputeNormals(positions, indices, normals);
  37740. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37741. var vertexData = new VertexData();
  37742. vertexData.indices = indices;
  37743. vertexData.positions = positions;
  37744. vertexData.normals = normals;
  37745. vertexData.uvs = uvs;
  37746. return vertexData;
  37747. };
  37748. /**
  37749. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37750. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37751. * @param polygon a mesh built from polygonTriangulation.build()
  37752. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37753. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37754. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37755. * @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)
  37756. * @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)
  37757. * @returns the VertexData of the Polygon
  37758. */
  37759. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37760. var faceUV = fUV || new Array(3);
  37761. var faceColors = fColors;
  37762. var colors = [];
  37763. // default face colors and UV if undefined
  37764. for (var f = 0; f < 3; f++) {
  37765. if (faceUV[f] === undefined) {
  37766. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37767. }
  37768. if (faceColors && faceColors[f] === undefined) {
  37769. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37770. }
  37771. }
  37772. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37773. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37774. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37775. var indices = polygon.getIndices();
  37776. // set face colours and textures
  37777. var idx = 0;
  37778. var face = 0;
  37779. for (var index = 0; index < normals.length; index += 3) {
  37780. //Edge Face no. 1
  37781. if (Math.abs(normals[index + 1]) < 0.001) {
  37782. face = 1;
  37783. }
  37784. //Top Face no. 0
  37785. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37786. face = 0;
  37787. }
  37788. //Bottom Face no. 2
  37789. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37790. face = 2;
  37791. }
  37792. idx = index / 3;
  37793. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37794. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37795. if (faceColors) {
  37796. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37797. }
  37798. }
  37799. // sides
  37800. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37801. // Result
  37802. var vertexData = new VertexData();
  37803. vertexData.indices = indices;
  37804. vertexData.positions = positions;
  37805. vertexData.normals = normals;
  37806. vertexData.uvs = uvs;
  37807. if (faceColors) {
  37808. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37809. vertexData.colors = totalColors;
  37810. }
  37811. return vertexData;
  37812. };
  37813. /**
  37814. * Creates the VertexData of the IcoSphere
  37815. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37816. * * radius the radius of the IcoSphere, optional default 1
  37817. * * radiusX allows stretching in the x direction, optional, default radius
  37818. * * radiusY allows stretching in the y direction, optional, default radius
  37819. * * radiusZ allows stretching in the z direction, optional, default radius
  37820. * * flat when true creates a flat shaded mesh, optional, default true
  37821. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37822. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37823. * * 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)
  37824. * * 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)
  37825. * @returns the VertexData of the IcoSphere
  37826. */
  37827. VertexData.CreateIcoSphere = function (options) {
  37828. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37829. var radius = options.radius || 1;
  37830. var flat = (options.flat === undefined) ? true : options.flat;
  37831. var subdivisions = options.subdivisions || 4;
  37832. var radiusX = options.radiusX || radius;
  37833. var radiusY = options.radiusY || radius;
  37834. var radiusZ = options.radiusZ || radius;
  37835. var t = (1 + Math.sqrt(5)) / 2;
  37836. // 12 vertex x,y,z
  37837. var ico_vertices = [
  37838. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37839. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37840. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37841. ];
  37842. // index of 3 vertex makes a face of icopshere
  37843. var ico_indices = [
  37844. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37845. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37846. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37847. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37848. ];
  37849. // vertex for uv have aliased position, not for UV
  37850. var vertices_unalias_id = [
  37851. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37852. // vertex alias
  37853. 0,
  37854. 2,
  37855. 3,
  37856. 3,
  37857. 3,
  37858. 4,
  37859. 7,
  37860. 8,
  37861. 9,
  37862. 9,
  37863. 10,
  37864. 11 // 23: B + 12
  37865. ];
  37866. // uv as integer step (not pixels !)
  37867. var ico_vertexuv = [
  37868. 5, 1, 3, 1, 6, 4, 0, 0,
  37869. 5, 3, 4, 2, 2, 2, 4, 0,
  37870. 2, 0, 1, 1, 6, 0, 6, 2,
  37871. // vertex alias (for same vertex on different faces)
  37872. 0, 4,
  37873. 3, 3,
  37874. 4, 4,
  37875. 3, 1,
  37876. 4, 2,
  37877. 4, 4,
  37878. 0, 2,
  37879. 1, 1,
  37880. 2, 2,
  37881. 3, 3,
  37882. 1, 3,
  37883. 2, 4 // 23: B + 12
  37884. ];
  37885. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37886. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37887. // First island of uv mapping
  37888. // v = 4h 3+ 2
  37889. // v = 3h 9+ 4
  37890. // v = 2h 9+ 5 B
  37891. // v = 1h 9 1 0
  37892. // v = 0h 3 8 7 A
  37893. // u = 0 1 2 3 4 5 6 *a
  37894. // Second island of uv mapping
  37895. // v = 4h 0+ B+ 4+
  37896. // v = 3h A+ 2+
  37897. // v = 2h 7+ 6 3+
  37898. // v = 1h 8+ 3+
  37899. // v = 0h
  37900. // u = 0 1 2 3 4 5 6 *a
  37901. // Face layout on texture UV mapping
  37902. // ============
  37903. // \ 4 /\ 16 / ======
  37904. // \ / \ / /\ 11 /
  37905. // \/ 7 \/ / \ /
  37906. // ======= / 10 \/
  37907. // /\ 17 /\ =======
  37908. // / \ / \ \ 15 /\
  37909. // / 8 \/ 12 \ \ / \
  37910. // ============ \/ 6 \
  37911. // \ 18 /\ ============
  37912. // \ / \ \ 5 /\ 0 /
  37913. // \/ 13 \ \ / \ /
  37914. // ======= \/ 1 \/
  37915. // =============
  37916. // /\ 19 /\ 2 /\
  37917. // / \ / \ / \
  37918. // / 14 \/ 9 \/ 3 \
  37919. // ===================
  37920. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37921. var ustep = 138 / 1024;
  37922. var vstep = 239 / 1024;
  37923. var uoffset = 60 / 1024;
  37924. var voffset = 26 / 1024;
  37925. // Second island should have margin, not to touch the first island
  37926. // avoid any borderline artefact in pixel rounding
  37927. var island_u_offset = -40 / 1024;
  37928. var island_v_offset = +20 / 1024;
  37929. // face is either island 0 or 1 :
  37930. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37931. var island = [
  37932. 0, 0, 0, 0, 1,
  37933. 0, 0, 1, 1, 0,
  37934. 0, 0, 1, 1, 0,
  37935. 0, 1, 1, 1, 0 // 15 - 19
  37936. ];
  37937. var indices = new Array();
  37938. var positions = new Array();
  37939. var normals = new Array();
  37940. var uvs = new Array();
  37941. var current_indice = 0;
  37942. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37943. var face_vertex_pos = new Array(3);
  37944. var face_vertex_uv = new Array(3);
  37945. var v012;
  37946. for (v012 = 0; v012 < 3; v012++) {
  37947. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37948. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37949. }
  37950. // create all with normals
  37951. for (var face = 0; face < 20; face++) {
  37952. // 3 vertex per face
  37953. for (v012 = 0; v012 < 3; v012++) {
  37954. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37955. var v_id = ico_indices[3 * face + v012];
  37956. // vertex have 3D position (x,y,z)
  37957. 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]);
  37958. // Normalize to get normal, then scale to radius
  37959. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37960. // uv Coordinates from vertex ID
  37961. 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);
  37962. }
  37963. // Subdivide the face (interpolate pos, norm, uv)
  37964. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37965. // - norm is linear interpolation of vertex corner normal
  37966. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37967. // - uv is linear interpolation
  37968. //
  37969. // Topology is as below for sub-divide by 2
  37970. // vertex shown as v0,v1,v2
  37971. // interp index is i1 to progress in range [v0,v1[
  37972. // interp index is i2 to progress in range [v0,v2[
  37973. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37974. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37975. //
  37976. //
  37977. // i2 v2
  37978. // ^ ^
  37979. // / / \
  37980. // / / \
  37981. // / / \
  37982. // / / (0,1) \
  37983. // / #---------\
  37984. // / / \ (0,0)'/ \
  37985. // / / \ / \
  37986. // / / \ / \
  37987. // / / (0,0) \ / (1,0) \
  37988. // / #---------#---------\
  37989. // v0 v1
  37990. //
  37991. // --------------------> i1
  37992. //
  37993. // interp of (i1,i2):
  37994. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37995. // along i1 : lerp(x0,x1, i1/(S-i2))
  37996. //
  37997. // centroid of triangle is needed to get help normal computation
  37998. // (c1,c2) are used for centroid location
  37999. var interp_vertex = function (i1, i2, c1, c2) {
  38000. // vertex is interpolated from
  38001. // - face_vertex_pos[0..2]
  38002. // - face_vertex_uv[0..2]
  38003. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38004. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38005. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38006. pos_interp.normalize();
  38007. var vertex_normal;
  38008. if (flat) {
  38009. // in flat mode, recalculate normal as face centroid normal
  38010. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38011. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38012. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38013. }
  38014. else {
  38015. // in smooth mode, recalculate normal from each single vertex position
  38016. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38017. }
  38018. // Vertex normal need correction due to X,Y,Z radius scaling
  38019. vertex_normal.x /= radiusX;
  38020. vertex_normal.y /= radiusY;
  38021. vertex_normal.z /= radiusZ;
  38022. vertex_normal.normalize();
  38023. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38024. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38025. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38026. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38027. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38028. uvs.push(uv_interp.x, uv_interp.y);
  38029. // push each vertex has member of a face
  38030. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38031. indices.push(current_indice);
  38032. current_indice++;
  38033. };
  38034. for (var i2 = 0; i2 < subdivisions; i2++) {
  38035. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38036. // face : (i1,i2) for /\ :
  38037. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38038. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38039. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38040. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38041. if (i1 + i2 + 1 < subdivisions) {
  38042. // face : (i1,i2)' for \/ :
  38043. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38044. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38045. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38046. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38047. }
  38048. }
  38049. }
  38050. }
  38051. // Sides
  38052. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38053. // Result
  38054. var vertexData = new VertexData();
  38055. vertexData.indices = indices;
  38056. vertexData.positions = positions;
  38057. vertexData.normals = normals;
  38058. vertexData.uvs = uvs;
  38059. return vertexData;
  38060. };
  38061. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38062. /**
  38063. * Creates the VertexData for a Polyhedron
  38064. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38065. * * type provided types are:
  38066. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38067. * * 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)
  38068. * * size the size of the IcoSphere, optional default 1
  38069. * * sizeX allows stretching in the x direction, optional, default size
  38070. * * sizeY allows stretching in the y direction, optional, default size
  38071. * * sizeZ allows stretching in the z direction, optional, default size
  38072. * * 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
  38073. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38074. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38075. * * flat when true creates a flat shaded mesh, optional, default true
  38076. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38077. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38078. * * 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)
  38079. * * 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)
  38080. * @returns the VertexData of the Polyhedron
  38081. */
  38082. VertexData.CreatePolyhedron = function (options) {
  38083. // provided polyhedron types :
  38084. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38085. // 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)
  38086. var polyhedra = [];
  38087. 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]] };
  38088. 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]] };
  38089. polyhedra[2] = {
  38090. 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]],
  38091. 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]]
  38092. };
  38093. polyhedra[3] = {
  38094. 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]],
  38095. 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]]
  38096. };
  38097. polyhedra[4] = {
  38098. 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]],
  38099. 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]]
  38100. };
  38101. 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]] };
  38102. 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]] };
  38103. 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]] };
  38104. 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]] };
  38105. 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]] };
  38106. 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]] };
  38107. 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]] };
  38108. 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]] };
  38109. 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]] };
  38110. polyhedra[14] = {
  38111. 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]],
  38112. 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]]
  38113. };
  38114. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38115. var size = options.size;
  38116. var sizeX = options.sizeX || size || 1;
  38117. var sizeY = options.sizeY || size || 1;
  38118. var sizeZ = options.sizeZ || size || 1;
  38119. var data = options.custom || polyhedra[type];
  38120. var nbfaces = data.face.length;
  38121. var faceUV = options.faceUV || new Array(nbfaces);
  38122. var faceColors = options.faceColors;
  38123. var flat = (options.flat === undefined) ? true : options.flat;
  38124. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38125. var positions = new Array();
  38126. var indices = new Array();
  38127. var normals = new Array();
  38128. var uvs = new Array();
  38129. var colors = new Array();
  38130. var index = 0;
  38131. var faceIdx = 0; // face cursor in the array "indexes"
  38132. var indexes = new Array();
  38133. var i = 0;
  38134. var f = 0;
  38135. var u, v, ang, x, y, tmp;
  38136. // default face colors and UV if undefined
  38137. if (flat) {
  38138. for (f = 0; f < nbfaces; f++) {
  38139. if (faceColors && faceColors[f] === undefined) {
  38140. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38141. }
  38142. if (faceUV && faceUV[f] === undefined) {
  38143. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38144. }
  38145. }
  38146. }
  38147. if (!flat) {
  38148. for (i = 0; i < data.vertex.length; i++) {
  38149. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38150. uvs.push(0, 0);
  38151. }
  38152. for (f = 0; f < nbfaces; f++) {
  38153. for (i = 0; i < data.face[f].length - 2; i++) {
  38154. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38155. }
  38156. }
  38157. }
  38158. else {
  38159. for (f = 0; f < nbfaces; f++) {
  38160. var fl = data.face[f].length; // number of vertices of the current face
  38161. ang = 2 * Math.PI / fl;
  38162. x = 0.5 * Math.tan(ang / 2);
  38163. y = 0.5;
  38164. // positions, uvs, colors
  38165. for (i = 0; i < fl; i++) {
  38166. // positions
  38167. 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);
  38168. indexes.push(index);
  38169. index++;
  38170. // uvs
  38171. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38172. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38173. uvs.push(u, v);
  38174. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38175. y = x * Math.sin(ang) + y * Math.cos(ang);
  38176. x = tmp;
  38177. // colors
  38178. if (faceColors) {
  38179. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38180. }
  38181. }
  38182. // indices from indexes
  38183. for (i = 0; i < fl - 2; i++) {
  38184. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38185. }
  38186. faceIdx += fl;
  38187. }
  38188. }
  38189. VertexData.ComputeNormals(positions, indices, normals);
  38190. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38191. var vertexData = new VertexData();
  38192. vertexData.positions = positions;
  38193. vertexData.indices = indices;
  38194. vertexData.normals = normals;
  38195. vertexData.uvs = uvs;
  38196. if (faceColors && flat) {
  38197. vertexData.colors = colors;
  38198. }
  38199. return vertexData;
  38200. };
  38201. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38202. /**
  38203. * Creates the VertexData for a TorusKnot
  38204. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38205. * * radius the radius of the torus knot, optional, default 2
  38206. * * tube the thickness of the tube, optional, default 0.5
  38207. * * radialSegments the number of sides on each tube segments, optional, default 32
  38208. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38209. * * p the number of windings around the z axis, optional, default 2
  38210. * * q the number of windings around the x axis, optional, default 3
  38211. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38212. * * 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)
  38213. * * 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)
  38214. * @returns the VertexData of the Torus Knot
  38215. */
  38216. VertexData.CreateTorusKnot = function (options) {
  38217. var indices = new Array();
  38218. var positions = new Array();
  38219. var normals = new Array();
  38220. var uvs = new Array();
  38221. var radius = options.radius || 2;
  38222. var tube = options.tube || 0.5;
  38223. var radialSegments = options.radialSegments || 32;
  38224. var tubularSegments = options.tubularSegments || 32;
  38225. var p = options.p || 2;
  38226. var q = options.q || 3;
  38227. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38228. // Helper
  38229. var getPos = function (angle) {
  38230. var cu = Math.cos(angle);
  38231. var su = Math.sin(angle);
  38232. var quOverP = q / p * angle;
  38233. var cs = Math.cos(quOverP);
  38234. var tx = radius * (2 + cs) * 0.5 * cu;
  38235. var ty = radius * (2 + cs) * su * 0.5;
  38236. var tz = radius * Math.sin(quOverP) * 0.5;
  38237. return new BABYLON.Vector3(tx, ty, tz);
  38238. };
  38239. // Vertices
  38240. var i;
  38241. var j;
  38242. for (i = 0; i <= radialSegments; i++) {
  38243. var modI = i % radialSegments;
  38244. var u = modI / radialSegments * 2 * p * Math.PI;
  38245. var p1 = getPos(u);
  38246. var p2 = getPos(u + 0.01);
  38247. var tang = p2.subtract(p1);
  38248. var n = p2.add(p1);
  38249. var bitan = BABYLON.Vector3.Cross(tang, n);
  38250. n = BABYLON.Vector3.Cross(bitan, tang);
  38251. bitan.normalize();
  38252. n.normalize();
  38253. for (j = 0; j < tubularSegments; j++) {
  38254. var modJ = j % tubularSegments;
  38255. var v = modJ / tubularSegments * 2 * Math.PI;
  38256. var cx = -tube * Math.cos(v);
  38257. var cy = tube * Math.sin(v);
  38258. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38259. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38260. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38261. uvs.push(i / radialSegments);
  38262. uvs.push(j / tubularSegments);
  38263. }
  38264. }
  38265. for (i = 0; i < radialSegments; i++) {
  38266. for (j = 0; j < tubularSegments; j++) {
  38267. var jNext = (j + 1) % tubularSegments;
  38268. var a = i * tubularSegments + j;
  38269. var b = (i + 1) * tubularSegments + j;
  38270. var c = (i + 1) * tubularSegments + jNext;
  38271. var d = i * tubularSegments + jNext;
  38272. indices.push(d);
  38273. indices.push(b);
  38274. indices.push(a);
  38275. indices.push(d);
  38276. indices.push(c);
  38277. indices.push(b);
  38278. }
  38279. }
  38280. // Normals
  38281. VertexData.ComputeNormals(positions, indices, normals);
  38282. // Sides
  38283. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38284. // Result
  38285. var vertexData = new VertexData();
  38286. vertexData.indices = indices;
  38287. vertexData.positions = positions;
  38288. vertexData.normals = normals;
  38289. vertexData.uvs = uvs;
  38290. return vertexData;
  38291. };
  38292. // Tools
  38293. /**
  38294. * Compute normals for given positions and indices
  38295. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38296. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38297. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38298. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38299. * * facetNormals : optional array of facet normals (vector3)
  38300. * * facetPositions : optional array of facet positions (vector3)
  38301. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38302. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38303. * * bInfo : optional bounding info, required for facetPartitioning computation
  38304. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38305. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38306. * * useRightHandedSystem: optional boolean to for right handed system computation
  38307. * * depthSort : optional boolean to enable the facet depth sort computation
  38308. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38309. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38310. */
  38311. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38312. // temporary scalar variables
  38313. var index = 0; // facet index
  38314. var p1p2x = 0.0; // p1p2 vector x coordinate
  38315. var p1p2y = 0.0; // p1p2 vector y coordinate
  38316. var p1p2z = 0.0; // p1p2 vector z coordinate
  38317. var p3p2x = 0.0; // p3p2 vector x coordinate
  38318. var p3p2y = 0.0; // p3p2 vector y coordinate
  38319. var p3p2z = 0.0; // p3p2 vector z coordinate
  38320. var faceNormalx = 0.0; // facet normal x coordinate
  38321. var faceNormaly = 0.0; // facet normal y coordinate
  38322. var faceNormalz = 0.0; // facet normal z coordinate
  38323. var length = 0.0; // facet normal length before normalization
  38324. var v1x = 0; // vector1 x index in the positions array
  38325. var v1y = 0; // vector1 y index in the positions array
  38326. var v1z = 0; // vector1 z index in the positions array
  38327. var v2x = 0; // vector2 x index in the positions array
  38328. var v2y = 0; // vector2 y index in the positions array
  38329. var v2z = 0; // vector2 z index in the positions array
  38330. var v3x = 0; // vector3 x index in the positions array
  38331. var v3y = 0; // vector3 y index in the positions array
  38332. var v3z = 0; // vector3 z index in the positions array
  38333. var computeFacetNormals = false;
  38334. var computeFacetPositions = false;
  38335. var computeFacetPartitioning = false;
  38336. var computeDepthSort = false;
  38337. var faceNormalSign = 1;
  38338. var ratio = 0;
  38339. var distanceTo = null;
  38340. if (options) {
  38341. computeFacetNormals = (options.facetNormals) ? true : false;
  38342. computeFacetPositions = (options.facetPositions) ? true : false;
  38343. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38344. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38345. ratio = options.ratio || 0;
  38346. computeDepthSort = (options.depthSort) ? true : false;
  38347. distanceTo = (options.distanceTo);
  38348. if (computeDepthSort) {
  38349. if (distanceTo === undefined) {
  38350. distanceTo = BABYLON.Vector3.Zero();
  38351. }
  38352. var depthSortedFacets = options.depthSortedFacets;
  38353. }
  38354. }
  38355. // facetPartitioning reinit if needed
  38356. var xSubRatio = 0;
  38357. var ySubRatio = 0;
  38358. var zSubRatio = 0;
  38359. var subSq = 0;
  38360. if (computeFacetPartitioning && options && options.bbSize) {
  38361. var ox = 0; // X partitioning index for facet position
  38362. var oy = 0; // Y partinioning index for facet position
  38363. var oz = 0; // Z partinioning index for facet position
  38364. var b1x = 0; // X partitioning index for facet v1 vertex
  38365. var b1y = 0; // Y partitioning index for facet v1 vertex
  38366. var b1z = 0; // z partitioning index for facet v1 vertex
  38367. var b2x = 0; // X partitioning index for facet v2 vertex
  38368. var b2y = 0; // Y partitioning index for facet v2 vertex
  38369. var b2z = 0; // Z partitioning index for facet v2 vertex
  38370. var b3x = 0; // X partitioning index for facet v3 vertex
  38371. var b3y = 0; // Y partitioning index for facet v3 vertex
  38372. var b3z = 0; // Z partitioning index for facet v3 vertex
  38373. var block_idx_o = 0; // facet barycenter block index
  38374. var block_idx_v1 = 0; // v1 vertex block index
  38375. var block_idx_v2 = 0; // v2 vertex block index
  38376. var block_idx_v3 = 0; // v3 vertex block index
  38377. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38378. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38379. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38380. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38381. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38382. subSq = options.subDiv.max * options.subDiv.max;
  38383. options.facetPartitioning.length = 0;
  38384. }
  38385. // reset the normals
  38386. for (index = 0; index < positions.length; index++) {
  38387. normals[index] = 0.0;
  38388. }
  38389. // Loop : 1 indice triplet = 1 facet
  38390. var nbFaces = (indices.length / 3) | 0;
  38391. for (index = 0; index < nbFaces; index++) {
  38392. // get the indexes of the coordinates of each vertex of the facet
  38393. v1x = indices[index * 3] * 3;
  38394. v1y = v1x + 1;
  38395. v1z = v1x + 2;
  38396. v2x = indices[index * 3 + 1] * 3;
  38397. v2y = v2x + 1;
  38398. v2z = v2x + 2;
  38399. v3x = indices[index * 3 + 2] * 3;
  38400. v3y = v3x + 1;
  38401. v3z = v3x + 2;
  38402. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38403. p1p2y = positions[v1y] - positions[v2y];
  38404. p1p2z = positions[v1z] - positions[v2z];
  38405. p3p2x = positions[v3x] - positions[v2x];
  38406. p3p2y = positions[v3y] - positions[v2y];
  38407. p3p2z = positions[v3z] - positions[v2z];
  38408. // compute the face normal with the cross product
  38409. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38410. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38411. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38412. // normalize this normal and store it in the array facetData
  38413. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38414. length = (length === 0) ? 1.0 : length;
  38415. faceNormalx /= length;
  38416. faceNormaly /= length;
  38417. faceNormalz /= length;
  38418. if (computeFacetNormals && options) {
  38419. options.facetNormals[index].x = faceNormalx;
  38420. options.facetNormals[index].y = faceNormaly;
  38421. options.facetNormals[index].z = faceNormalz;
  38422. }
  38423. if (computeFacetPositions && options) {
  38424. // compute and the facet barycenter coordinates in the array facetPositions
  38425. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38426. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38427. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38428. }
  38429. if (computeFacetPartitioning && options) {
  38430. // store the facet indexes in arrays in the main facetPartitioning array :
  38431. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38432. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38433. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38434. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38435. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38436. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38437. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38438. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38439. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38440. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38441. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38442. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38443. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38444. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38445. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38446. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38447. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38448. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38449. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38450. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38451. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38452. // push each facet index in each block containing the vertex
  38453. options.facetPartitioning[block_idx_v1].push(index);
  38454. if (block_idx_v2 != block_idx_v1) {
  38455. options.facetPartitioning[block_idx_v2].push(index);
  38456. }
  38457. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38458. options.facetPartitioning[block_idx_v3].push(index);
  38459. }
  38460. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38461. options.facetPartitioning[block_idx_o].push(index);
  38462. }
  38463. }
  38464. if (computeDepthSort && options && options.facetPositions) {
  38465. var dsf = depthSortedFacets[index];
  38466. dsf.ind = index * 3;
  38467. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38468. }
  38469. // compute the normals anyway
  38470. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38471. normals[v1y] += faceNormaly;
  38472. normals[v1z] += faceNormalz;
  38473. normals[v2x] += faceNormalx;
  38474. normals[v2y] += faceNormaly;
  38475. normals[v2z] += faceNormalz;
  38476. normals[v3x] += faceNormalx;
  38477. normals[v3y] += faceNormaly;
  38478. normals[v3z] += faceNormalz;
  38479. }
  38480. // last normalization of each normal
  38481. for (index = 0; index < normals.length / 3; index++) {
  38482. faceNormalx = normals[index * 3];
  38483. faceNormaly = normals[index * 3 + 1];
  38484. faceNormalz = normals[index * 3 + 2];
  38485. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38486. length = (length === 0) ? 1.0 : length;
  38487. faceNormalx /= length;
  38488. faceNormaly /= length;
  38489. faceNormalz /= length;
  38490. normals[index * 3] = faceNormalx;
  38491. normals[index * 3 + 1] = faceNormaly;
  38492. normals[index * 3 + 2] = faceNormalz;
  38493. }
  38494. };
  38495. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38496. var li = indices.length;
  38497. var ln = normals.length;
  38498. var i;
  38499. var n;
  38500. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38501. switch (sideOrientation) {
  38502. case BABYLON.Mesh.FRONTSIDE:
  38503. // nothing changed
  38504. break;
  38505. case BABYLON.Mesh.BACKSIDE:
  38506. var tmp;
  38507. // indices
  38508. for (i = 0; i < li; i += 3) {
  38509. tmp = indices[i];
  38510. indices[i] = indices[i + 2];
  38511. indices[i + 2] = tmp;
  38512. }
  38513. // normals
  38514. for (n = 0; n < ln; n++) {
  38515. normals[n] = -normals[n];
  38516. }
  38517. break;
  38518. case BABYLON.Mesh.DOUBLESIDE:
  38519. // positions
  38520. var lp = positions.length;
  38521. var l = lp / 3;
  38522. for (var p = 0; p < lp; p++) {
  38523. positions[lp + p] = positions[p];
  38524. }
  38525. // indices
  38526. for (i = 0; i < li; i += 3) {
  38527. indices[i + li] = indices[i + 2] + l;
  38528. indices[i + 1 + li] = indices[i + 1] + l;
  38529. indices[i + 2 + li] = indices[i] + l;
  38530. }
  38531. // normals
  38532. for (n = 0; n < ln; n++) {
  38533. normals[ln + n] = -normals[n];
  38534. }
  38535. // uvs
  38536. var lu = uvs.length;
  38537. var u = 0;
  38538. for (u = 0; u < lu; u++) {
  38539. uvs[u + lu] = uvs[u];
  38540. }
  38541. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38542. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38543. u = 0;
  38544. for (i = 0; i < lu / 2; i++) {
  38545. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38546. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38547. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38548. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38549. u += 2;
  38550. }
  38551. break;
  38552. }
  38553. };
  38554. /**
  38555. * Applies VertexData created from the imported parameters to the geometry
  38556. * @param parsedVertexData the parsed data from an imported file
  38557. * @param geometry the geometry to apply the VertexData to
  38558. */
  38559. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38560. var vertexData = new VertexData();
  38561. // positions
  38562. var positions = parsedVertexData.positions;
  38563. if (positions) {
  38564. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38565. }
  38566. // normals
  38567. var normals = parsedVertexData.normals;
  38568. if (normals) {
  38569. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38570. }
  38571. // tangents
  38572. var tangents = parsedVertexData.tangents;
  38573. if (tangents) {
  38574. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38575. }
  38576. // uvs
  38577. var uvs = parsedVertexData.uvs;
  38578. if (uvs) {
  38579. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38580. }
  38581. // uv2s
  38582. var uv2s = parsedVertexData.uv2s;
  38583. if (uv2s) {
  38584. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38585. }
  38586. // uv3s
  38587. var uv3s = parsedVertexData.uv3s;
  38588. if (uv3s) {
  38589. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38590. }
  38591. // uv4s
  38592. var uv4s = parsedVertexData.uv4s;
  38593. if (uv4s) {
  38594. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38595. }
  38596. // uv5s
  38597. var uv5s = parsedVertexData.uv5s;
  38598. if (uv5s) {
  38599. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38600. }
  38601. // uv6s
  38602. var uv6s = parsedVertexData.uv6s;
  38603. if (uv6s) {
  38604. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38605. }
  38606. // colors
  38607. var colors = parsedVertexData.colors;
  38608. if (colors) {
  38609. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38610. }
  38611. // matricesIndices
  38612. var matricesIndices = parsedVertexData.matricesIndices;
  38613. if (matricesIndices) {
  38614. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38615. }
  38616. // matricesWeights
  38617. var matricesWeights = parsedVertexData.matricesWeights;
  38618. if (matricesWeights) {
  38619. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38620. }
  38621. // indices
  38622. var indices = parsedVertexData.indices;
  38623. if (indices) {
  38624. vertexData.indices = indices;
  38625. }
  38626. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38627. };
  38628. return VertexData;
  38629. }());
  38630. BABYLON.VertexData = VertexData;
  38631. })(BABYLON || (BABYLON = {}));
  38632. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38633. var BABYLON;
  38634. (function (BABYLON) {
  38635. /**
  38636. * Class used to store geometry data (vertex buffers + index buffer)
  38637. */
  38638. var Geometry = /** @class */ (function () {
  38639. /**
  38640. * Creates a new geometry
  38641. * @param id defines the unique ID
  38642. * @param scene defines the hosting scene
  38643. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38644. * @param updatable defines if geometry must be updatable (false by default)
  38645. * @param mesh defines the mesh that will be associated with the geometry
  38646. */
  38647. function Geometry(id, scene, vertexData, updatable, mesh) {
  38648. if (updatable === void 0) { updatable = false; }
  38649. if (mesh === void 0) { mesh = null; }
  38650. /**
  38651. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38652. */
  38653. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38654. this._totalVertices = 0;
  38655. this._isDisposed = false;
  38656. this._indexBufferIsUpdatable = false;
  38657. this.id = id;
  38658. this._engine = scene.getEngine();
  38659. this._meshes = [];
  38660. this._scene = scene;
  38661. //Init vertex buffer cache
  38662. this._vertexBuffers = {};
  38663. this._indices = [];
  38664. this._updatable = updatable;
  38665. // vertexData
  38666. if (vertexData) {
  38667. this.setAllVerticesData(vertexData, updatable);
  38668. }
  38669. else {
  38670. this._totalVertices = 0;
  38671. this._indices = [];
  38672. }
  38673. if (this._engine.getCaps().vertexArrayObject) {
  38674. this._vertexArrayObjects = {};
  38675. }
  38676. // applyToMesh
  38677. if (mesh) {
  38678. if (mesh.getClassName() === "LinesMesh") {
  38679. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38680. this._updateExtend();
  38681. }
  38682. this.applyToMesh(mesh);
  38683. mesh.computeWorldMatrix(true);
  38684. }
  38685. }
  38686. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38687. /**
  38688. * 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
  38689. */
  38690. get: function () {
  38691. return this._boundingBias;
  38692. },
  38693. /**
  38694. * 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
  38695. */
  38696. set: function (value) {
  38697. if (this._boundingBias && this._boundingBias.equals(value)) {
  38698. return;
  38699. }
  38700. this._boundingBias = value.clone();
  38701. this._updateBoundingInfo(true, null);
  38702. },
  38703. enumerable: true,
  38704. configurable: true
  38705. });
  38706. /**
  38707. * Static function used to attach a new empty geometry to a mesh
  38708. * @param mesh defines the mesh to attach the geometry to
  38709. * @returns the new {BABYLON.Geometry}
  38710. */
  38711. Geometry.CreateGeometryForMesh = function (mesh) {
  38712. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38713. geometry.applyToMesh(mesh);
  38714. return geometry;
  38715. };
  38716. Object.defineProperty(Geometry.prototype, "extend", {
  38717. /**
  38718. * Gets the current extend of the geometry
  38719. */
  38720. get: function () {
  38721. return this._extend;
  38722. },
  38723. enumerable: true,
  38724. configurable: true
  38725. });
  38726. /**
  38727. * Gets the hosting scene
  38728. * @returns the hosting {BABYLON.Scene}
  38729. */
  38730. Geometry.prototype.getScene = function () {
  38731. return this._scene;
  38732. };
  38733. /**
  38734. * Gets the hosting engine
  38735. * @returns the hosting {BABYLON.Engine}
  38736. */
  38737. Geometry.prototype.getEngine = function () {
  38738. return this._engine;
  38739. };
  38740. /**
  38741. * Defines if the geometry is ready to use
  38742. * @returns true if the geometry is ready to be used
  38743. */
  38744. Geometry.prototype.isReady = function () {
  38745. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38746. };
  38747. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38748. /**
  38749. * Gets a value indicating that the geometry should not be serialized
  38750. */
  38751. get: function () {
  38752. for (var index = 0; index < this._meshes.length; index++) {
  38753. if (!this._meshes[index].doNotSerialize) {
  38754. return false;
  38755. }
  38756. }
  38757. return true;
  38758. },
  38759. enumerable: true,
  38760. configurable: true
  38761. });
  38762. /** @hidden */
  38763. Geometry.prototype._rebuild = function () {
  38764. if (this._vertexArrayObjects) {
  38765. this._vertexArrayObjects = {};
  38766. }
  38767. // Index buffer
  38768. if (this._meshes.length !== 0 && this._indices) {
  38769. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38770. }
  38771. // Vertex buffers
  38772. for (var key in this._vertexBuffers) {
  38773. var vertexBuffer = this._vertexBuffers[key];
  38774. vertexBuffer._rebuild();
  38775. }
  38776. };
  38777. /**
  38778. * Affects all geometry data in one call
  38779. * @param vertexData defines the geometry data
  38780. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38781. */
  38782. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38783. vertexData.applyToGeometry(this, updatable);
  38784. this.notifyUpdate();
  38785. };
  38786. /**
  38787. * Set specific vertex data
  38788. * @param kind defines the data kind (Position, normal, etc...)
  38789. * @param data defines the vertex data to use
  38790. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38791. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38792. */
  38793. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38794. if (updatable === void 0) { updatable = false; }
  38795. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38796. this.setVerticesBuffer(buffer);
  38797. };
  38798. /**
  38799. * Removes a specific vertex data
  38800. * @param kind defines the data kind (Position, normal, etc...)
  38801. */
  38802. Geometry.prototype.removeVerticesData = function (kind) {
  38803. if (this._vertexBuffers[kind]) {
  38804. this._vertexBuffers[kind].dispose();
  38805. delete this._vertexBuffers[kind];
  38806. }
  38807. };
  38808. /**
  38809. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38810. * @param buffer defines the vertex buffer to use
  38811. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38812. */
  38813. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38814. if (totalVertices === void 0) { totalVertices = null; }
  38815. var kind = buffer.getKind();
  38816. if (this._vertexBuffers[kind]) {
  38817. this._vertexBuffers[kind].dispose();
  38818. }
  38819. this._vertexBuffers[kind] = buffer;
  38820. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38821. var data = buffer.getData();
  38822. if (totalVertices != null) {
  38823. this._totalVertices = totalVertices;
  38824. }
  38825. else {
  38826. if (data != null) {
  38827. this._totalVertices = data.length / (buffer.byteStride / 4);
  38828. }
  38829. }
  38830. this._updateExtend(data);
  38831. this._resetPointsArrayCache();
  38832. var meshes = this._meshes;
  38833. var numOfMeshes = meshes.length;
  38834. for (var index = 0; index < numOfMeshes; index++) {
  38835. var mesh = meshes[index];
  38836. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38837. mesh._createGlobalSubMesh(false);
  38838. mesh.computeWorldMatrix(true);
  38839. }
  38840. }
  38841. this.notifyUpdate(kind);
  38842. if (this._vertexArrayObjects) {
  38843. this._disposeVertexArrayObjects();
  38844. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38845. }
  38846. };
  38847. /**
  38848. * Update a specific vertex buffer
  38849. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38850. * It will do nothing if the buffer is not updatable
  38851. * @param kind defines the data kind (Position, normal, etc...)
  38852. * @param data defines the data to use
  38853. * @param offset defines the offset in the target buffer where to store the data
  38854. * @param useBytes set to true if the offset is in bytes
  38855. */
  38856. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38857. if (useBytes === void 0) { useBytes = false; }
  38858. var vertexBuffer = this.getVertexBuffer(kind);
  38859. if (!vertexBuffer) {
  38860. return;
  38861. }
  38862. vertexBuffer.updateDirectly(data, offset, useBytes);
  38863. this.notifyUpdate(kind);
  38864. };
  38865. /**
  38866. * Update a specific vertex buffer
  38867. * This function will create a new buffer if the current one is not updatable
  38868. * @param kind defines the data kind (Position, normal, etc...)
  38869. * @param data defines the data to use
  38870. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38871. */
  38872. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38873. if (updateExtends === void 0) { updateExtends = false; }
  38874. var vertexBuffer = this.getVertexBuffer(kind);
  38875. if (!vertexBuffer) {
  38876. return;
  38877. }
  38878. vertexBuffer.update(data);
  38879. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38880. this._updateBoundingInfo(updateExtends, data);
  38881. }
  38882. this.notifyUpdate(kind);
  38883. };
  38884. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38885. if (updateExtends) {
  38886. this._updateExtend(data);
  38887. }
  38888. var meshes = this._meshes;
  38889. var numOfMeshes = meshes.length;
  38890. this._resetPointsArrayCache();
  38891. for (var index = 0; index < numOfMeshes; index++) {
  38892. var mesh = meshes[index];
  38893. if (updateExtends) {
  38894. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38895. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38896. var subMesh = mesh.subMeshes[subIndex];
  38897. subMesh.refreshBoundingInfo();
  38898. }
  38899. }
  38900. }
  38901. };
  38902. /** @hidden */
  38903. Geometry.prototype._bind = function (effect, indexToBind) {
  38904. if (!effect) {
  38905. return;
  38906. }
  38907. if (indexToBind === undefined) {
  38908. indexToBind = this._indexBuffer;
  38909. }
  38910. var vbs = this.getVertexBuffers();
  38911. if (!vbs) {
  38912. return;
  38913. }
  38914. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38915. this._engine.bindBuffers(vbs, indexToBind, effect);
  38916. return;
  38917. }
  38918. // Using VAO
  38919. if (!this._vertexArrayObjects[effect.key]) {
  38920. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38921. }
  38922. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38923. };
  38924. /**
  38925. * Gets total number of vertices
  38926. * @returns the total number of vertices
  38927. */
  38928. Geometry.prototype.getTotalVertices = function () {
  38929. if (!this.isReady()) {
  38930. return 0;
  38931. }
  38932. return this._totalVertices;
  38933. };
  38934. /**
  38935. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38936. * @param kind defines the data kind (Position, normal, etc...)
  38937. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38938. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38939. * @returns a float array containing vertex data
  38940. */
  38941. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38942. var vertexBuffer = this.getVertexBuffer(kind);
  38943. if (!vertexBuffer) {
  38944. return null;
  38945. }
  38946. var data = vertexBuffer.getData();
  38947. if (!data) {
  38948. return null;
  38949. }
  38950. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38951. var count = this._totalVertices * vertexBuffer.getSize();
  38952. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38953. var copy_1 = new Array(count);
  38954. vertexBuffer.forEach(count, function (value, index) {
  38955. copy_1[index] = value;
  38956. });
  38957. return copy_1;
  38958. }
  38959. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38960. if (data instanceof Array) {
  38961. var offset = vertexBuffer.byteOffset / 4;
  38962. return BABYLON.Tools.Slice(data, offset, offset + count);
  38963. }
  38964. else if (data instanceof ArrayBuffer) {
  38965. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38966. }
  38967. else {
  38968. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38969. }
  38970. }
  38971. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38972. return BABYLON.Tools.Slice(data);
  38973. }
  38974. return data;
  38975. };
  38976. /**
  38977. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38978. * @param kind defines the data kind (Position, normal, etc...)
  38979. * @returns true if the vertex buffer with the specified kind is updatable
  38980. */
  38981. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38982. var vb = this._vertexBuffers[kind];
  38983. if (!vb) {
  38984. return false;
  38985. }
  38986. return vb.isUpdatable();
  38987. };
  38988. /**
  38989. * Gets a specific vertex buffer
  38990. * @param kind defines the data kind (Position, normal, etc...)
  38991. * @returns a {BABYLON.VertexBuffer}
  38992. */
  38993. Geometry.prototype.getVertexBuffer = function (kind) {
  38994. if (!this.isReady()) {
  38995. return null;
  38996. }
  38997. return this._vertexBuffers[kind];
  38998. };
  38999. /**
  39000. * Returns all vertex buffers
  39001. * @return an object holding all vertex buffers indexed by kind
  39002. */
  39003. Geometry.prototype.getVertexBuffers = function () {
  39004. if (!this.isReady()) {
  39005. return null;
  39006. }
  39007. return this._vertexBuffers;
  39008. };
  39009. /**
  39010. * Gets a boolean indicating if specific vertex buffer is present
  39011. * @param kind defines the data kind (Position, normal, etc...)
  39012. * @returns true if data is present
  39013. */
  39014. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39015. if (!this._vertexBuffers) {
  39016. if (this._delayInfo) {
  39017. return this._delayInfo.indexOf(kind) !== -1;
  39018. }
  39019. return false;
  39020. }
  39021. return this._vertexBuffers[kind] !== undefined;
  39022. };
  39023. /**
  39024. * Gets a list of all attached data kinds (Position, normal, etc...)
  39025. * @returns a list of string containing all kinds
  39026. */
  39027. Geometry.prototype.getVerticesDataKinds = function () {
  39028. var result = [];
  39029. var kind;
  39030. if (!this._vertexBuffers && this._delayInfo) {
  39031. for (kind in this._delayInfo) {
  39032. result.push(kind);
  39033. }
  39034. }
  39035. else {
  39036. for (kind in this._vertexBuffers) {
  39037. result.push(kind);
  39038. }
  39039. }
  39040. return result;
  39041. };
  39042. /**
  39043. * Update index buffer
  39044. * @param indices defines the indices to store in the index buffer
  39045. * @param offset defines the offset in the target buffer where to store the data
  39046. */
  39047. Geometry.prototype.updateIndices = function (indices, offset) {
  39048. if (!this._indexBuffer) {
  39049. return;
  39050. }
  39051. if (!this._indexBufferIsUpdatable) {
  39052. this.setIndices(indices, null, true);
  39053. }
  39054. else {
  39055. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39056. }
  39057. };
  39058. /**
  39059. * Creates a new index buffer
  39060. * @param indices defines the indices to store in the index buffer
  39061. * @param totalVertices defines the total number of vertices (could be null)
  39062. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39063. */
  39064. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39065. if (totalVertices === void 0) { totalVertices = null; }
  39066. if (updatable === void 0) { updatable = false; }
  39067. if (this._indexBuffer) {
  39068. this._engine._releaseBuffer(this._indexBuffer);
  39069. }
  39070. this._disposeVertexArrayObjects();
  39071. this._indices = indices;
  39072. this._indexBufferIsUpdatable = updatable;
  39073. if (this._meshes.length !== 0 && this._indices) {
  39074. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39075. }
  39076. if (totalVertices != undefined) { // including null and undefined
  39077. this._totalVertices = totalVertices;
  39078. }
  39079. var meshes = this._meshes;
  39080. var numOfMeshes = meshes.length;
  39081. for (var index = 0; index < numOfMeshes; index++) {
  39082. meshes[index]._createGlobalSubMesh(true);
  39083. }
  39084. this.notifyUpdate();
  39085. };
  39086. /**
  39087. * Return the total number of indices
  39088. * @returns the total number of indices
  39089. */
  39090. Geometry.prototype.getTotalIndices = function () {
  39091. if (!this.isReady()) {
  39092. return 0;
  39093. }
  39094. return this._indices.length;
  39095. };
  39096. /**
  39097. * Gets the index buffer array
  39098. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39099. * @returns the index buffer array
  39100. */
  39101. Geometry.prototype.getIndices = function (copyWhenShared) {
  39102. if (!this.isReady()) {
  39103. return null;
  39104. }
  39105. var orig = this._indices;
  39106. if (!copyWhenShared || this._meshes.length === 1) {
  39107. return orig;
  39108. }
  39109. else {
  39110. var len = orig.length;
  39111. var copy = [];
  39112. for (var i = 0; i < len; i++) {
  39113. copy.push(orig[i]);
  39114. }
  39115. return copy;
  39116. }
  39117. };
  39118. /**
  39119. * Gets the index buffer
  39120. * @return the index buffer
  39121. */
  39122. Geometry.prototype.getIndexBuffer = function () {
  39123. if (!this.isReady()) {
  39124. return null;
  39125. }
  39126. return this._indexBuffer;
  39127. };
  39128. /** @hidden */
  39129. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39130. if (effect === void 0) { effect = null; }
  39131. if (!effect || !this._vertexArrayObjects) {
  39132. return;
  39133. }
  39134. if (this._vertexArrayObjects[effect.key]) {
  39135. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39136. delete this._vertexArrayObjects[effect.key];
  39137. }
  39138. };
  39139. /**
  39140. * Release the associated resources for a specific mesh
  39141. * @param mesh defines the source mesh
  39142. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39143. */
  39144. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39145. var meshes = this._meshes;
  39146. var index = meshes.indexOf(mesh);
  39147. if (index === -1) {
  39148. return;
  39149. }
  39150. meshes.splice(index, 1);
  39151. mesh._geometry = null;
  39152. if (meshes.length === 0 && shouldDispose) {
  39153. this.dispose();
  39154. }
  39155. };
  39156. /**
  39157. * Apply current geometry to a given mesh
  39158. * @param mesh defines the mesh to apply geometry to
  39159. */
  39160. Geometry.prototype.applyToMesh = function (mesh) {
  39161. if (mesh._geometry === this) {
  39162. return;
  39163. }
  39164. var previousGeometry = mesh._geometry;
  39165. if (previousGeometry) {
  39166. previousGeometry.releaseForMesh(mesh);
  39167. }
  39168. var meshes = this._meshes;
  39169. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39170. mesh._geometry = this;
  39171. this._scene.pushGeometry(this);
  39172. meshes.push(mesh);
  39173. if (this.isReady()) {
  39174. this._applyToMesh(mesh);
  39175. }
  39176. else {
  39177. mesh._boundingInfo = this._boundingInfo;
  39178. }
  39179. };
  39180. Geometry.prototype._updateExtend = function (data) {
  39181. if (data === void 0) { data = null; }
  39182. if (!data) {
  39183. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39184. }
  39185. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39186. };
  39187. Geometry.prototype._applyToMesh = function (mesh) {
  39188. var numOfMeshes = this._meshes.length;
  39189. // vertexBuffers
  39190. for (var kind in this._vertexBuffers) {
  39191. if (numOfMeshes === 1) {
  39192. this._vertexBuffers[kind].create();
  39193. }
  39194. var buffer = this._vertexBuffers[kind].getBuffer();
  39195. if (buffer)
  39196. buffer.references = numOfMeshes;
  39197. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39198. if (!this._extend) {
  39199. this._updateExtend();
  39200. }
  39201. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39202. mesh._createGlobalSubMesh(false);
  39203. //bounding info was just created again, world matrix should be applied again.
  39204. mesh._updateBoundingInfo();
  39205. }
  39206. }
  39207. // indexBuffer
  39208. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39209. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39210. }
  39211. if (this._indexBuffer) {
  39212. this._indexBuffer.references = numOfMeshes;
  39213. }
  39214. };
  39215. Geometry.prototype.notifyUpdate = function (kind) {
  39216. if (this.onGeometryUpdated) {
  39217. this.onGeometryUpdated(this, kind);
  39218. }
  39219. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39220. var mesh = _a[_i];
  39221. mesh._markSubMeshesAsAttributesDirty();
  39222. }
  39223. };
  39224. /**
  39225. * Load the geometry if it was flagged as delay loaded
  39226. * @param scene defines the hosting scene
  39227. * @param onLoaded defines a callback called when the geometry is loaded
  39228. */
  39229. Geometry.prototype.load = function (scene, onLoaded) {
  39230. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39231. return;
  39232. }
  39233. if (this.isReady()) {
  39234. if (onLoaded) {
  39235. onLoaded();
  39236. }
  39237. return;
  39238. }
  39239. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39240. this._queueLoad(scene, onLoaded);
  39241. };
  39242. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39243. var _this = this;
  39244. if (!this.delayLoadingFile) {
  39245. return;
  39246. }
  39247. scene._addPendingData(this);
  39248. scene._loadFile(this.delayLoadingFile, function (data) {
  39249. if (!_this._delayLoadingFunction) {
  39250. return;
  39251. }
  39252. _this._delayLoadingFunction(JSON.parse(data), _this);
  39253. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39254. _this._delayInfo = [];
  39255. scene._removePendingData(_this);
  39256. var meshes = _this._meshes;
  39257. var numOfMeshes = meshes.length;
  39258. for (var index = 0; index < numOfMeshes; index++) {
  39259. _this._applyToMesh(meshes[index]);
  39260. }
  39261. if (onLoaded) {
  39262. onLoaded();
  39263. }
  39264. }, undefined, true);
  39265. };
  39266. /**
  39267. * Invert the geometry to move from a right handed system to a left handed one.
  39268. */
  39269. Geometry.prototype.toLeftHanded = function () {
  39270. // Flip faces
  39271. var tIndices = this.getIndices(false);
  39272. if (tIndices != null && tIndices.length > 0) {
  39273. for (var i = 0; i < tIndices.length; i += 3) {
  39274. var tTemp = tIndices[i + 0];
  39275. tIndices[i + 0] = tIndices[i + 2];
  39276. tIndices[i + 2] = tTemp;
  39277. }
  39278. this.setIndices(tIndices);
  39279. }
  39280. // Negate position.z
  39281. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39282. if (tPositions != null && tPositions.length > 0) {
  39283. for (var i = 0; i < tPositions.length; i += 3) {
  39284. tPositions[i + 2] = -tPositions[i + 2];
  39285. }
  39286. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39287. }
  39288. // Negate normal.z
  39289. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39290. if (tNormals != null && tNormals.length > 0) {
  39291. for (var i = 0; i < tNormals.length; i += 3) {
  39292. tNormals[i + 2] = -tNormals[i + 2];
  39293. }
  39294. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39295. }
  39296. };
  39297. // Cache
  39298. /** @hidden */
  39299. Geometry.prototype._resetPointsArrayCache = function () {
  39300. this._positions = null;
  39301. };
  39302. /** @hidden */
  39303. Geometry.prototype._generatePointsArray = function () {
  39304. if (this._positions)
  39305. return true;
  39306. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39307. if (!data || data.length === 0) {
  39308. return false;
  39309. }
  39310. this._positions = [];
  39311. for (var index = 0; index < data.length; index += 3) {
  39312. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39313. }
  39314. return true;
  39315. };
  39316. /**
  39317. * Gets a value indicating if the geometry is disposed
  39318. * @returns true if the geometry was disposed
  39319. */
  39320. Geometry.prototype.isDisposed = function () {
  39321. return this._isDisposed;
  39322. };
  39323. Geometry.prototype._disposeVertexArrayObjects = function () {
  39324. if (this._vertexArrayObjects) {
  39325. for (var kind in this._vertexArrayObjects) {
  39326. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39327. }
  39328. this._vertexArrayObjects = {};
  39329. }
  39330. };
  39331. /**
  39332. * Free all associated resources
  39333. */
  39334. Geometry.prototype.dispose = function () {
  39335. var meshes = this._meshes;
  39336. var numOfMeshes = meshes.length;
  39337. var index;
  39338. for (index = 0; index < numOfMeshes; index++) {
  39339. this.releaseForMesh(meshes[index]);
  39340. }
  39341. this._meshes = [];
  39342. this._disposeVertexArrayObjects();
  39343. for (var kind in this._vertexBuffers) {
  39344. this._vertexBuffers[kind].dispose();
  39345. }
  39346. this._vertexBuffers = {};
  39347. this._totalVertices = 0;
  39348. if (this._indexBuffer) {
  39349. this._engine._releaseBuffer(this._indexBuffer);
  39350. }
  39351. this._indexBuffer = null;
  39352. this._indices = [];
  39353. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39354. this.delayLoadingFile = null;
  39355. this._delayLoadingFunction = null;
  39356. this._delayInfo = [];
  39357. this._boundingInfo = null;
  39358. this._scene.removeGeometry(this);
  39359. this._isDisposed = true;
  39360. };
  39361. /**
  39362. * Clone the current geometry into a new geometry
  39363. * @param id defines the unique ID of the new geometry
  39364. * @returns a new geometry object
  39365. */
  39366. Geometry.prototype.copy = function (id) {
  39367. var vertexData = new BABYLON.VertexData();
  39368. vertexData.indices = [];
  39369. var indices = this.getIndices();
  39370. if (indices) {
  39371. for (var index = 0; index < indices.length; index++) {
  39372. vertexData.indices.push(indices[index]);
  39373. }
  39374. }
  39375. var updatable = false;
  39376. var stopChecking = false;
  39377. var kind;
  39378. for (kind in this._vertexBuffers) {
  39379. // using slice() to make a copy of the array and not just reference it
  39380. var data = this.getVerticesData(kind);
  39381. if (data instanceof Float32Array) {
  39382. vertexData.set(new Float32Array(data), kind);
  39383. }
  39384. else {
  39385. vertexData.set(data.slice(0), kind);
  39386. }
  39387. if (!stopChecking) {
  39388. var vb = this.getVertexBuffer(kind);
  39389. if (vb) {
  39390. updatable = vb.isUpdatable();
  39391. stopChecking = !updatable;
  39392. }
  39393. }
  39394. }
  39395. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39396. geometry.delayLoadState = this.delayLoadState;
  39397. geometry.delayLoadingFile = this.delayLoadingFile;
  39398. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39399. for (kind in this._delayInfo) {
  39400. geometry._delayInfo = geometry._delayInfo || [];
  39401. geometry._delayInfo.push(kind);
  39402. }
  39403. // Bounding info
  39404. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39405. return geometry;
  39406. };
  39407. /**
  39408. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39409. * @return a JSON representation of the current geometry data (without the vertices data)
  39410. */
  39411. Geometry.prototype.serialize = function () {
  39412. var serializationObject = {};
  39413. serializationObject.id = this.id;
  39414. serializationObject.updatable = this._updatable;
  39415. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39416. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39417. }
  39418. return serializationObject;
  39419. };
  39420. Geometry.prototype.toNumberArray = function (origin) {
  39421. if (Array.isArray(origin)) {
  39422. return origin;
  39423. }
  39424. else {
  39425. return Array.prototype.slice.call(origin);
  39426. }
  39427. };
  39428. /**
  39429. * Serialize all vertices data into a JSON oject
  39430. * @returns a JSON representation of the current geometry data
  39431. */
  39432. Geometry.prototype.serializeVerticeData = function () {
  39433. var serializationObject = this.serialize();
  39434. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39435. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39436. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39437. serializationObject.positions._updatable = true;
  39438. }
  39439. }
  39440. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39441. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39442. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39443. serializationObject.normals._updatable = true;
  39444. }
  39445. }
  39446. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39447. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39448. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39449. serializationObject.tangets._updatable = true;
  39450. }
  39451. }
  39452. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39453. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39454. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39455. serializationObject.uvs._updatable = true;
  39456. }
  39457. }
  39458. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39459. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39460. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39461. serializationObject.uv2s._updatable = true;
  39462. }
  39463. }
  39464. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39465. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39466. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39467. serializationObject.uv3s._updatable = true;
  39468. }
  39469. }
  39470. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39471. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39472. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39473. serializationObject.uv4s._updatable = true;
  39474. }
  39475. }
  39476. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39477. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39478. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39479. serializationObject.uv5s._updatable = true;
  39480. }
  39481. }
  39482. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39483. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39484. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39485. serializationObject.uv6s._updatable = true;
  39486. }
  39487. }
  39488. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39489. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39490. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39491. serializationObject.colors._updatable = true;
  39492. }
  39493. }
  39494. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39495. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39496. serializationObject.matricesIndices._isExpanded = true;
  39497. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39498. serializationObject.matricesIndices._updatable = true;
  39499. }
  39500. }
  39501. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39502. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39503. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39504. serializationObject.matricesWeights._updatable = true;
  39505. }
  39506. }
  39507. serializationObject.indices = this.toNumberArray(this.getIndices());
  39508. return serializationObject;
  39509. };
  39510. // Statics
  39511. /**
  39512. * Extracts a clone of a mesh geometry
  39513. * @param mesh defines the source mesh
  39514. * @param id defines the unique ID of the new geometry object
  39515. * @returns the new geometry object
  39516. */
  39517. Geometry.ExtractFromMesh = function (mesh, id) {
  39518. var geometry = mesh._geometry;
  39519. if (!geometry) {
  39520. return null;
  39521. }
  39522. return geometry.copy(id);
  39523. };
  39524. /**
  39525. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39526. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39527. * Be aware Math.random() could cause collisions, but:
  39528. * "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"
  39529. * @returns a string containing a new GUID
  39530. */
  39531. Geometry.RandomId = function () {
  39532. return BABYLON.Tools.RandomId();
  39533. };
  39534. /** @hidden */
  39535. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39536. var scene = mesh.getScene();
  39537. // Geometry
  39538. var geometryId = parsedGeometry.geometryId;
  39539. if (geometryId) {
  39540. var geometry = scene.getGeometryByID(geometryId);
  39541. if (geometry) {
  39542. geometry.applyToMesh(mesh);
  39543. }
  39544. }
  39545. else if (parsedGeometry instanceof ArrayBuffer) {
  39546. var binaryInfo = mesh._binaryInfo;
  39547. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39548. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39549. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39550. }
  39551. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39552. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39553. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39554. }
  39555. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39556. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39557. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39558. }
  39559. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39560. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39561. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39562. }
  39563. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39564. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39565. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39566. }
  39567. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39568. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39569. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39570. }
  39571. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39572. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39573. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39574. }
  39575. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39576. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39577. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39578. }
  39579. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39580. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39581. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39582. }
  39583. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39584. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39585. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39586. }
  39587. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39588. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39589. var floatIndices = [];
  39590. for (var i = 0; i < matricesIndicesData.length; i++) {
  39591. var index = matricesIndicesData[i];
  39592. floatIndices.push(index & 0x000000FF);
  39593. floatIndices.push((index & 0x0000FF00) >> 8);
  39594. floatIndices.push((index & 0x00FF0000) >> 16);
  39595. floatIndices.push(index >> 24);
  39596. }
  39597. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39598. }
  39599. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39600. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39601. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39602. }
  39603. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39604. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39605. mesh.setIndices(indicesData, null);
  39606. }
  39607. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39608. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39609. mesh.subMeshes = [];
  39610. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39611. var materialIndex = subMeshesData[(i * 5) + 0];
  39612. var verticesStart = subMeshesData[(i * 5) + 1];
  39613. var verticesCount = subMeshesData[(i * 5) + 2];
  39614. var indexStart = subMeshesData[(i * 5) + 3];
  39615. var indexCount = subMeshesData[(i * 5) + 4];
  39616. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39617. }
  39618. }
  39619. }
  39620. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39621. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39622. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39623. if (parsedGeometry.tangents) {
  39624. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39625. }
  39626. if (parsedGeometry.uvs) {
  39627. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39628. }
  39629. if (parsedGeometry.uvs2) {
  39630. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39631. }
  39632. if (parsedGeometry.uvs3) {
  39633. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39634. }
  39635. if (parsedGeometry.uvs4) {
  39636. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39637. }
  39638. if (parsedGeometry.uvs5) {
  39639. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39640. }
  39641. if (parsedGeometry.uvs6) {
  39642. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39643. }
  39644. if (parsedGeometry.colors) {
  39645. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39646. }
  39647. if (parsedGeometry.matricesIndices) {
  39648. if (!parsedGeometry.matricesIndices._isExpanded) {
  39649. var floatIndices = [];
  39650. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39651. var matricesIndex = parsedGeometry.matricesIndices[i];
  39652. floatIndices.push(matricesIndex & 0x000000FF);
  39653. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39654. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39655. floatIndices.push(matricesIndex >> 24);
  39656. }
  39657. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39658. }
  39659. else {
  39660. delete parsedGeometry.matricesIndices._isExpanded;
  39661. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39662. }
  39663. }
  39664. if (parsedGeometry.matricesIndicesExtra) {
  39665. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39666. var floatIndices = [];
  39667. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39668. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39669. floatIndices.push(matricesIndex & 0x000000FF);
  39670. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39671. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39672. floatIndices.push(matricesIndex >> 24);
  39673. }
  39674. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39675. }
  39676. else {
  39677. delete parsedGeometry.matricesIndices._isExpanded;
  39678. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39679. }
  39680. }
  39681. if (parsedGeometry.matricesWeights) {
  39682. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39683. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39684. }
  39685. if (parsedGeometry.matricesWeightsExtra) {
  39686. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39687. }
  39688. mesh.setIndices(parsedGeometry.indices, null);
  39689. }
  39690. // SubMeshes
  39691. if (parsedGeometry.subMeshes) {
  39692. mesh.subMeshes = [];
  39693. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39694. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39695. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39696. }
  39697. }
  39698. // Flat shading
  39699. if (mesh._shouldGenerateFlatShading) {
  39700. mesh.convertToFlatShadedMesh();
  39701. delete mesh._shouldGenerateFlatShading;
  39702. }
  39703. // Update
  39704. mesh.computeWorldMatrix(true);
  39705. // Octree
  39706. var sceneOctree = scene.selectionOctree;
  39707. if (sceneOctree !== undefined && sceneOctree !== null) {
  39708. sceneOctree.addMesh(mesh);
  39709. }
  39710. };
  39711. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39712. var epsilon = 1e-3;
  39713. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39714. return;
  39715. }
  39716. var noInfluenceBoneIndex = 0.0;
  39717. if (parsedGeometry.skeletonId > -1) {
  39718. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39719. if (!skeleton) {
  39720. return;
  39721. }
  39722. noInfluenceBoneIndex = skeleton.bones.length;
  39723. }
  39724. else {
  39725. return;
  39726. }
  39727. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39728. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39729. var matricesWeights = parsedGeometry.matricesWeights;
  39730. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39731. var influencers = parsedGeometry.numBoneInfluencer;
  39732. var size = matricesWeights.length;
  39733. for (var i = 0; i < size; i += 4) {
  39734. var weight = 0.0;
  39735. var firstZeroWeight = -1;
  39736. for (var j = 0; j < 4; j++) {
  39737. var w = matricesWeights[i + j];
  39738. weight += w;
  39739. if (w < epsilon && firstZeroWeight < 0) {
  39740. firstZeroWeight = j;
  39741. }
  39742. }
  39743. if (matricesWeightsExtra) {
  39744. for (var j = 0; j < 4; j++) {
  39745. var w = matricesWeightsExtra[i + j];
  39746. weight += w;
  39747. if (w < epsilon && firstZeroWeight < 0) {
  39748. firstZeroWeight = j + 4;
  39749. }
  39750. }
  39751. }
  39752. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39753. firstZeroWeight = influencers - 1;
  39754. }
  39755. if (weight > epsilon) {
  39756. var mweight = 1.0 / weight;
  39757. for (var j = 0; j < 4; j++) {
  39758. matricesWeights[i + j] *= mweight;
  39759. }
  39760. if (matricesWeightsExtra) {
  39761. for (var j = 0; j < 4; j++) {
  39762. matricesWeightsExtra[i + j] *= mweight;
  39763. }
  39764. }
  39765. }
  39766. else {
  39767. if (firstZeroWeight >= 4) {
  39768. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39769. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39770. }
  39771. else {
  39772. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39773. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39774. }
  39775. }
  39776. }
  39777. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39778. if (parsedGeometry.matricesWeightsExtra) {
  39779. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39780. }
  39781. };
  39782. /**
  39783. * Create a new geometry from persisted data (Using .babylon file format)
  39784. * @param parsedVertexData defines the persisted data
  39785. * @param scene defines the hosting scene
  39786. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39787. * @returns the new geometry object
  39788. */
  39789. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39790. if (scene.getGeometryByID(parsedVertexData.id)) {
  39791. return null; // null since geometry could be something else than a box...
  39792. }
  39793. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39794. if (BABYLON.Tags) {
  39795. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39796. }
  39797. if (parsedVertexData.delayLoadingFile) {
  39798. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39799. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39800. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39801. geometry._delayInfo = [];
  39802. if (parsedVertexData.hasUVs) {
  39803. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39804. }
  39805. if (parsedVertexData.hasUVs2) {
  39806. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39807. }
  39808. if (parsedVertexData.hasUVs3) {
  39809. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39810. }
  39811. if (parsedVertexData.hasUVs4) {
  39812. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39813. }
  39814. if (parsedVertexData.hasUVs5) {
  39815. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39816. }
  39817. if (parsedVertexData.hasUVs6) {
  39818. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39819. }
  39820. if (parsedVertexData.hasColors) {
  39821. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39822. }
  39823. if (parsedVertexData.hasMatricesIndices) {
  39824. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39825. }
  39826. if (parsedVertexData.hasMatricesWeights) {
  39827. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39828. }
  39829. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39830. }
  39831. else {
  39832. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39833. }
  39834. scene.pushGeometry(geometry, true);
  39835. return geometry;
  39836. };
  39837. return Geometry;
  39838. }());
  39839. BABYLON.Geometry = Geometry;
  39840. // Primitives
  39841. /// Abstract class
  39842. /**
  39843. * Abstract class used to provide common services for all typed geometries
  39844. * @hidden
  39845. */
  39846. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39847. __extends(_PrimitiveGeometry, _super);
  39848. /**
  39849. * Creates a new typed geometry
  39850. * @param id defines the unique ID of the geometry
  39851. * @param scene defines the hosting scene
  39852. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39853. * @param mesh defines the hosting mesh (can be null)
  39854. */
  39855. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39856. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39857. if (mesh === void 0) { mesh = null; }
  39858. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39859. _this._canBeRegenerated = _canBeRegenerated;
  39860. _this._beingRegenerated = true;
  39861. _this.regenerate();
  39862. _this._beingRegenerated = false;
  39863. return _this;
  39864. }
  39865. /**
  39866. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39867. * @returns true if the geometry can be regenerated
  39868. */
  39869. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39870. return this._canBeRegenerated;
  39871. };
  39872. /**
  39873. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39874. */
  39875. _PrimitiveGeometry.prototype.regenerate = function () {
  39876. if (!this._canBeRegenerated) {
  39877. return;
  39878. }
  39879. this._beingRegenerated = true;
  39880. this.setAllVerticesData(this._regenerateVertexData(), false);
  39881. this._beingRegenerated = false;
  39882. };
  39883. /**
  39884. * Clone the geometry
  39885. * @param id defines the unique ID of the new geometry
  39886. * @returns the new geometry
  39887. */
  39888. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39889. return _super.prototype.copy.call(this, id);
  39890. };
  39891. // overrides
  39892. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39893. if (!this._beingRegenerated) {
  39894. return;
  39895. }
  39896. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39897. };
  39898. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39899. if (!this._beingRegenerated) {
  39900. return;
  39901. }
  39902. _super.prototype.setVerticesData.call(this, kind, data, false);
  39903. };
  39904. // to override
  39905. /** @hidden */
  39906. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39907. throw new Error("Abstract method");
  39908. };
  39909. _PrimitiveGeometry.prototype.copy = function (id) {
  39910. throw new Error("Must be overriden in sub-classes.");
  39911. };
  39912. _PrimitiveGeometry.prototype.serialize = function () {
  39913. var serializationObject = _super.prototype.serialize.call(this);
  39914. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39915. return serializationObject;
  39916. };
  39917. return _PrimitiveGeometry;
  39918. }(Geometry));
  39919. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39920. /**
  39921. * Creates a ribbon geometry
  39922. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39923. */
  39924. var RibbonGeometry = /** @class */ (function (_super) {
  39925. __extends(RibbonGeometry, _super);
  39926. /**
  39927. * Creates a ribbon geometry
  39928. * @param id defines the unique ID of the geometry
  39929. * @param scene defines the hosting scene
  39930. * @param pathArray defines the array of paths to use
  39931. * @param closeArray defines if the last path and the first path must be joined
  39932. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39933. * @param offset defines the offset between points
  39934. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39935. * @param mesh defines the hosting mesh (can be null)
  39936. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39937. */
  39938. function RibbonGeometry(id, scene,
  39939. /**
  39940. * Defines the array of paths to use
  39941. */
  39942. pathArray,
  39943. /**
  39944. * Defines if the last and first points of each path in your pathArray must be joined
  39945. */
  39946. closeArray,
  39947. /**
  39948. * Defines if the last and first points of each path in your pathArray must be joined
  39949. */
  39950. closePath,
  39951. /**
  39952. * Defines the offset between points
  39953. */
  39954. offset, canBeRegenerated, mesh,
  39955. /**
  39956. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39957. */
  39958. side) {
  39959. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39960. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39961. _this.pathArray = pathArray;
  39962. _this.closeArray = closeArray;
  39963. _this.closePath = closePath;
  39964. _this.offset = offset;
  39965. _this.side = side;
  39966. return _this;
  39967. }
  39968. /** @hidden */
  39969. RibbonGeometry.prototype._regenerateVertexData = function () {
  39970. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39971. };
  39972. RibbonGeometry.prototype.copy = function (id) {
  39973. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39974. };
  39975. return RibbonGeometry;
  39976. }(_PrimitiveGeometry));
  39977. BABYLON.RibbonGeometry = RibbonGeometry;
  39978. /**
  39979. * Creates a box geometry
  39980. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39981. */
  39982. var BoxGeometry = /** @class */ (function (_super) {
  39983. __extends(BoxGeometry, _super);
  39984. /**
  39985. * Creates a box geometry
  39986. * @param id defines the unique ID of the geometry
  39987. * @param scene defines the hosting scene
  39988. * @param size defines the zise of the box (width, height and depth are the same)
  39989. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39990. * @param mesh defines the hosting mesh (can be null)
  39991. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39992. */
  39993. function BoxGeometry(id, scene,
  39994. /**
  39995. * Defines the zise of the box (width, height and depth are the same)
  39996. */
  39997. size, canBeRegenerated, mesh,
  39998. /**
  39999. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40000. */
  40001. side) {
  40002. if (mesh === void 0) { mesh = null; }
  40003. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40004. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40005. _this.size = size;
  40006. _this.side = side;
  40007. return _this;
  40008. }
  40009. BoxGeometry.prototype._regenerateVertexData = function () {
  40010. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40011. };
  40012. BoxGeometry.prototype.copy = function (id) {
  40013. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40014. };
  40015. BoxGeometry.prototype.serialize = function () {
  40016. var serializationObject = _super.prototype.serialize.call(this);
  40017. serializationObject.size = this.size;
  40018. return serializationObject;
  40019. };
  40020. BoxGeometry.Parse = function (parsedBox, scene) {
  40021. if (scene.getGeometryByID(parsedBox.id)) {
  40022. return null; // null since geometry could be something else than a box...
  40023. }
  40024. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40025. if (BABYLON.Tags) {
  40026. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40027. }
  40028. scene.pushGeometry(box, true);
  40029. return box;
  40030. };
  40031. return BoxGeometry;
  40032. }(_PrimitiveGeometry));
  40033. BABYLON.BoxGeometry = BoxGeometry;
  40034. /**
  40035. * Creates a sphere geometry
  40036. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40037. */
  40038. var SphereGeometry = /** @class */ (function (_super) {
  40039. __extends(SphereGeometry, _super);
  40040. /**
  40041. * Create a new sphere geometry
  40042. * @param id defines the unique ID of the geometry
  40043. * @param scene defines the hosting scene
  40044. * @param segments defines the number of segments to use to create the sphere
  40045. * @param diameter defines the diameter of the sphere
  40046. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40047. * @param mesh defines the hosting mesh (can be null)
  40048. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40049. */
  40050. function SphereGeometry(id, scene,
  40051. /**
  40052. * Defines the number of segments to use to create the sphere
  40053. */
  40054. segments,
  40055. /**
  40056. * Defines the diameter of the sphere
  40057. */
  40058. diameter, canBeRegenerated, mesh,
  40059. /**
  40060. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40061. */
  40062. side) {
  40063. if (mesh === void 0) { mesh = null; }
  40064. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40065. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40066. _this.segments = segments;
  40067. _this.diameter = diameter;
  40068. _this.side = side;
  40069. return _this;
  40070. }
  40071. SphereGeometry.prototype._regenerateVertexData = function () {
  40072. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40073. };
  40074. SphereGeometry.prototype.copy = function (id) {
  40075. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40076. };
  40077. SphereGeometry.prototype.serialize = function () {
  40078. var serializationObject = _super.prototype.serialize.call(this);
  40079. serializationObject.segments = this.segments;
  40080. serializationObject.diameter = this.diameter;
  40081. return serializationObject;
  40082. };
  40083. SphereGeometry.Parse = function (parsedSphere, scene) {
  40084. if (scene.getGeometryByID(parsedSphere.id)) {
  40085. return null; // null since geometry could be something else than a sphere...
  40086. }
  40087. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40088. if (BABYLON.Tags) {
  40089. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40090. }
  40091. scene.pushGeometry(sphere, true);
  40092. return sphere;
  40093. };
  40094. return SphereGeometry;
  40095. }(_PrimitiveGeometry));
  40096. BABYLON.SphereGeometry = SphereGeometry;
  40097. /**
  40098. * Creates a disc geometry
  40099. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40100. */
  40101. var DiscGeometry = /** @class */ (function (_super) {
  40102. __extends(DiscGeometry, _super);
  40103. /**
  40104. * Creates a new disc geometry
  40105. * @param id defines the unique ID of the geometry
  40106. * @param scene defines the hosting scene
  40107. * @param radius defines the radius of the disc
  40108. * @param tessellation defines the tesselation factor to apply to the disc
  40109. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40110. * @param mesh defines the hosting mesh (can be null)
  40111. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40112. */
  40113. function DiscGeometry(id, scene,
  40114. /**
  40115. * Defines the radius of the disc
  40116. */
  40117. radius,
  40118. /**
  40119. * Defines the tesselation factor to apply to the disc
  40120. */
  40121. tessellation, canBeRegenerated, mesh,
  40122. /**
  40123. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40124. */
  40125. side) {
  40126. if (mesh === void 0) { mesh = null; }
  40127. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40128. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40129. _this.radius = radius;
  40130. _this.tessellation = tessellation;
  40131. _this.side = side;
  40132. return _this;
  40133. }
  40134. DiscGeometry.prototype._regenerateVertexData = function () {
  40135. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40136. };
  40137. DiscGeometry.prototype.copy = function (id) {
  40138. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40139. };
  40140. return DiscGeometry;
  40141. }(_PrimitiveGeometry));
  40142. BABYLON.DiscGeometry = DiscGeometry;
  40143. /**
  40144. * Creates a new cylinder geometry
  40145. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40146. */
  40147. var CylinderGeometry = /** @class */ (function (_super) {
  40148. __extends(CylinderGeometry, _super);
  40149. /**
  40150. * Creates a new cylinder geometry
  40151. * @param id defines the unique ID of the geometry
  40152. * @param scene defines the hosting scene
  40153. * @param height defines the height of the cylinder
  40154. * @param diameterTop defines the diameter of the cylinder's top cap
  40155. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40156. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40157. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40158. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40159. * @param mesh defines the hosting mesh (can be null)
  40160. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40161. */
  40162. function CylinderGeometry(id, scene,
  40163. /**
  40164. * Defines the height of the cylinder
  40165. */
  40166. height,
  40167. /**
  40168. * Defines the diameter of the cylinder's top cap
  40169. */
  40170. diameterTop,
  40171. /**
  40172. * Defines the diameter of the cylinder's bottom cap
  40173. */
  40174. diameterBottom,
  40175. /**
  40176. * Defines the tessellation factor to apply to the cylinder
  40177. */
  40178. tessellation,
  40179. /**
  40180. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40181. */
  40182. subdivisions, canBeRegenerated, mesh,
  40183. /**
  40184. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40185. */
  40186. side) {
  40187. if (subdivisions === void 0) { subdivisions = 1; }
  40188. if (mesh === void 0) { mesh = null; }
  40189. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40190. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40191. _this.height = height;
  40192. _this.diameterTop = diameterTop;
  40193. _this.diameterBottom = diameterBottom;
  40194. _this.tessellation = tessellation;
  40195. _this.subdivisions = subdivisions;
  40196. _this.side = side;
  40197. return _this;
  40198. }
  40199. CylinderGeometry.prototype._regenerateVertexData = function () {
  40200. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40201. };
  40202. CylinderGeometry.prototype.copy = function (id) {
  40203. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40204. };
  40205. CylinderGeometry.prototype.serialize = function () {
  40206. var serializationObject = _super.prototype.serialize.call(this);
  40207. serializationObject.height = this.height;
  40208. serializationObject.diameterTop = this.diameterTop;
  40209. serializationObject.diameterBottom = this.diameterBottom;
  40210. serializationObject.tessellation = this.tessellation;
  40211. return serializationObject;
  40212. };
  40213. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40214. if (scene.getGeometryByID(parsedCylinder.id)) {
  40215. return null; // null since geometry could be something else than a cylinder...
  40216. }
  40217. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40218. if (BABYLON.Tags) {
  40219. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40220. }
  40221. scene.pushGeometry(cylinder, true);
  40222. return cylinder;
  40223. };
  40224. return CylinderGeometry;
  40225. }(_PrimitiveGeometry));
  40226. BABYLON.CylinderGeometry = CylinderGeometry;
  40227. /**
  40228. * Creates a new torus geometry
  40229. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40230. */
  40231. var TorusGeometry = /** @class */ (function (_super) {
  40232. __extends(TorusGeometry, _super);
  40233. /**
  40234. * Creates a new torus geometry
  40235. * @param id defines the unique ID of the geometry
  40236. * @param scene defines the hosting scene
  40237. * @param diameter defines the diameter of the torus
  40238. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40239. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40240. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40241. * @param mesh defines the hosting mesh (can be null)
  40242. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40243. */
  40244. function TorusGeometry(id, scene,
  40245. /**
  40246. * Defines the diameter of the torus
  40247. */
  40248. diameter,
  40249. /**
  40250. * Defines the thickness of the torus (ie. internal diameter)
  40251. */
  40252. thickness,
  40253. /**
  40254. * Defines the tesselation factor to apply to the torus
  40255. */
  40256. tessellation, canBeRegenerated, mesh,
  40257. /**
  40258. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40259. */
  40260. side) {
  40261. if (mesh === void 0) { mesh = null; }
  40262. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40263. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40264. _this.diameter = diameter;
  40265. _this.thickness = thickness;
  40266. _this.tessellation = tessellation;
  40267. _this.side = side;
  40268. return _this;
  40269. }
  40270. TorusGeometry.prototype._regenerateVertexData = function () {
  40271. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40272. };
  40273. TorusGeometry.prototype.copy = function (id) {
  40274. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40275. };
  40276. TorusGeometry.prototype.serialize = function () {
  40277. var serializationObject = _super.prototype.serialize.call(this);
  40278. serializationObject.diameter = this.diameter;
  40279. serializationObject.thickness = this.thickness;
  40280. serializationObject.tessellation = this.tessellation;
  40281. return serializationObject;
  40282. };
  40283. TorusGeometry.Parse = function (parsedTorus, scene) {
  40284. if (scene.getGeometryByID(parsedTorus.id)) {
  40285. return null; // null since geometry could be something else than a torus...
  40286. }
  40287. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40288. if (BABYLON.Tags) {
  40289. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40290. }
  40291. scene.pushGeometry(torus, true);
  40292. return torus;
  40293. };
  40294. return TorusGeometry;
  40295. }(_PrimitiveGeometry));
  40296. BABYLON.TorusGeometry = TorusGeometry;
  40297. /**
  40298. * Creates a new ground geometry
  40299. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40300. */
  40301. var GroundGeometry = /** @class */ (function (_super) {
  40302. __extends(GroundGeometry, _super);
  40303. /**
  40304. * Creates a new ground geometry
  40305. * @param id defines the unique ID of the geometry
  40306. * @param scene defines the hosting scene
  40307. * @param width defines the width of the ground
  40308. * @param height defines the height of the ground
  40309. * @param subdivisions defines the subdivisions to apply to the ground
  40310. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40311. * @param mesh defines the hosting mesh (can be null)
  40312. */
  40313. function GroundGeometry(id, scene,
  40314. /**
  40315. * Defines the width of the ground
  40316. */
  40317. width,
  40318. /**
  40319. * Defines the height of the ground
  40320. */
  40321. height,
  40322. /**
  40323. * Defines the subdivisions to apply to the ground
  40324. */
  40325. subdivisions, canBeRegenerated, mesh) {
  40326. if (mesh === void 0) { mesh = null; }
  40327. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40328. _this.width = width;
  40329. _this.height = height;
  40330. _this.subdivisions = subdivisions;
  40331. return _this;
  40332. }
  40333. GroundGeometry.prototype._regenerateVertexData = function () {
  40334. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40335. };
  40336. GroundGeometry.prototype.copy = function (id) {
  40337. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40338. };
  40339. GroundGeometry.prototype.serialize = function () {
  40340. var serializationObject = _super.prototype.serialize.call(this);
  40341. serializationObject.width = this.width;
  40342. serializationObject.height = this.height;
  40343. serializationObject.subdivisions = this.subdivisions;
  40344. return serializationObject;
  40345. };
  40346. GroundGeometry.Parse = function (parsedGround, scene) {
  40347. if (scene.getGeometryByID(parsedGround.id)) {
  40348. return null; // null since geometry could be something else than a ground...
  40349. }
  40350. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40351. if (BABYLON.Tags) {
  40352. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40353. }
  40354. scene.pushGeometry(ground, true);
  40355. return ground;
  40356. };
  40357. return GroundGeometry;
  40358. }(_PrimitiveGeometry));
  40359. BABYLON.GroundGeometry = GroundGeometry;
  40360. /**
  40361. * Creates a tiled ground geometry
  40362. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40363. */
  40364. var TiledGroundGeometry = /** @class */ (function (_super) {
  40365. __extends(TiledGroundGeometry, _super);
  40366. /**
  40367. * Creates a tiled ground geometry
  40368. * @param id defines the unique ID of the geometry
  40369. * @param scene defines the hosting scene
  40370. * @param xmin defines the minimum value on X axis
  40371. * @param zmin defines the minimum value on Z axis
  40372. * @param xmax defines the maximum value on X axis
  40373. * @param zmax defines the maximum value on Z axis
  40374. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40375. * @param precision defines the precision to use when computing the tiles
  40376. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40377. * @param mesh defines the hosting mesh (can be null)
  40378. */
  40379. function TiledGroundGeometry(id, scene,
  40380. /**
  40381. * Defines the minimum value on X axis
  40382. */
  40383. xmin,
  40384. /**
  40385. * Defines the minimum value on Z axis
  40386. */
  40387. zmin,
  40388. /**
  40389. * Defines the maximum value on X axis
  40390. */
  40391. xmax,
  40392. /**
  40393. * Defines the maximum value on Z axis
  40394. */
  40395. zmax,
  40396. /**
  40397. * Defines the subdivisions to apply to the ground
  40398. */
  40399. subdivisions,
  40400. /**
  40401. * Defines the precision to use when computing the tiles
  40402. */
  40403. precision, canBeRegenerated, mesh) {
  40404. if (mesh === void 0) { mesh = null; }
  40405. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40406. _this.xmin = xmin;
  40407. _this.zmin = zmin;
  40408. _this.xmax = xmax;
  40409. _this.zmax = zmax;
  40410. _this.subdivisions = subdivisions;
  40411. _this.precision = precision;
  40412. return _this;
  40413. }
  40414. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40415. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40416. };
  40417. TiledGroundGeometry.prototype.copy = function (id) {
  40418. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40419. };
  40420. return TiledGroundGeometry;
  40421. }(_PrimitiveGeometry));
  40422. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40423. /**
  40424. * Creates a plane geometry
  40425. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40426. */
  40427. var PlaneGeometry = /** @class */ (function (_super) {
  40428. __extends(PlaneGeometry, _super);
  40429. /**
  40430. * Creates a plane geometry
  40431. * @param id defines the unique ID of the geometry
  40432. * @param scene defines the hosting scene
  40433. * @param size defines the size of the plane (width === height)
  40434. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40435. * @param mesh defines the hosting mesh (can be null)
  40436. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40437. */
  40438. function PlaneGeometry(id, scene,
  40439. /**
  40440. * Defines the size of the plane (width === height)
  40441. */
  40442. size, canBeRegenerated, mesh,
  40443. /**
  40444. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40445. */
  40446. side) {
  40447. if (mesh === void 0) { mesh = null; }
  40448. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40449. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40450. _this.size = size;
  40451. _this.side = side;
  40452. return _this;
  40453. }
  40454. PlaneGeometry.prototype._regenerateVertexData = function () {
  40455. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40456. };
  40457. PlaneGeometry.prototype.copy = function (id) {
  40458. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40459. };
  40460. PlaneGeometry.prototype.serialize = function () {
  40461. var serializationObject = _super.prototype.serialize.call(this);
  40462. serializationObject.size = this.size;
  40463. return serializationObject;
  40464. };
  40465. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40466. if (scene.getGeometryByID(parsedPlane.id)) {
  40467. return null; // null since geometry could be something else than a ground...
  40468. }
  40469. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40470. if (BABYLON.Tags) {
  40471. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40472. }
  40473. scene.pushGeometry(plane, true);
  40474. return plane;
  40475. };
  40476. return PlaneGeometry;
  40477. }(_PrimitiveGeometry));
  40478. BABYLON.PlaneGeometry = PlaneGeometry;
  40479. /**
  40480. * Creates a torus knot geometry
  40481. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40482. */
  40483. var TorusKnotGeometry = /** @class */ (function (_super) {
  40484. __extends(TorusKnotGeometry, _super);
  40485. /**
  40486. * Creates a torus knot geometry
  40487. * @param id defines the unique ID of the geometry
  40488. * @param scene defines the hosting scene
  40489. * @param radius defines the radius of the torus knot
  40490. * @param tube defines the thickness of the torus knot tube
  40491. * @param radialSegments defines the number of radial segments
  40492. * @param tubularSegments defines the number of tubular segments
  40493. * @param p defines the first number of windings
  40494. * @param q defines the second number of windings
  40495. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40496. * @param mesh defines the hosting mesh (can be null)
  40497. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40498. */
  40499. function TorusKnotGeometry(id, scene,
  40500. /**
  40501. * Defines the radius of the torus knot
  40502. */
  40503. radius,
  40504. /**
  40505. * Defines the thickness of the torus knot tube
  40506. */
  40507. tube,
  40508. /**
  40509. * Defines the number of radial segments
  40510. */
  40511. radialSegments,
  40512. /**
  40513. * Defines the number of tubular segments
  40514. */
  40515. tubularSegments,
  40516. /**
  40517. * Defines the first number of windings
  40518. */
  40519. p,
  40520. /**
  40521. * Defines the second number of windings
  40522. */
  40523. q, canBeRegenerated, mesh,
  40524. /**
  40525. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40526. */
  40527. side) {
  40528. if (mesh === void 0) { mesh = null; }
  40529. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40530. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40531. _this.radius = radius;
  40532. _this.tube = tube;
  40533. _this.radialSegments = radialSegments;
  40534. _this.tubularSegments = tubularSegments;
  40535. _this.p = p;
  40536. _this.q = q;
  40537. _this.side = side;
  40538. return _this;
  40539. }
  40540. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40541. 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 });
  40542. };
  40543. TorusKnotGeometry.prototype.copy = function (id) {
  40544. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40545. };
  40546. TorusKnotGeometry.prototype.serialize = function () {
  40547. var serializationObject = _super.prototype.serialize.call(this);
  40548. serializationObject.radius = this.radius;
  40549. serializationObject.tube = this.tube;
  40550. serializationObject.radialSegments = this.radialSegments;
  40551. serializationObject.tubularSegments = this.tubularSegments;
  40552. serializationObject.p = this.p;
  40553. serializationObject.q = this.q;
  40554. return serializationObject;
  40555. };
  40556. ;
  40557. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40558. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40559. return null; // null since geometry could be something else than a ground...
  40560. }
  40561. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40562. if (BABYLON.Tags) {
  40563. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40564. }
  40565. scene.pushGeometry(torusKnot, true);
  40566. return torusKnot;
  40567. };
  40568. return TorusKnotGeometry;
  40569. }(_PrimitiveGeometry));
  40570. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40571. //}
  40572. })(BABYLON || (BABYLON = {}));
  40573. //# sourceMappingURL=babylon.geometry.js.map
  40574. var BABYLON;
  40575. (function (BABYLON) {
  40576. /**
  40577. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40578. */
  40579. var PerformanceMonitor = /** @class */ (function () {
  40580. /**
  40581. * constructor
  40582. * @param frameSampleSize The number of samples required to saturate the sliding window
  40583. */
  40584. function PerformanceMonitor(frameSampleSize) {
  40585. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40586. this._enabled = true;
  40587. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40588. }
  40589. /**
  40590. * Samples current frame
  40591. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40592. */
  40593. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40594. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40595. if (!this._enabled)
  40596. return;
  40597. if (this._lastFrameTimeMs != null) {
  40598. var dt = timeMs - this._lastFrameTimeMs;
  40599. this._rollingFrameTime.add(dt);
  40600. }
  40601. this._lastFrameTimeMs = timeMs;
  40602. };
  40603. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40604. /**
  40605. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40606. * @return Average frame time in milliseconds
  40607. */
  40608. get: function () {
  40609. return this._rollingFrameTime.average;
  40610. },
  40611. enumerable: true,
  40612. configurable: true
  40613. });
  40614. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40615. /**
  40616. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40617. * @return Frame time variance in milliseconds squared
  40618. */
  40619. get: function () {
  40620. return this._rollingFrameTime.variance;
  40621. },
  40622. enumerable: true,
  40623. configurable: true
  40624. });
  40625. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40626. /**
  40627. * Returns the frame time of the most recent frame
  40628. * @return Frame time in milliseconds
  40629. */
  40630. get: function () {
  40631. return this._rollingFrameTime.history(0);
  40632. },
  40633. enumerable: true,
  40634. configurable: true
  40635. });
  40636. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40637. /**
  40638. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40639. * @return Framerate in frames per second
  40640. */
  40641. get: function () {
  40642. return 1000.0 / this._rollingFrameTime.average;
  40643. },
  40644. enumerable: true,
  40645. configurable: true
  40646. });
  40647. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40648. /**
  40649. * Returns the average framerate in frames per second using the most recent frame time
  40650. * @return Framerate in frames per second
  40651. */
  40652. get: function () {
  40653. var history = this._rollingFrameTime.history(0);
  40654. if (history === 0) {
  40655. return 0;
  40656. }
  40657. return 1000.0 / history;
  40658. },
  40659. enumerable: true,
  40660. configurable: true
  40661. });
  40662. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40663. /**
  40664. * Returns true if enough samples have been taken to completely fill the sliding window
  40665. * @return true if saturated
  40666. */
  40667. get: function () {
  40668. return this._rollingFrameTime.isSaturated();
  40669. },
  40670. enumerable: true,
  40671. configurable: true
  40672. });
  40673. /**
  40674. * Enables contributions to the sliding window sample set
  40675. */
  40676. PerformanceMonitor.prototype.enable = function () {
  40677. this._enabled = true;
  40678. };
  40679. /**
  40680. * Disables contributions to the sliding window sample set
  40681. * Samples will not be interpolated over the disabled period
  40682. */
  40683. PerformanceMonitor.prototype.disable = function () {
  40684. this._enabled = false;
  40685. //clear last sample to avoid interpolating over the disabled period when next enabled
  40686. this._lastFrameTimeMs = null;
  40687. };
  40688. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40689. /**
  40690. * Returns true if sampling is enabled
  40691. * @return true if enabled
  40692. */
  40693. get: function () {
  40694. return this._enabled;
  40695. },
  40696. enumerable: true,
  40697. configurable: true
  40698. });
  40699. /**
  40700. * Resets performance monitor
  40701. */
  40702. PerformanceMonitor.prototype.reset = function () {
  40703. //clear last sample to avoid interpolating over the disabled period when next enabled
  40704. this._lastFrameTimeMs = null;
  40705. //wipe record
  40706. this._rollingFrameTime.reset();
  40707. };
  40708. return PerformanceMonitor;
  40709. }());
  40710. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40711. /**
  40712. * RollingAverage
  40713. *
  40714. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40715. */
  40716. var RollingAverage = /** @class */ (function () {
  40717. /**
  40718. * constructor
  40719. * @param length The number of samples required to saturate the sliding window
  40720. */
  40721. function RollingAverage(length) {
  40722. this._samples = new Array(length);
  40723. this.reset();
  40724. }
  40725. /**
  40726. * Adds a sample to the sample set
  40727. * @param v The sample value
  40728. */
  40729. RollingAverage.prototype.add = function (v) {
  40730. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40731. var delta;
  40732. //we need to check if we've already wrapped round
  40733. if (this.isSaturated()) {
  40734. //remove bottom of stack from mean
  40735. var bottomValue = this._samples[this._pos];
  40736. delta = bottomValue - this.average;
  40737. this.average -= delta / (this._sampleCount - 1);
  40738. this._m2 -= delta * (bottomValue - this.average);
  40739. }
  40740. else {
  40741. this._sampleCount++;
  40742. }
  40743. //add new value to mean
  40744. delta = v - this.average;
  40745. this.average += delta / (this._sampleCount);
  40746. this._m2 += delta * (v - this.average);
  40747. //set the new variance
  40748. this.variance = this._m2 / (this._sampleCount - 1);
  40749. this._samples[this._pos] = v;
  40750. this._pos++;
  40751. this._pos %= this._samples.length; //positive wrap around
  40752. };
  40753. /**
  40754. * Returns previously added values or null if outside of history or outside the sliding window domain
  40755. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40756. * @return Value previously recorded with add() or null if outside of range
  40757. */
  40758. RollingAverage.prototype.history = function (i) {
  40759. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40760. return 0;
  40761. }
  40762. var i0 = this._wrapPosition(this._pos - 1.0);
  40763. return this._samples[this._wrapPosition(i0 - i)];
  40764. };
  40765. /**
  40766. * Returns true if enough samples have been taken to completely fill the sliding window
  40767. * @return true if sample-set saturated
  40768. */
  40769. RollingAverage.prototype.isSaturated = function () {
  40770. return this._sampleCount >= this._samples.length;
  40771. };
  40772. /**
  40773. * Resets the rolling average (equivalent to 0 samples taken so far)
  40774. */
  40775. RollingAverage.prototype.reset = function () {
  40776. this.average = 0;
  40777. this.variance = 0;
  40778. this._sampleCount = 0;
  40779. this._pos = 0;
  40780. this._m2 = 0;
  40781. };
  40782. /**
  40783. * Wraps a value around the sample range boundaries
  40784. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40785. * @return Wrapped position in sample range
  40786. */
  40787. RollingAverage.prototype._wrapPosition = function (i) {
  40788. var max = this._samples.length;
  40789. return ((i % max) + max) % max;
  40790. };
  40791. return RollingAverage;
  40792. }());
  40793. BABYLON.RollingAverage = RollingAverage;
  40794. })(BABYLON || (BABYLON = {}));
  40795. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40796. var BABYLON;
  40797. (function (BABYLON) {
  40798. /**
  40799. * "Static Class" containing the most commonly used helper while dealing with material for
  40800. * rendering purpose.
  40801. *
  40802. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40803. *
  40804. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40805. */
  40806. var MaterialHelper = /** @class */ (function () {
  40807. function MaterialHelper() {
  40808. }
  40809. /**
  40810. * Bind the current view position to an effect.
  40811. * @param effect The effect to be bound
  40812. * @param scene The scene the eyes position is used from
  40813. */
  40814. MaterialHelper.BindEyePosition = function (effect, scene) {
  40815. if (scene._forcedViewPosition) {
  40816. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40817. return;
  40818. }
  40819. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40820. };
  40821. /**
  40822. * Helps preparing the defines values about the UVs in used in the effect.
  40823. * UVs are shared as much as we can accross chanels in the shaders.
  40824. * @param texture The texture we are preparing the UVs for
  40825. * @param defines The defines to update
  40826. * @param key The chanel key "diffuse", "specular"... used in the shader
  40827. */
  40828. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40829. defines._needUVs = true;
  40830. defines[key] = true;
  40831. if (texture.getTextureMatrix().isIdentity(true)) {
  40832. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40833. if (texture.coordinatesIndex === 0) {
  40834. defines["MAINUV1"] = true;
  40835. }
  40836. else {
  40837. defines["MAINUV2"] = true;
  40838. }
  40839. }
  40840. else {
  40841. defines[key + "DIRECTUV"] = 0;
  40842. }
  40843. };
  40844. /**
  40845. * Binds a texture matrix value to its corrsponding uniform
  40846. * @param texture The texture to bind the matrix for
  40847. * @param uniformBuffer The uniform buffer receivin the data
  40848. * @param key The chanel key "diffuse", "specular"... used in the shader
  40849. */
  40850. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40851. var matrix = texture.getTextureMatrix();
  40852. if (!matrix.isIdentity(true)) {
  40853. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40854. }
  40855. };
  40856. /**
  40857. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40858. * @param mesh defines the current mesh
  40859. * @param scene defines the current scene
  40860. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40861. * @param pointsCloud defines if point cloud rendering has to be turned on
  40862. * @param fogEnabled defines if fog has to be turned on
  40863. * @param alphaTest defines if alpha testing has to be turned on
  40864. * @param defines defines the current list of defines
  40865. */
  40866. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40867. if (defines._areMiscDirty) {
  40868. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40869. defines["POINTSIZE"] = pointsCloud;
  40870. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40871. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40872. defines["ALPHATEST"] = alphaTest;
  40873. }
  40874. };
  40875. /**
  40876. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40877. * @param scene defines the current scene
  40878. * @param engine defines the current engine
  40879. * @param defines specifies the list of active defines
  40880. * @param useInstances defines if instances have to be turned on
  40881. * @param useClipPlane defines if clip plane have to be turned on
  40882. */
  40883. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40884. if (useClipPlane === void 0) { useClipPlane = null; }
  40885. var changed = false;
  40886. if (useClipPlane == null) {
  40887. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40888. }
  40889. if (defines["CLIPPLANE"] !== useClipPlane) {
  40890. defines["CLIPPLANE"] = useClipPlane;
  40891. changed = true;
  40892. }
  40893. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40894. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40895. changed = true;
  40896. }
  40897. if (defines["INSTANCES"] !== useInstances) {
  40898. defines["INSTANCES"] = useInstances;
  40899. changed = true;
  40900. }
  40901. if (changed) {
  40902. defines.markAsUnprocessed();
  40903. }
  40904. };
  40905. /**
  40906. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40907. * @param mesh The mesh containing the geometry data we will draw
  40908. * @param defines The defines to update
  40909. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40910. * @param useBones Precise whether bones should be used or not (override mesh info)
  40911. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40912. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40913. * @returns false if defines are considered not dirty and have not been checked
  40914. */
  40915. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40916. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40917. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40918. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40919. return false;
  40920. }
  40921. defines._normals = defines._needNormals;
  40922. defines._uvs = defines._needUVs;
  40923. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40924. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40925. defines["TANGENT"] = true;
  40926. }
  40927. if (defines._needUVs) {
  40928. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40929. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40930. }
  40931. else {
  40932. defines["UV1"] = false;
  40933. defines["UV2"] = false;
  40934. }
  40935. if (useVertexColor) {
  40936. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40937. defines["VERTEXCOLOR"] = hasVertexColors;
  40938. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40939. }
  40940. if (useBones) {
  40941. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40942. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40943. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40944. }
  40945. else {
  40946. defines["NUM_BONE_INFLUENCERS"] = 0;
  40947. defines["BonesPerMesh"] = 0;
  40948. }
  40949. }
  40950. if (useMorphTargets) {
  40951. var manager = mesh.morphTargetManager;
  40952. if (manager) {
  40953. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40954. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40955. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40956. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40957. }
  40958. else {
  40959. defines["MORPHTARGETS_TANGENT"] = false;
  40960. defines["MORPHTARGETS_NORMAL"] = false;
  40961. defines["MORPHTARGETS"] = false;
  40962. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40963. }
  40964. }
  40965. return true;
  40966. };
  40967. /**
  40968. * Prepares the defines related to the light information passed in parameter
  40969. * @param scene The scene we are intending to draw
  40970. * @param mesh The mesh the effect is compiling for
  40971. * @param defines The defines to update
  40972. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40973. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40974. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40975. * @returns true if normals will be required for the rest of the effect
  40976. */
  40977. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40978. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40979. if (disableLighting === void 0) { disableLighting = false; }
  40980. if (!defines._areLightsDirty) {
  40981. return defines._needNormals;
  40982. }
  40983. var lightIndex = 0;
  40984. var needNormals = false;
  40985. var needRebuild = false;
  40986. var lightmapMode = false;
  40987. var shadowEnabled = false;
  40988. var specularEnabled = false;
  40989. if (scene.lightsEnabled && !disableLighting) {
  40990. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40991. var light = _a[_i];
  40992. needNormals = true;
  40993. if (defines["LIGHT" + lightIndex] === undefined) {
  40994. needRebuild = true;
  40995. }
  40996. defines["LIGHT" + lightIndex] = true;
  40997. defines["SPOTLIGHT" + lightIndex] = false;
  40998. defines["HEMILIGHT" + lightIndex] = false;
  40999. defines["POINTLIGHT" + lightIndex] = false;
  41000. defines["DIRLIGHT" + lightIndex] = false;
  41001. light.prepareLightSpecificDefines(defines, lightIndex);
  41002. // FallOff.
  41003. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41004. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41005. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41006. switch (light.falloffType) {
  41007. case BABYLON.Light.FALLOFF_GLTF:
  41008. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41009. break;
  41010. case BABYLON.Light.FALLOFF_PHYSICAL:
  41011. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41012. break;
  41013. case BABYLON.Light.FALLOFF_STANDARD:
  41014. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41015. break;
  41016. }
  41017. // Specular
  41018. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41019. specularEnabled = true;
  41020. }
  41021. // Shadows
  41022. defines["SHADOW" + lightIndex] = false;
  41023. defines["SHADOWPCF" + lightIndex] = false;
  41024. defines["SHADOWPCSS" + lightIndex] = false;
  41025. defines["SHADOWPOISSON" + lightIndex] = false;
  41026. defines["SHADOWESM" + lightIndex] = false;
  41027. defines["SHADOWCUBE" + lightIndex] = false;
  41028. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41029. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41030. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41031. var shadowGenerator = light.getShadowGenerator();
  41032. if (shadowGenerator) {
  41033. var shadowMap = shadowGenerator.getShadowMap();
  41034. if (shadowMap) {
  41035. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41036. shadowEnabled = true;
  41037. shadowGenerator.prepareDefines(defines, lightIndex);
  41038. }
  41039. }
  41040. }
  41041. }
  41042. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41043. lightmapMode = true;
  41044. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41045. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41046. }
  41047. else {
  41048. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41049. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41050. }
  41051. lightIndex++;
  41052. if (lightIndex === maxSimultaneousLights)
  41053. break;
  41054. }
  41055. }
  41056. defines["SPECULARTERM"] = specularEnabled;
  41057. defines["SHADOWS"] = shadowEnabled;
  41058. // Resetting all other lights if any
  41059. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41060. if (defines["LIGHT" + index] !== undefined) {
  41061. defines["LIGHT" + index] = false;
  41062. defines["HEMILIGHT" + lightIndex] = false;
  41063. defines["POINTLIGHT" + lightIndex] = false;
  41064. defines["DIRLIGHT" + lightIndex] = false;
  41065. defines["SPOTLIGHT" + lightIndex] = false;
  41066. defines["SHADOW" + lightIndex] = false;
  41067. }
  41068. }
  41069. var caps = scene.getEngine().getCaps();
  41070. if (defines["SHADOWFLOAT"] === undefined) {
  41071. needRebuild = true;
  41072. }
  41073. defines["SHADOWFLOAT"] = shadowEnabled &&
  41074. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41075. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41076. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41077. if (needRebuild) {
  41078. defines.rebuild();
  41079. }
  41080. return needNormals;
  41081. };
  41082. /**
  41083. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41084. * that won t be acctive due to defines being turned off.
  41085. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41086. * @param samplersList The samplers list
  41087. * @param defines The defines helping in the list generation
  41088. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41089. */
  41090. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41091. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41092. var uniformsList;
  41093. var uniformBuffersList = null;
  41094. if (uniformsListOrOptions.uniformsNames) {
  41095. var options = uniformsListOrOptions;
  41096. uniformsList = options.uniformsNames;
  41097. uniformBuffersList = options.uniformBuffersNames;
  41098. samplersList = options.samplers;
  41099. defines = options.defines;
  41100. maxSimultaneousLights = options.maxSimultaneousLights;
  41101. }
  41102. else {
  41103. uniformsList = uniformsListOrOptions;
  41104. if (!samplersList) {
  41105. samplersList = [];
  41106. }
  41107. }
  41108. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41109. if (!defines["LIGHT" + lightIndex]) {
  41110. break;
  41111. }
  41112. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41113. if (uniformBuffersList) {
  41114. uniformBuffersList.push("Light" + lightIndex);
  41115. }
  41116. samplersList.push("shadowSampler" + lightIndex);
  41117. samplersList.push("depthSampler" + lightIndex);
  41118. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41119. samplersList.push("projectionLightSampler" + lightIndex);
  41120. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41121. }
  41122. }
  41123. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41124. uniformsList.push("morphTargetInfluences");
  41125. }
  41126. };
  41127. /**
  41128. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41129. * @param defines The defines to update while falling back
  41130. * @param fallbacks The authorized effect fallbacks
  41131. * @param maxSimultaneousLights The maximum number of lights allowed
  41132. * @param rank the current rank of the Effect
  41133. * @returns The newly affected rank
  41134. */
  41135. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41136. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41137. if (rank === void 0) { rank = 0; }
  41138. var lightFallbackRank = 0;
  41139. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41140. if (!defines["LIGHT" + lightIndex]) {
  41141. break;
  41142. }
  41143. if (lightIndex > 0) {
  41144. lightFallbackRank = rank + lightIndex;
  41145. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41146. }
  41147. if (!defines["SHADOWS"]) {
  41148. if (defines["SHADOW" + lightIndex]) {
  41149. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41150. }
  41151. if (defines["SHADOWPCF" + lightIndex]) {
  41152. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41153. }
  41154. if (defines["SHADOWPCSS" + lightIndex]) {
  41155. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41156. }
  41157. if (defines["SHADOWPOISSON" + lightIndex]) {
  41158. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41159. }
  41160. if (defines["SHADOWESM" + lightIndex]) {
  41161. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41162. }
  41163. }
  41164. }
  41165. return lightFallbackRank++;
  41166. };
  41167. /**
  41168. * Prepares the list of attributes required for morph targets according to the effect defines.
  41169. * @param attribs The current list of supported attribs
  41170. * @param mesh The mesh to prepare the morph targets attributes for
  41171. * @param defines The current Defines of the effect
  41172. */
  41173. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41174. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41175. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41176. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41177. var manager = mesh.morphTargetManager;
  41178. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41179. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41180. for (var index = 0; index < influencers; index++) {
  41181. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41182. if (normal) {
  41183. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41184. }
  41185. if (tangent) {
  41186. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41187. }
  41188. if (attribs.length > maxAttributesCount) {
  41189. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41190. }
  41191. }
  41192. }
  41193. };
  41194. /**
  41195. * Prepares the list of attributes required for bones according to the effect defines.
  41196. * @param attribs The current list of supported attribs
  41197. * @param mesh The mesh to prepare the bones attributes for
  41198. * @param defines The current Defines of the effect
  41199. * @param fallbacks The current efffect fallback strategy
  41200. */
  41201. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41202. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41203. fallbacks.addCPUSkinningFallback(0, mesh);
  41204. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41205. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41206. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41207. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41208. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41209. }
  41210. }
  41211. };
  41212. /**
  41213. * Prepares the list of attributes required for instances according to the effect defines.
  41214. * @param attribs The current list of supported attribs
  41215. * @param defines The current Defines of the effect
  41216. */
  41217. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41218. if (defines["INSTANCES"]) {
  41219. attribs.push("world0");
  41220. attribs.push("world1");
  41221. attribs.push("world2");
  41222. attribs.push("world3");
  41223. }
  41224. };
  41225. /**
  41226. * Binds the light shadow information to the effect for the given mesh.
  41227. * @param light The light containing the generator
  41228. * @param scene The scene the lights belongs to
  41229. * @param mesh The mesh we are binding the information to render
  41230. * @param lightIndex The light index in the effect used to render the mesh
  41231. * @param effect The effect we are binding the data to
  41232. */
  41233. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41234. if (light.shadowEnabled && mesh.receiveShadows) {
  41235. var shadowGenerator = light.getShadowGenerator();
  41236. if (shadowGenerator) {
  41237. shadowGenerator.bindShadowLight(lightIndex, effect);
  41238. }
  41239. }
  41240. };
  41241. /**
  41242. * Binds the light information to the effect.
  41243. * @param light The light containing the generator
  41244. * @param effect The effect we are binding the data to
  41245. * @param lightIndex The light index in the effect used to render
  41246. */
  41247. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41248. light.transferToEffect(effect, lightIndex + "");
  41249. };
  41250. /**
  41251. * Binds the lights information from the scene to the effect for the given mesh.
  41252. * @param scene The scene the lights belongs to
  41253. * @param mesh The mesh we are binding the information to render
  41254. * @param effect The effect we are binding the data to
  41255. * @param defines The generated defines for the effect
  41256. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41257. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41258. */
  41259. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41260. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41261. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41262. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41263. for (var i = 0; i < len; i++) {
  41264. var light = mesh._lightSources[i];
  41265. var iAsString = i.toString();
  41266. var scaledIntensity = light.getScaledIntensity();
  41267. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41268. MaterialHelper.BindLightProperties(light, effect, i);
  41269. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41270. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41271. if (defines["SPECULARTERM"]) {
  41272. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41273. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41274. }
  41275. // Shadows
  41276. if (scene.shadowsEnabled) {
  41277. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41278. }
  41279. light._uniformBuffer.update();
  41280. }
  41281. };
  41282. /**
  41283. * Binds the fog information from the scene to the effect for the given mesh.
  41284. * @param scene The scene the lights belongs to
  41285. * @param mesh The mesh we are binding the information to render
  41286. * @param effect The effect we are binding the data to
  41287. */
  41288. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41289. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41290. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41291. effect.setColor3("vFogColor", scene.fogColor);
  41292. }
  41293. };
  41294. /**
  41295. * Binds the bones information from the mesh to the effect.
  41296. * @param mesh The mesh we are binding the information to render
  41297. * @param effect The effect we are binding the data to
  41298. */
  41299. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41300. if (!effect || !mesh) {
  41301. return;
  41302. }
  41303. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41304. mesh.computeBonesUsingShaders = false;
  41305. }
  41306. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41307. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41308. if (matrices) {
  41309. effect.setMatrices("mBones", matrices);
  41310. }
  41311. }
  41312. };
  41313. /**
  41314. * Binds the morph targets information from the mesh to the effect.
  41315. * @param abstractMesh The mesh we are binding the information to render
  41316. * @param effect The effect we are binding the data to
  41317. */
  41318. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41319. var manager = abstractMesh.morphTargetManager;
  41320. if (!abstractMesh || !manager) {
  41321. return;
  41322. }
  41323. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41324. };
  41325. /**
  41326. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41327. * @param defines The generated defines used in the effect
  41328. * @param effect The effect we are binding the data to
  41329. * @param scene The scene we are willing to render with logarithmic scale for
  41330. */
  41331. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41332. if (defines["LOGARITHMICDEPTH"]) {
  41333. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41334. }
  41335. };
  41336. /**
  41337. * Binds the clip plane information from the scene to the effect.
  41338. * @param scene The scene the clip plane information are extracted from
  41339. * @param effect The effect we are binding the data to
  41340. */
  41341. MaterialHelper.BindClipPlane = function (effect, scene) {
  41342. if (scene.clipPlane) {
  41343. var clipPlane = scene.clipPlane;
  41344. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41345. }
  41346. };
  41347. return MaterialHelper;
  41348. }());
  41349. BABYLON.MaterialHelper = MaterialHelper;
  41350. })(BABYLON || (BABYLON = {}));
  41351. //# sourceMappingURL=babylon.materialHelper.js.map
  41352. var BABYLON;
  41353. (function (BABYLON) {
  41354. var PushMaterial = /** @class */ (function (_super) {
  41355. __extends(PushMaterial, _super);
  41356. function PushMaterial(name, scene) {
  41357. var _this = _super.call(this, name, scene) || this;
  41358. _this._normalMatrix = new BABYLON.Matrix();
  41359. _this.storeEffectOnSubMeshes = true;
  41360. return _this;
  41361. }
  41362. PushMaterial.prototype.getEffect = function () {
  41363. return this._activeEffect;
  41364. };
  41365. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41366. if (!mesh) {
  41367. return false;
  41368. }
  41369. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41370. return true;
  41371. }
  41372. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41373. };
  41374. /**
  41375. * Binds the given world matrix to the active effect
  41376. *
  41377. * @param world the matrix to bind
  41378. */
  41379. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41380. this._activeEffect.setMatrix("world", world);
  41381. };
  41382. /**
  41383. * Binds the given normal matrix to the active effect
  41384. *
  41385. * @param normalMatrix the matrix to bind
  41386. */
  41387. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41388. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41389. };
  41390. PushMaterial.prototype.bind = function (world, mesh) {
  41391. if (!mesh) {
  41392. return;
  41393. }
  41394. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41395. };
  41396. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41397. if (effect === void 0) { effect = null; }
  41398. _super.prototype._afterBind.call(this, mesh);
  41399. this.getScene()._cachedEffect = effect;
  41400. };
  41401. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41402. if (visibility === void 0) { visibility = 1; }
  41403. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41404. };
  41405. return PushMaterial;
  41406. }(BABYLON.Material));
  41407. BABYLON.PushMaterial = PushMaterial;
  41408. })(BABYLON || (BABYLON = {}));
  41409. //# sourceMappingURL=babylon.pushMaterial.js.map
  41410. var BABYLON;
  41411. (function (BABYLON) {
  41412. /** @hidden */
  41413. var StandardMaterialDefines = /** @class */ (function (_super) {
  41414. __extends(StandardMaterialDefines, _super);
  41415. function StandardMaterialDefines() {
  41416. var _this = _super.call(this) || this;
  41417. _this.MAINUV1 = false;
  41418. _this.MAINUV2 = false;
  41419. _this.DIFFUSE = false;
  41420. _this.DIFFUSEDIRECTUV = 0;
  41421. _this.AMBIENT = false;
  41422. _this.AMBIENTDIRECTUV = 0;
  41423. _this.OPACITY = false;
  41424. _this.OPACITYDIRECTUV = 0;
  41425. _this.OPACITYRGB = false;
  41426. _this.REFLECTION = false;
  41427. _this.EMISSIVE = false;
  41428. _this.EMISSIVEDIRECTUV = 0;
  41429. _this.SPECULAR = false;
  41430. _this.SPECULARDIRECTUV = 0;
  41431. _this.BUMP = false;
  41432. _this.BUMPDIRECTUV = 0;
  41433. _this.PARALLAX = false;
  41434. _this.PARALLAXOCCLUSION = false;
  41435. _this.SPECULAROVERALPHA = false;
  41436. _this.CLIPPLANE = false;
  41437. _this.ALPHATEST = false;
  41438. _this.DEPTHPREPASS = false;
  41439. _this.ALPHAFROMDIFFUSE = false;
  41440. _this.POINTSIZE = false;
  41441. _this.FOG = false;
  41442. _this.SPECULARTERM = false;
  41443. _this.DIFFUSEFRESNEL = false;
  41444. _this.OPACITYFRESNEL = false;
  41445. _this.REFLECTIONFRESNEL = false;
  41446. _this.REFRACTIONFRESNEL = false;
  41447. _this.EMISSIVEFRESNEL = false;
  41448. _this.FRESNEL = false;
  41449. _this.NORMAL = false;
  41450. _this.UV1 = false;
  41451. _this.UV2 = false;
  41452. _this.VERTEXCOLOR = false;
  41453. _this.VERTEXALPHA = false;
  41454. _this.NUM_BONE_INFLUENCERS = 0;
  41455. _this.BonesPerMesh = 0;
  41456. _this.INSTANCES = false;
  41457. _this.GLOSSINESS = false;
  41458. _this.ROUGHNESS = false;
  41459. _this.EMISSIVEASILLUMINATION = false;
  41460. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41461. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41462. _this.LIGHTMAP = false;
  41463. _this.LIGHTMAPDIRECTUV = 0;
  41464. _this.OBJECTSPACE_NORMALMAP = false;
  41465. _this.USELIGHTMAPASSHADOWMAP = false;
  41466. _this.REFLECTIONMAP_3D = false;
  41467. _this.REFLECTIONMAP_SPHERICAL = false;
  41468. _this.REFLECTIONMAP_PLANAR = false;
  41469. _this.REFLECTIONMAP_CUBIC = false;
  41470. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41471. _this.REFLECTIONMAP_PROJECTION = false;
  41472. _this.REFLECTIONMAP_SKYBOX = false;
  41473. _this.REFLECTIONMAP_EXPLICIT = false;
  41474. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41475. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41476. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41477. _this.INVERTCUBICMAP = false;
  41478. _this.LOGARITHMICDEPTH = false;
  41479. _this.REFRACTION = false;
  41480. _this.REFRACTIONMAP_3D = false;
  41481. _this.REFLECTIONOVERALPHA = false;
  41482. _this.TWOSIDEDLIGHTING = false;
  41483. _this.SHADOWFLOAT = false;
  41484. _this.MORPHTARGETS = false;
  41485. _this.MORPHTARGETS_NORMAL = false;
  41486. _this.MORPHTARGETS_TANGENT = false;
  41487. _this.NUM_MORPH_INFLUENCERS = 0;
  41488. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41489. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41490. _this.IMAGEPROCESSING = false;
  41491. _this.VIGNETTE = false;
  41492. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41493. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41494. _this.TONEMAPPING = false;
  41495. _this.CONTRAST = false;
  41496. _this.COLORCURVES = false;
  41497. _this.COLORGRADING = false;
  41498. _this.COLORGRADING3D = false;
  41499. _this.SAMPLER3DGREENDEPTH = false;
  41500. _this.SAMPLER3DBGRMAP = false;
  41501. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41502. /**
  41503. * If the reflection texture on this material is in linear color space
  41504. * @hidden
  41505. */
  41506. _this.IS_REFLECTION_LINEAR = false;
  41507. /**
  41508. * If the refraction texture on this material is in linear color space
  41509. * @hidden
  41510. */
  41511. _this.IS_REFRACTION_LINEAR = false;
  41512. _this.EXPOSURE = false;
  41513. _this.rebuild();
  41514. return _this;
  41515. }
  41516. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41517. var modes = [
  41518. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41519. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41520. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41521. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41522. ];
  41523. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41524. var mode = modes_1[_i];
  41525. this[mode] = (mode === modeToEnable);
  41526. }
  41527. };
  41528. return StandardMaterialDefines;
  41529. }(BABYLON.MaterialDefines));
  41530. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41531. var StandardMaterial = /** @class */ (function (_super) {
  41532. __extends(StandardMaterial, _super);
  41533. function StandardMaterial(name, scene) {
  41534. var _this = _super.call(this, name, scene) || this;
  41535. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41536. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41537. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41538. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41539. _this.specularPower = 64;
  41540. _this._useAlphaFromDiffuseTexture = false;
  41541. _this._useEmissiveAsIllumination = false;
  41542. _this._linkEmissiveWithDiffuse = false;
  41543. _this._useSpecularOverAlpha = false;
  41544. _this._useReflectionOverAlpha = false;
  41545. _this._disableLighting = false;
  41546. _this._useObjectSpaceNormalMap = false;
  41547. _this._useParallax = false;
  41548. _this._useParallaxOcclusion = false;
  41549. _this.parallaxScaleBias = 0.05;
  41550. _this._roughness = 0;
  41551. _this.indexOfRefraction = 0.98;
  41552. _this.invertRefractionY = true;
  41553. /**
  41554. * Defines the alpha limits in alpha test mode
  41555. */
  41556. _this.alphaCutOff = 0.4;
  41557. _this._useLightmapAsShadowmap = false;
  41558. _this._useReflectionFresnelFromSpecular = false;
  41559. _this._useGlossinessFromSpecularMapAlpha = false;
  41560. _this._maxSimultaneousLights = 4;
  41561. /**
  41562. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41563. */
  41564. _this._invertNormalMapX = false;
  41565. /**
  41566. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41567. */
  41568. _this._invertNormalMapY = false;
  41569. /**
  41570. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41571. */
  41572. _this._twoSidedLighting = false;
  41573. _this._renderTargets = new BABYLON.SmartArray(16);
  41574. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41575. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41576. // Setup the default processing configuration to the scene.
  41577. _this._attachImageProcessingConfiguration(null);
  41578. _this.getRenderTargetTextures = function () {
  41579. _this._renderTargets.reset();
  41580. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41581. _this._renderTargets.push(_this._reflectionTexture);
  41582. }
  41583. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41584. _this._renderTargets.push(_this._refractionTexture);
  41585. }
  41586. return _this._renderTargets;
  41587. };
  41588. return _this;
  41589. }
  41590. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41591. /**
  41592. * Gets the image processing configuration used either in this material.
  41593. */
  41594. get: function () {
  41595. return this._imageProcessingConfiguration;
  41596. },
  41597. /**
  41598. * Sets the Default image processing configuration used either in the this material.
  41599. *
  41600. * If sets to null, the scene one is in use.
  41601. */
  41602. set: function (value) {
  41603. this._attachImageProcessingConfiguration(value);
  41604. // Ensure the effect will be rebuilt.
  41605. this._markAllSubMeshesAsTexturesDirty();
  41606. },
  41607. enumerable: true,
  41608. configurable: true
  41609. });
  41610. /**
  41611. * Attaches a new image processing configuration to the Standard Material.
  41612. * @param configuration
  41613. */
  41614. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41615. var _this = this;
  41616. if (configuration === this._imageProcessingConfiguration) {
  41617. return;
  41618. }
  41619. // Detaches observer.
  41620. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41621. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41622. }
  41623. // Pick the scene configuration if needed.
  41624. if (!configuration) {
  41625. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41626. }
  41627. else {
  41628. this._imageProcessingConfiguration = configuration;
  41629. }
  41630. // Attaches observer.
  41631. if (this._imageProcessingConfiguration) {
  41632. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41633. _this._markAllSubMeshesAsImageProcessingDirty();
  41634. });
  41635. }
  41636. };
  41637. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41638. /**
  41639. * Gets wether the color curves effect is enabled.
  41640. */
  41641. get: function () {
  41642. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41643. },
  41644. /**
  41645. * Sets wether the color curves effect is enabled.
  41646. */
  41647. set: function (value) {
  41648. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41649. },
  41650. enumerable: true,
  41651. configurable: true
  41652. });
  41653. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41654. /**
  41655. * Gets wether the color grading effect is enabled.
  41656. */
  41657. get: function () {
  41658. return this.imageProcessingConfiguration.colorGradingEnabled;
  41659. },
  41660. /**
  41661. * Gets wether the color grading effect is enabled.
  41662. */
  41663. set: function (value) {
  41664. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41665. },
  41666. enumerable: true,
  41667. configurable: true
  41668. });
  41669. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41670. /**
  41671. * Gets wether tonemapping is enabled or not.
  41672. */
  41673. get: function () {
  41674. return this._imageProcessingConfiguration.toneMappingEnabled;
  41675. },
  41676. /**
  41677. * Sets wether tonemapping is enabled or not
  41678. */
  41679. set: function (value) {
  41680. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41681. },
  41682. enumerable: true,
  41683. configurable: true
  41684. });
  41685. ;
  41686. ;
  41687. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41688. /**
  41689. * The camera exposure used on this material.
  41690. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41691. * This corresponds to a photographic exposure.
  41692. */
  41693. get: function () {
  41694. return this._imageProcessingConfiguration.exposure;
  41695. },
  41696. /**
  41697. * The camera exposure used on this material.
  41698. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41699. * This corresponds to a photographic exposure.
  41700. */
  41701. set: function (value) {
  41702. this._imageProcessingConfiguration.exposure = value;
  41703. },
  41704. enumerable: true,
  41705. configurable: true
  41706. });
  41707. ;
  41708. ;
  41709. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41710. /**
  41711. * Gets The camera contrast used on this material.
  41712. */
  41713. get: function () {
  41714. return this._imageProcessingConfiguration.contrast;
  41715. },
  41716. /**
  41717. * Sets The camera contrast used on this material.
  41718. */
  41719. set: function (value) {
  41720. this._imageProcessingConfiguration.contrast = value;
  41721. },
  41722. enumerable: true,
  41723. configurable: true
  41724. });
  41725. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41726. /**
  41727. * Gets the Color Grading 2D Lookup Texture.
  41728. */
  41729. get: function () {
  41730. return this._imageProcessingConfiguration.colorGradingTexture;
  41731. },
  41732. /**
  41733. * Sets the Color Grading 2D Lookup Texture.
  41734. */
  41735. set: function (value) {
  41736. this._imageProcessingConfiguration.colorGradingTexture = value;
  41737. },
  41738. enumerable: true,
  41739. configurable: true
  41740. });
  41741. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41742. /**
  41743. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41744. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41745. * 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;
  41746. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41747. */
  41748. get: function () {
  41749. return this._imageProcessingConfiguration.colorCurves;
  41750. },
  41751. /**
  41752. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41753. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41754. * 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;
  41755. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41756. */
  41757. set: function (value) {
  41758. this._imageProcessingConfiguration.colorCurves = value;
  41759. },
  41760. enumerable: true,
  41761. configurable: true
  41762. });
  41763. StandardMaterial.prototype.getClassName = function () {
  41764. return "StandardMaterial";
  41765. };
  41766. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41767. get: function () {
  41768. return this._useLogarithmicDepth;
  41769. },
  41770. set: function (value) {
  41771. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41772. this._markAllSubMeshesAsMiscDirty();
  41773. },
  41774. enumerable: true,
  41775. configurable: true
  41776. });
  41777. StandardMaterial.prototype.needAlphaBlending = function () {
  41778. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41779. };
  41780. StandardMaterial.prototype.needAlphaTesting = function () {
  41781. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41782. };
  41783. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41784. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41785. };
  41786. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41787. return this._diffuseTexture;
  41788. };
  41789. /**
  41790. * Child classes can use it to update shaders
  41791. */
  41792. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41793. if (useInstances === void 0) { useInstances = false; }
  41794. if (subMesh.effect && this.isFrozen) {
  41795. if (this._wasPreviouslyReady) {
  41796. return true;
  41797. }
  41798. }
  41799. if (!subMesh._materialDefines) {
  41800. subMesh._materialDefines = new StandardMaterialDefines();
  41801. }
  41802. var scene = this.getScene();
  41803. var defines = subMesh._materialDefines;
  41804. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41805. if (defines._renderId === scene.getRenderId()) {
  41806. return true;
  41807. }
  41808. }
  41809. var engine = scene.getEngine();
  41810. // Lights
  41811. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41812. // Textures
  41813. if (defines._areTexturesDirty) {
  41814. defines._needUVs = false;
  41815. defines.MAINUV1 = false;
  41816. defines.MAINUV2 = false;
  41817. if (scene.texturesEnabled) {
  41818. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41819. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41820. return false;
  41821. }
  41822. else {
  41823. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41824. }
  41825. }
  41826. else {
  41827. defines.DIFFUSE = false;
  41828. }
  41829. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41830. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41831. return false;
  41832. }
  41833. else {
  41834. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41835. }
  41836. }
  41837. else {
  41838. defines.AMBIENT = false;
  41839. }
  41840. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41841. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41842. return false;
  41843. }
  41844. else {
  41845. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41846. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41847. }
  41848. }
  41849. else {
  41850. defines.OPACITY = false;
  41851. }
  41852. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41853. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41854. return false;
  41855. }
  41856. else {
  41857. defines._needNormals = true;
  41858. defines.REFLECTION = true;
  41859. defines.ROUGHNESS = (this._roughness > 0);
  41860. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41861. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41862. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41863. switch (this._reflectionTexture.coordinatesMode) {
  41864. case BABYLON.Texture.EXPLICIT_MODE:
  41865. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41866. break;
  41867. case BABYLON.Texture.PLANAR_MODE:
  41868. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41869. break;
  41870. case BABYLON.Texture.PROJECTION_MODE:
  41871. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41872. break;
  41873. case BABYLON.Texture.SKYBOX_MODE:
  41874. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41875. break;
  41876. case BABYLON.Texture.SPHERICAL_MODE:
  41877. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41878. break;
  41879. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41880. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41881. break;
  41882. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41883. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41884. break;
  41885. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41886. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41887. break;
  41888. case BABYLON.Texture.CUBIC_MODE:
  41889. case BABYLON.Texture.INVCUBIC_MODE:
  41890. default:
  41891. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41892. break;
  41893. }
  41894. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41895. }
  41896. }
  41897. else {
  41898. defines.REFLECTION = false;
  41899. }
  41900. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41901. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41902. return false;
  41903. }
  41904. else {
  41905. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41906. }
  41907. }
  41908. else {
  41909. defines.EMISSIVE = false;
  41910. }
  41911. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41912. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41913. return false;
  41914. }
  41915. else {
  41916. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41917. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41918. }
  41919. }
  41920. else {
  41921. defines.LIGHTMAP = false;
  41922. }
  41923. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41924. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41925. return false;
  41926. }
  41927. else {
  41928. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41929. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41930. }
  41931. }
  41932. else {
  41933. defines.SPECULAR = false;
  41934. }
  41935. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41936. // Bump texure can not be not blocking.
  41937. if (!this._bumpTexture.isReady()) {
  41938. return false;
  41939. }
  41940. else {
  41941. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41942. defines.PARALLAX = this._useParallax;
  41943. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41944. }
  41945. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41946. }
  41947. else {
  41948. defines.BUMP = false;
  41949. }
  41950. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41951. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41952. return false;
  41953. }
  41954. else {
  41955. defines._needUVs = true;
  41956. defines.REFRACTION = true;
  41957. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41958. }
  41959. }
  41960. else {
  41961. defines.REFRACTION = false;
  41962. }
  41963. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41964. }
  41965. else {
  41966. defines.DIFFUSE = false;
  41967. defines.AMBIENT = false;
  41968. defines.OPACITY = false;
  41969. defines.REFLECTION = false;
  41970. defines.EMISSIVE = false;
  41971. defines.LIGHTMAP = false;
  41972. defines.BUMP = false;
  41973. defines.REFRACTION = false;
  41974. }
  41975. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41976. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41977. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41978. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41979. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41980. }
  41981. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41982. if (!this._imageProcessingConfiguration.isReady()) {
  41983. return false;
  41984. }
  41985. this._imageProcessingConfiguration.prepareDefines(defines);
  41986. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41987. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41988. }
  41989. if (defines._areFresnelDirty) {
  41990. if (StandardMaterial.FresnelEnabled) {
  41991. // Fresnel
  41992. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41993. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41994. this._reflectionFresnelParameters) {
  41995. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41996. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41997. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41998. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41999. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42000. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42001. defines._needNormals = true;
  42002. defines.FRESNEL = true;
  42003. }
  42004. }
  42005. else {
  42006. defines.FRESNEL = false;
  42007. }
  42008. }
  42009. // Misc.
  42010. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42011. // Attribs
  42012. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42013. // Values that need to be evaluated on every frame
  42014. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42015. // Get correct effect
  42016. if (defines.isDirty) {
  42017. defines.markAsProcessed();
  42018. scene.resetCachedMaterial();
  42019. // Fallbacks
  42020. var fallbacks = new BABYLON.EffectFallbacks();
  42021. if (defines.REFLECTION) {
  42022. fallbacks.addFallback(0, "REFLECTION");
  42023. }
  42024. if (defines.SPECULAR) {
  42025. fallbacks.addFallback(0, "SPECULAR");
  42026. }
  42027. if (defines.BUMP) {
  42028. fallbacks.addFallback(0, "BUMP");
  42029. }
  42030. if (defines.PARALLAX) {
  42031. fallbacks.addFallback(1, "PARALLAX");
  42032. }
  42033. if (defines.PARALLAXOCCLUSION) {
  42034. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42035. }
  42036. if (defines.SPECULAROVERALPHA) {
  42037. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42038. }
  42039. if (defines.FOG) {
  42040. fallbacks.addFallback(1, "FOG");
  42041. }
  42042. if (defines.POINTSIZE) {
  42043. fallbacks.addFallback(0, "POINTSIZE");
  42044. }
  42045. if (defines.LOGARITHMICDEPTH) {
  42046. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42047. }
  42048. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42049. if (defines.SPECULARTERM) {
  42050. fallbacks.addFallback(0, "SPECULARTERM");
  42051. }
  42052. if (defines.DIFFUSEFRESNEL) {
  42053. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42054. }
  42055. if (defines.OPACITYFRESNEL) {
  42056. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42057. }
  42058. if (defines.REFLECTIONFRESNEL) {
  42059. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42060. }
  42061. if (defines.EMISSIVEFRESNEL) {
  42062. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42063. }
  42064. if (defines.FRESNEL) {
  42065. fallbacks.addFallback(4, "FRESNEL");
  42066. }
  42067. //Attributes
  42068. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42069. if (defines.NORMAL) {
  42070. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42071. }
  42072. if (defines.UV1) {
  42073. attribs.push(BABYLON.VertexBuffer.UVKind);
  42074. }
  42075. if (defines.UV2) {
  42076. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42077. }
  42078. if (defines.VERTEXCOLOR) {
  42079. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42080. }
  42081. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42082. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42083. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42084. var shaderName = "default";
  42085. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42086. "vFogInfos", "vFogColor", "pointSize",
  42087. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42088. "mBones",
  42089. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42090. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42091. "vReflectionPosition", "vReflectionSize",
  42092. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42093. ];
  42094. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42095. var uniformBuffers = ["Material", "Scene"];
  42096. if (BABYLON.ImageProcessingConfiguration) {
  42097. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42098. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42099. }
  42100. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42101. uniformsNames: uniforms,
  42102. uniformBuffersNames: uniformBuffers,
  42103. samplers: samplers,
  42104. defines: defines,
  42105. maxSimultaneousLights: this._maxSimultaneousLights
  42106. });
  42107. if (this.customShaderNameResolve) {
  42108. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42109. }
  42110. var join = defines.toString();
  42111. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42112. attributes: attribs,
  42113. uniformsNames: uniforms,
  42114. uniformBuffersNames: uniformBuffers,
  42115. samplers: samplers,
  42116. defines: join,
  42117. fallbacks: fallbacks,
  42118. onCompiled: this.onCompiled,
  42119. onError: this.onError,
  42120. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42121. }, engine), defines);
  42122. this.buildUniformLayout();
  42123. }
  42124. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42125. return false;
  42126. }
  42127. defines._renderId = scene.getRenderId();
  42128. this._wasPreviouslyReady = true;
  42129. return true;
  42130. };
  42131. StandardMaterial.prototype.buildUniformLayout = function () {
  42132. // Order is important !
  42133. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42134. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42135. this._uniformBuffer.addUniform("opacityParts", 4);
  42136. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42137. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42138. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42139. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42140. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42141. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42142. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42143. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42144. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42145. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42146. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42147. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42148. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42149. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42150. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42151. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42152. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42153. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42154. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42155. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42156. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42157. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42158. this._uniformBuffer.addUniform("specularMatrix", 16);
  42159. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42160. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42161. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42162. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42163. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42164. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42165. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42166. this._uniformBuffer.addUniform("pointSize", 1);
  42167. this._uniformBuffer.create();
  42168. };
  42169. StandardMaterial.prototype.unbind = function () {
  42170. if (this._activeEffect) {
  42171. var needFlag = false;
  42172. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42173. this._activeEffect.setTexture("reflection2DSampler", null);
  42174. needFlag = true;
  42175. }
  42176. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42177. this._activeEffect.setTexture("refraction2DSampler", null);
  42178. needFlag = true;
  42179. }
  42180. if (needFlag) {
  42181. this._markAllSubMeshesAsTexturesDirty();
  42182. }
  42183. }
  42184. _super.prototype.unbind.call(this);
  42185. };
  42186. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42187. var scene = this.getScene();
  42188. var defines = subMesh._materialDefines;
  42189. if (!defines) {
  42190. return;
  42191. }
  42192. var effect = subMesh.effect;
  42193. if (!effect) {
  42194. return;
  42195. }
  42196. this._activeEffect = effect;
  42197. // Matrices
  42198. this.bindOnlyWorldMatrix(world);
  42199. // Normal Matrix
  42200. if (defines.OBJECTSPACE_NORMALMAP) {
  42201. world.toNormalMatrix(this._normalMatrix);
  42202. this.bindOnlyNormalMatrix(this._normalMatrix);
  42203. }
  42204. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42205. // Bones
  42206. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42207. if (mustRebind) {
  42208. this._uniformBuffer.bindToEffect(effect, "Material");
  42209. this.bindViewProjection(effect);
  42210. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42211. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42212. // Fresnel
  42213. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42214. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42215. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42216. }
  42217. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42218. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42219. }
  42220. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42221. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42222. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42223. }
  42224. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42225. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42226. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42227. }
  42228. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42229. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42230. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42231. }
  42232. }
  42233. // Textures
  42234. if (scene.texturesEnabled) {
  42235. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42236. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42237. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42238. if (this._diffuseTexture.hasAlpha) {
  42239. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42240. }
  42241. }
  42242. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42243. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42244. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42245. }
  42246. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42247. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42248. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42249. }
  42250. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42251. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42252. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42253. if (this._reflectionTexture.boundingBoxSize) {
  42254. var cubeTexture = this._reflectionTexture;
  42255. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42256. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42257. }
  42258. }
  42259. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42260. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42261. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42262. }
  42263. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42264. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42265. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42266. }
  42267. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42268. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42269. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42270. }
  42271. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42272. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42273. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42274. if (scene._mirroredCameraPosition) {
  42275. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42276. }
  42277. else {
  42278. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42279. }
  42280. }
  42281. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42282. var depth = 1.0;
  42283. if (!this._refractionTexture.isCube) {
  42284. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42285. if (this._refractionTexture.depth) {
  42286. depth = this._refractionTexture.depth;
  42287. }
  42288. }
  42289. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42290. }
  42291. }
  42292. // Point size
  42293. if (this.pointsCloud) {
  42294. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42295. }
  42296. if (defines.SPECULARTERM) {
  42297. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42298. }
  42299. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42300. // Diffuse
  42301. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42302. }
  42303. // Textures
  42304. if (scene.texturesEnabled) {
  42305. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42306. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42307. }
  42308. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42309. effect.setTexture("ambientSampler", this._ambientTexture);
  42310. }
  42311. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42312. effect.setTexture("opacitySampler", this._opacityTexture);
  42313. }
  42314. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42315. if (this._reflectionTexture.isCube) {
  42316. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42317. }
  42318. else {
  42319. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42320. }
  42321. }
  42322. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42323. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42324. }
  42325. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42326. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42327. }
  42328. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42329. effect.setTexture("specularSampler", this._specularTexture);
  42330. }
  42331. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42332. effect.setTexture("bumpSampler", this._bumpTexture);
  42333. }
  42334. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42335. var depth = 1.0;
  42336. if (this._refractionTexture.isCube) {
  42337. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42338. }
  42339. else {
  42340. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42341. }
  42342. }
  42343. }
  42344. // Clip plane
  42345. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42346. // Colors
  42347. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42348. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42349. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42350. }
  42351. if (mustRebind || !this.isFrozen) {
  42352. // Lights
  42353. if (scene.lightsEnabled && !this._disableLighting) {
  42354. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42355. }
  42356. // View
  42357. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42358. this.bindView(effect);
  42359. }
  42360. // Fog
  42361. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42362. // Morph targets
  42363. if (defines.NUM_MORPH_INFLUENCERS) {
  42364. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42365. }
  42366. // Log. depth
  42367. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42368. // image processing
  42369. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42370. this._imageProcessingConfiguration.bind(this._activeEffect);
  42371. }
  42372. }
  42373. this._uniformBuffer.update();
  42374. this._afterBind(mesh, this._activeEffect);
  42375. };
  42376. StandardMaterial.prototype.getAnimatables = function () {
  42377. var results = [];
  42378. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42379. results.push(this._diffuseTexture);
  42380. }
  42381. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42382. results.push(this._ambientTexture);
  42383. }
  42384. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42385. results.push(this._opacityTexture);
  42386. }
  42387. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42388. results.push(this._reflectionTexture);
  42389. }
  42390. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42391. results.push(this._emissiveTexture);
  42392. }
  42393. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42394. results.push(this._specularTexture);
  42395. }
  42396. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42397. results.push(this._bumpTexture);
  42398. }
  42399. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42400. results.push(this._lightmapTexture);
  42401. }
  42402. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42403. results.push(this._refractionTexture);
  42404. }
  42405. return results;
  42406. };
  42407. StandardMaterial.prototype.getActiveTextures = function () {
  42408. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42409. if (this._diffuseTexture) {
  42410. activeTextures.push(this._diffuseTexture);
  42411. }
  42412. if (this._ambientTexture) {
  42413. activeTextures.push(this._ambientTexture);
  42414. }
  42415. if (this._opacityTexture) {
  42416. activeTextures.push(this._opacityTexture);
  42417. }
  42418. if (this._reflectionTexture) {
  42419. activeTextures.push(this._reflectionTexture);
  42420. }
  42421. if (this._emissiveTexture) {
  42422. activeTextures.push(this._emissiveTexture);
  42423. }
  42424. if (this._specularTexture) {
  42425. activeTextures.push(this._specularTexture);
  42426. }
  42427. if (this._bumpTexture) {
  42428. activeTextures.push(this._bumpTexture);
  42429. }
  42430. if (this._lightmapTexture) {
  42431. activeTextures.push(this._lightmapTexture);
  42432. }
  42433. if (this._refractionTexture) {
  42434. activeTextures.push(this._refractionTexture);
  42435. }
  42436. return activeTextures;
  42437. };
  42438. StandardMaterial.prototype.hasTexture = function (texture) {
  42439. if (_super.prototype.hasTexture.call(this, texture)) {
  42440. return true;
  42441. }
  42442. if (this._diffuseTexture === texture) {
  42443. return true;
  42444. }
  42445. if (this._ambientTexture === texture) {
  42446. return true;
  42447. }
  42448. if (this._opacityTexture === texture) {
  42449. return true;
  42450. }
  42451. if (this._reflectionTexture === texture) {
  42452. return true;
  42453. }
  42454. if (this._emissiveTexture === texture) {
  42455. return true;
  42456. }
  42457. if (this._specularTexture === texture) {
  42458. return true;
  42459. }
  42460. if (this._bumpTexture === texture) {
  42461. return true;
  42462. }
  42463. if (this._lightmapTexture === texture) {
  42464. return true;
  42465. }
  42466. if (this._refractionTexture === texture) {
  42467. return true;
  42468. }
  42469. return false;
  42470. };
  42471. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42472. if (forceDisposeTextures) {
  42473. if (this._diffuseTexture) {
  42474. this._diffuseTexture.dispose();
  42475. }
  42476. if (this._ambientTexture) {
  42477. this._ambientTexture.dispose();
  42478. }
  42479. if (this._opacityTexture) {
  42480. this._opacityTexture.dispose();
  42481. }
  42482. if (this._reflectionTexture) {
  42483. this._reflectionTexture.dispose();
  42484. }
  42485. if (this._emissiveTexture) {
  42486. this._emissiveTexture.dispose();
  42487. }
  42488. if (this._specularTexture) {
  42489. this._specularTexture.dispose();
  42490. }
  42491. if (this._bumpTexture) {
  42492. this._bumpTexture.dispose();
  42493. }
  42494. if (this._lightmapTexture) {
  42495. this._lightmapTexture.dispose();
  42496. }
  42497. if (this._refractionTexture) {
  42498. this._refractionTexture.dispose();
  42499. }
  42500. }
  42501. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42502. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42503. }
  42504. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42505. };
  42506. StandardMaterial.prototype.clone = function (name) {
  42507. var _this = this;
  42508. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42509. result.name = name;
  42510. result.id = name;
  42511. return result;
  42512. };
  42513. StandardMaterial.prototype.serialize = function () {
  42514. return BABYLON.SerializationHelper.Serialize(this);
  42515. };
  42516. // Statics
  42517. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42518. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42519. };
  42520. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42521. get: function () {
  42522. return StandardMaterial._DiffuseTextureEnabled;
  42523. },
  42524. set: function (value) {
  42525. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42526. return;
  42527. }
  42528. StandardMaterial._DiffuseTextureEnabled = value;
  42529. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42530. },
  42531. enumerable: true,
  42532. configurable: true
  42533. });
  42534. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42535. get: function () {
  42536. return StandardMaterial._AmbientTextureEnabled;
  42537. },
  42538. set: function (value) {
  42539. if (StandardMaterial._AmbientTextureEnabled === value) {
  42540. return;
  42541. }
  42542. StandardMaterial._AmbientTextureEnabled = value;
  42543. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42544. },
  42545. enumerable: true,
  42546. configurable: true
  42547. });
  42548. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42549. get: function () {
  42550. return StandardMaterial._OpacityTextureEnabled;
  42551. },
  42552. set: function (value) {
  42553. if (StandardMaterial._OpacityTextureEnabled === value) {
  42554. return;
  42555. }
  42556. StandardMaterial._OpacityTextureEnabled = value;
  42557. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42558. },
  42559. enumerable: true,
  42560. configurable: true
  42561. });
  42562. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42563. get: function () {
  42564. return StandardMaterial._ReflectionTextureEnabled;
  42565. },
  42566. set: function (value) {
  42567. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42568. return;
  42569. }
  42570. StandardMaterial._ReflectionTextureEnabled = value;
  42571. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42572. },
  42573. enumerable: true,
  42574. configurable: true
  42575. });
  42576. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42577. get: function () {
  42578. return StandardMaterial._EmissiveTextureEnabled;
  42579. },
  42580. set: function (value) {
  42581. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42582. return;
  42583. }
  42584. StandardMaterial._EmissiveTextureEnabled = value;
  42585. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42586. },
  42587. enumerable: true,
  42588. configurable: true
  42589. });
  42590. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42591. get: function () {
  42592. return StandardMaterial._SpecularTextureEnabled;
  42593. },
  42594. set: function (value) {
  42595. if (StandardMaterial._SpecularTextureEnabled === value) {
  42596. return;
  42597. }
  42598. StandardMaterial._SpecularTextureEnabled = value;
  42599. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42600. },
  42601. enumerable: true,
  42602. configurable: true
  42603. });
  42604. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42605. get: function () {
  42606. return StandardMaterial._BumpTextureEnabled;
  42607. },
  42608. set: function (value) {
  42609. if (StandardMaterial._BumpTextureEnabled === value) {
  42610. return;
  42611. }
  42612. StandardMaterial._BumpTextureEnabled = value;
  42613. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42614. },
  42615. enumerable: true,
  42616. configurable: true
  42617. });
  42618. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42619. get: function () {
  42620. return StandardMaterial._LightmapTextureEnabled;
  42621. },
  42622. set: function (value) {
  42623. if (StandardMaterial._LightmapTextureEnabled === value) {
  42624. return;
  42625. }
  42626. StandardMaterial._LightmapTextureEnabled = value;
  42627. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42628. },
  42629. enumerable: true,
  42630. configurable: true
  42631. });
  42632. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42633. get: function () {
  42634. return StandardMaterial._RefractionTextureEnabled;
  42635. },
  42636. set: function (value) {
  42637. if (StandardMaterial._RefractionTextureEnabled === value) {
  42638. return;
  42639. }
  42640. StandardMaterial._RefractionTextureEnabled = value;
  42641. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42642. },
  42643. enumerable: true,
  42644. configurable: true
  42645. });
  42646. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42647. get: function () {
  42648. return StandardMaterial._ColorGradingTextureEnabled;
  42649. },
  42650. set: function (value) {
  42651. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42652. return;
  42653. }
  42654. StandardMaterial._ColorGradingTextureEnabled = value;
  42655. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42656. },
  42657. enumerable: true,
  42658. configurable: true
  42659. });
  42660. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42661. get: function () {
  42662. return StandardMaterial._FresnelEnabled;
  42663. },
  42664. set: function (value) {
  42665. if (StandardMaterial._FresnelEnabled === value) {
  42666. return;
  42667. }
  42668. StandardMaterial._FresnelEnabled = value;
  42669. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42670. },
  42671. enumerable: true,
  42672. configurable: true
  42673. });
  42674. // Flags used to enable or disable a type of texture for all Standard Materials
  42675. StandardMaterial._DiffuseTextureEnabled = true;
  42676. StandardMaterial._AmbientTextureEnabled = true;
  42677. StandardMaterial._OpacityTextureEnabled = true;
  42678. StandardMaterial._ReflectionTextureEnabled = true;
  42679. StandardMaterial._EmissiveTextureEnabled = true;
  42680. StandardMaterial._SpecularTextureEnabled = true;
  42681. StandardMaterial._BumpTextureEnabled = true;
  42682. StandardMaterial._LightmapTextureEnabled = true;
  42683. StandardMaterial._RefractionTextureEnabled = true;
  42684. StandardMaterial._ColorGradingTextureEnabled = true;
  42685. StandardMaterial._FresnelEnabled = true;
  42686. __decorate([
  42687. BABYLON.serializeAsTexture("diffuseTexture")
  42688. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42689. __decorate([
  42690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42691. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42692. __decorate([
  42693. BABYLON.serializeAsTexture("ambientTexture")
  42694. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42695. __decorate([
  42696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42697. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42698. __decorate([
  42699. BABYLON.serializeAsTexture("opacityTexture")
  42700. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42701. __decorate([
  42702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42703. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42704. __decorate([
  42705. BABYLON.serializeAsTexture("reflectionTexture")
  42706. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42707. __decorate([
  42708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42709. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42710. __decorate([
  42711. BABYLON.serializeAsTexture("emissiveTexture")
  42712. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42713. __decorate([
  42714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42715. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42716. __decorate([
  42717. BABYLON.serializeAsTexture("specularTexture")
  42718. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42719. __decorate([
  42720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42721. ], StandardMaterial.prototype, "specularTexture", void 0);
  42722. __decorate([
  42723. BABYLON.serializeAsTexture("bumpTexture")
  42724. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42725. __decorate([
  42726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42727. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42728. __decorate([
  42729. BABYLON.serializeAsTexture("lightmapTexture")
  42730. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42731. __decorate([
  42732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42733. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42734. __decorate([
  42735. BABYLON.serializeAsTexture("refractionTexture")
  42736. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42737. __decorate([
  42738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42739. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42740. __decorate([
  42741. BABYLON.serializeAsColor3("ambient")
  42742. ], StandardMaterial.prototype, "ambientColor", void 0);
  42743. __decorate([
  42744. BABYLON.serializeAsColor3("diffuse")
  42745. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42746. __decorate([
  42747. BABYLON.serializeAsColor3("specular")
  42748. ], StandardMaterial.prototype, "specularColor", void 0);
  42749. __decorate([
  42750. BABYLON.serializeAsColor3("emissive")
  42751. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42752. __decorate([
  42753. BABYLON.serialize()
  42754. ], StandardMaterial.prototype, "specularPower", void 0);
  42755. __decorate([
  42756. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42757. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42758. __decorate([
  42759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42760. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42761. __decorate([
  42762. BABYLON.serialize("useEmissiveAsIllumination")
  42763. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42764. __decorate([
  42765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42766. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42767. __decorate([
  42768. BABYLON.serialize("linkEmissiveWithDiffuse")
  42769. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42770. __decorate([
  42771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42772. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42773. __decorate([
  42774. BABYLON.serialize("useSpecularOverAlpha")
  42775. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42776. __decorate([
  42777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42778. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42779. __decorate([
  42780. BABYLON.serialize("useReflectionOverAlpha")
  42781. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42782. __decorate([
  42783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42784. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42785. __decorate([
  42786. BABYLON.serialize("disableLighting")
  42787. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42788. __decorate([
  42789. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42790. ], StandardMaterial.prototype, "disableLighting", void 0);
  42791. __decorate([
  42792. BABYLON.serialize("useObjectSpaceNormalMap")
  42793. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42794. __decorate([
  42795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42796. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42797. __decorate([
  42798. BABYLON.serialize("useParallax")
  42799. ], StandardMaterial.prototype, "_useParallax", void 0);
  42800. __decorate([
  42801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42802. ], StandardMaterial.prototype, "useParallax", void 0);
  42803. __decorate([
  42804. BABYLON.serialize("useParallaxOcclusion")
  42805. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42806. __decorate([
  42807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42808. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42809. __decorate([
  42810. BABYLON.serialize()
  42811. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42812. __decorate([
  42813. BABYLON.serialize("roughness")
  42814. ], StandardMaterial.prototype, "_roughness", void 0);
  42815. __decorate([
  42816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42817. ], StandardMaterial.prototype, "roughness", void 0);
  42818. __decorate([
  42819. BABYLON.serialize()
  42820. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42821. __decorate([
  42822. BABYLON.serialize()
  42823. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42824. __decorate([
  42825. BABYLON.serialize()
  42826. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42827. __decorate([
  42828. BABYLON.serialize("useLightmapAsShadowmap")
  42829. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42830. __decorate([
  42831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42832. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42833. __decorate([
  42834. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42835. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42836. __decorate([
  42837. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42838. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42839. __decorate([
  42840. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42841. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42842. __decorate([
  42843. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42844. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42845. __decorate([
  42846. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42847. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42848. __decorate([
  42849. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42850. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42851. __decorate([
  42852. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42853. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42854. __decorate([
  42855. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42856. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42857. __decorate([
  42858. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42859. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42860. __decorate([
  42861. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42862. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42863. __decorate([
  42864. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42865. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42866. __decorate([
  42867. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42868. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42869. __decorate([
  42870. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42871. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42872. __decorate([
  42873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42874. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42875. __decorate([
  42876. BABYLON.serialize("maxSimultaneousLights")
  42877. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42878. __decorate([
  42879. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42880. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42881. __decorate([
  42882. BABYLON.serialize("invertNormalMapX")
  42883. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42884. __decorate([
  42885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42886. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42887. __decorate([
  42888. BABYLON.serialize("invertNormalMapY")
  42889. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42890. __decorate([
  42891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42892. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42893. __decorate([
  42894. BABYLON.serialize("twoSidedLighting")
  42895. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42896. __decorate([
  42897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42898. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42899. __decorate([
  42900. BABYLON.serialize()
  42901. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42902. return StandardMaterial;
  42903. }(BABYLON.PushMaterial));
  42904. BABYLON.StandardMaterial = StandardMaterial;
  42905. })(BABYLON || (BABYLON = {}));
  42906. //# sourceMappingURL=babylon.standardMaterial.js.map
  42907. var BABYLON;
  42908. (function (BABYLON) {
  42909. /**
  42910. * Class representing spherical polynomial coefficients to the 3rd degree
  42911. */
  42912. var SphericalPolynomial = /** @class */ (function () {
  42913. function SphericalPolynomial() {
  42914. /**
  42915. * The x coefficients of the spherical polynomial
  42916. */
  42917. this.x = BABYLON.Vector3.Zero();
  42918. /**
  42919. * The y coefficients of the spherical polynomial
  42920. */
  42921. this.y = BABYLON.Vector3.Zero();
  42922. /**
  42923. * The z coefficients of the spherical polynomial
  42924. */
  42925. this.z = BABYLON.Vector3.Zero();
  42926. /**
  42927. * The xx coefficients of the spherical polynomial
  42928. */
  42929. this.xx = BABYLON.Vector3.Zero();
  42930. /**
  42931. * The yy coefficients of the spherical polynomial
  42932. */
  42933. this.yy = BABYLON.Vector3.Zero();
  42934. /**
  42935. * The zz coefficients of the spherical polynomial
  42936. */
  42937. this.zz = BABYLON.Vector3.Zero();
  42938. /**
  42939. * The xy coefficients of the spherical polynomial
  42940. */
  42941. this.xy = BABYLON.Vector3.Zero();
  42942. /**
  42943. * The yz coefficients of the spherical polynomial
  42944. */
  42945. this.yz = BABYLON.Vector3.Zero();
  42946. /**
  42947. * The zx coefficients of the spherical polynomial
  42948. */
  42949. this.zx = BABYLON.Vector3.Zero();
  42950. }
  42951. /**
  42952. * Adds an ambient color to the spherical polynomial
  42953. * @param color the color to add
  42954. */
  42955. SphericalPolynomial.prototype.addAmbient = function (color) {
  42956. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42957. this.xx = this.xx.add(colorVector);
  42958. this.yy = this.yy.add(colorVector);
  42959. this.zz = this.zz.add(colorVector);
  42960. };
  42961. /**
  42962. * Scales the spherical polynomial by the given amount
  42963. * @param scale the amount to scale
  42964. */
  42965. SphericalPolynomial.prototype.scale = function (scale) {
  42966. this.x = this.x.scale(scale);
  42967. this.y = this.y.scale(scale);
  42968. this.z = this.z.scale(scale);
  42969. this.xx = this.xx.scale(scale);
  42970. this.yy = this.yy.scale(scale);
  42971. this.zz = this.zz.scale(scale);
  42972. this.yz = this.yz.scale(scale);
  42973. this.zx = this.zx.scale(scale);
  42974. this.xy = this.xy.scale(scale);
  42975. };
  42976. /**
  42977. * Gets the spherical polynomial from harmonics
  42978. * @param harmonics the spherical harmonics
  42979. * @returns the spherical polynomial
  42980. */
  42981. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42982. var result = new SphericalPolynomial();
  42983. result.x = harmonics.l11.scale(1.02333);
  42984. result.y = harmonics.l1_1.scale(1.02333);
  42985. result.z = harmonics.l10.scale(1.02333);
  42986. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42987. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42988. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42989. result.yz = harmonics.l2_1.scale(0.858086);
  42990. result.zx = harmonics.l21.scale(0.858086);
  42991. result.xy = harmonics.l2_2.scale(0.858086);
  42992. result.scale(1.0 / Math.PI);
  42993. return result;
  42994. };
  42995. /**
  42996. * Constructs a spherical polynomial from an array.
  42997. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42998. * @returns the spherical polynomial
  42999. */
  43000. SphericalPolynomial.FromArray = function (data) {
  43001. var sp = new SphericalPolynomial();
  43002. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43003. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43004. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43005. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43006. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43007. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43008. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43009. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43010. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43011. return sp;
  43012. };
  43013. return SphericalPolynomial;
  43014. }());
  43015. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43016. /**
  43017. * Class representing spherical harmonics coefficients to the 3rd degree
  43018. */
  43019. var SphericalHarmonics = /** @class */ (function () {
  43020. function SphericalHarmonics() {
  43021. /**
  43022. * The l0,0 coefficients of the spherical harmonics
  43023. */
  43024. this.l00 = BABYLON.Vector3.Zero();
  43025. /**
  43026. * The l1,-1 coefficients of the spherical harmonics
  43027. */
  43028. this.l1_1 = BABYLON.Vector3.Zero();
  43029. /**
  43030. * The l1,0 coefficients of the spherical harmonics
  43031. */
  43032. this.l10 = BABYLON.Vector3.Zero();
  43033. /**
  43034. * The l1,1 coefficients of the spherical harmonics
  43035. */
  43036. this.l11 = BABYLON.Vector3.Zero();
  43037. /**
  43038. * The l2,-2 coefficients of the spherical harmonics
  43039. */
  43040. this.l2_2 = BABYLON.Vector3.Zero();
  43041. /**
  43042. * The l2,-1 coefficients of the spherical harmonics
  43043. */
  43044. this.l2_1 = BABYLON.Vector3.Zero();
  43045. /**
  43046. * The l2,0 coefficients of the spherical harmonics
  43047. */
  43048. this.l20 = BABYLON.Vector3.Zero();
  43049. /**
  43050. * The l2,1 coefficients of the spherical harmonics
  43051. */
  43052. this.l21 = BABYLON.Vector3.Zero();
  43053. /**
  43054. * The l2,2 coefficients of the spherical harmonics
  43055. */
  43056. this.lL22 = BABYLON.Vector3.Zero();
  43057. }
  43058. /**
  43059. * Adds a light to the spherical harmonics
  43060. * @param direction the direction of the light
  43061. * @param color the color of the light
  43062. * @param deltaSolidAngle the delta solid angle of the light
  43063. */
  43064. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43065. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43066. var c = colorVector.scale(deltaSolidAngle);
  43067. this.l00 = this.l00.add(c.scale(0.282095));
  43068. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43069. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43070. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43071. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43072. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43073. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43074. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43075. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43076. };
  43077. /**
  43078. * Scales the spherical harmonics by the given amount
  43079. * @param scale the amount to scale
  43080. */
  43081. SphericalHarmonics.prototype.scale = function (scale) {
  43082. this.l00 = this.l00.scale(scale);
  43083. this.l1_1 = this.l1_1.scale(scale);
  43084. this.l10 = this.l10.scale(scale);
  43085. this.l11 = this.l11.scale(scale);
  43086. this.l2_2 = this.l2_2.scale(scale);
  43087. this.l2_1 = this.l2_1.scale(scale);
  43088. this.l20 = this.l20.scale(scale);
  43089. this.l21 = this.l21.scale(scale);
  43090. this.lL22 = this.lL22.scale(scale);
  43091. };
  43092. /**
  43093. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43094. *
  43095. * ```
  43096. * E_lm = A_l * L_lm
  43097. * ```
  43098. *
  43099. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43100. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43101. * the scaling factors are given in equation 9.
  43102. */
  43103. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43104. // Constant (Band 0)
  43105. this.l00 = this.l00.scale(3.141593);
  43106. // Linear (Band 1)
  43107. this.l1_1 = this.l1_1.scale(2.094395);
  43108. this.l10 = this.l10.scale(2.094395);
  43109. this.l11 = this.l11.scale(2.094395);
  43110. // Quadratic (Band 2)
  43111. this.l2_2 = this.l2_2.scale(0.785398);
  43112. this.l2_1 = this.l2_1.scale(0.785398);
  43113. this.l20 = this.l20.scale(0.785398);
  43114. this.l21 = this.l21.scale(0.785398);
  43115. this.lL22 = this.lL22.scale(0.785398);
  43116. };
  43117. /**
  43118. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43119. *
  43120. * ```
  43121. * L = (1/pi) * E * rho
  43122. * ```
  43123. *
  43124. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43125. */
  43126. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43127. this.scale(1.0 / Math.PI);
  43128. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43129. // (The pixel shader must apply albedo after texture fetches, etc).
  43130. };
  43131. /**
  43132. * Gets the spherical harmonics from polynomial
  43133. * @param polynomial the spherical polynomial
  43134. * @returns the spherical harmonics
  43135. */
  43136. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43137. var result = new SphericalHarmonics();
  43138. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43139. result.l1_1 = polynomial.y.scale(0.977204);
  43140. result.l10 = polynomial.z.scale(0.977204);
  43141. result.l11 = polynomial.x.scale(0.977204);
  43142. result.l2_2 = polynomial.xy.scale(1.16538);
  43143. result.l2_1 = polynomial.yz.scale(1.16538);
  43144. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43145. result.l21 = polynomial.zx.scale(1.16538);
  43146. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43147. result.scale(Math.PI);
  43148. return result;
  43149. };
  43150. /**
  43151. * Constructs a spherical harmonics from an array.
  43152. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43153. * @returns the spherical harmonics
  43154. */
  43155. SphericalHarmonics.FromArray = function (data) {
  43156. var sh = new SphericalHarmonics();
  43157. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43158. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43159. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43160. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43161. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43162. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43163. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43164. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43165. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43166. return sh;
  43167. };
  43168. return SphericalHarmonics;
  43169. }());
  43170. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43171. })(BABYLON || (BABYLON = {}));
  43172. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43173. var BABYLON;
  43174. (function (BABYLON) {
  43175. var FileFaceOrientation = /** @class */ (function () {
  43176. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43177. this.name = name;
  43178. this.worldAxisForNormal = worldAxisForNormal;
  43179. this.worldAxisForFileX = worldAxisForFileX;
  43180. this.worldAxisForFileY = worldAxisForFileY;
  43181. }
  43182. return FileFaceOrientation;
  43183. }());
  43184. ;
  43185. /**
  43186. * Helper class dealing with the extraction of spherical polynomial dataArray
  43187. * from a cube map.
  43188. */
  43189. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43190. function CubeMapToSphericalPolynomialTools() {
  43191. }
  43192. /**
  43193. * Converts a texture to the according Spherical Polynomial data.
  43194. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43195. *
  43196. * @param texture The texture to extract the information from.
  43197. * @return The Spherical Polynomial data.
  43198. */
  43199. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43200. if (!texture.isCube) {
  43201. // Only supports cube Textures currently.
  43202. return null;
  43203. }
  43204. var size = texture.getSize().width;
  43205. var right = texture.readPixels(0);
  43206. var left = texture.readPixels(1);
  43207. var up;
  43208. var down;
  43209. if (texture.isRenderTarget) {
  43210. up = texture.readPixels(3);
  43211. down = texture.readPixels(2);
  43212. }
  43213. else {
  43214. up = texture.readPixels(2);
  43215. down = texture.readPixels(3);
  43216. }
  43217. var front = texture.readPixels(4);
  43218. var back = texture.readPixels(5);
  43219. var gammaSpace = texture.gammaSpace;
  43220. // Always read as RGBA.
  43221. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43222. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43223. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43224. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43225. }
  43226. var cubeInfo = {
  43227. size: size,
  43228. right: right,
  43229. left: left,
  43230. up: up,
  43231. down: down,
  43232. front: front,
  43233. back: back,
  43234. format: format,
  43235. type: type,
  43236. gammaSpace: gammaSpace,
  43237. };
  43238. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43239. };
  43240. /**
  43241. * Converts a cubemap to the according Spherical Polynomial data.
  43242. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43243. *
  43244. * @param cubeInfo The Cube map to extract the information from.
  43245. * @return The Spherical Polynomial data.
  43246. */
  43247. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43248. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43249. var totalSolidAngle = 0.0;
  43250. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43251. var du = 2.0 / cubeInfo.size;
  43252. var dv = du;
  43253. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43254. var minUV = du * 0.5 - 1.0;
  43255. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43256. var fileFace = this.FileFaces[faceIndex];
  43257. var dataArray = cubeInfo[fileFace.name];
  43258. var v = minUV;
  43259. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43260. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43261. // Because SP is still linear, so summation is fine in that basis.
  43262. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43263. for (var y = 0; y < cubeInfo.size; y++) {
  43264. var u = minUV;
  43265. for (var x = 0; x < cubeInfo.size; x++) {
  43266. // World direction (not normalised)
  43267. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43268. worldDirection.normalize();
  43269. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43270. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43271. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43272. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43273. // Handle Integer types.
  43274. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43275. r /= 255;
  43276. g /= 255;
  43277. b /= 255;
  43278. }
  43279. // Handle Gamma space textures.
  43280. if (cubeInfo.gammaSpace) {
  43281. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43282. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43283. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43284. }
  43285. var color = new BABYLON.Color3(r, g, b);
  43286. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43287. totalSolidAngle += deltaSolidAngle;
  43288. u += du;
  43289. }
  43290. v += dv;
  43291. }
  43292. }
  43293. // Solid angle for entire sphere is 4*pi
  43294. var sphereSolidAngle = 4.0 * Math.PI;
  43295. // Adjust the solid angle to allow for how many faces we processed.
  43296. var facesProcessed = 6.0;
  43297. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43298. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43299. // This is needed because the numerical integration over the cube uses a
  43300. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43301. // and also to compensate for accumulative error due to float precision in the summation.
  43302. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43303. sphericalHarmonics.scale(correctionFactor);
  43304. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43305. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43306. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43307. };
  43308. CubeMapToSphericalPolynomialTools.FileFaces = [
  43309. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43310. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43311. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43312. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43313. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43314. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43315. ];
  43316. return CubeMapToSphericalPolynomialTools;
  43317. }());
  43318. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43319. })(BABYLON || (BABYLON = {}));
  43320. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43321. var BABYLON;
  43322. (function (BABYLON) {
  43323. /**
  43324. * Manages the defines for the PBR Material.
  43325. * @hiddenChildren
  43326. */
  43327. var PBRMaterialDefines = /** @class */ (function (_super) {
  43328. __extends(PBRMaterialDefines, _super);
  43329. /**
  43330. * Initializes the PBR Material defines.
  43331. */
  43332. function PBRMaterialDefines() {
  43333. var _this = _super.call(this) || this;
  43334. _this.PBR = true;
  43335. _this.MAINUV1 = false;
  43336. _this.MAINUV2 = false;
  43337. _this.UV1 = false;
  43338. _this.UV2 = false;
  43339. _this.ALBEDO = false;
  43340. _this.ALBEDODIRECTUV = 0;
  43341. _this.VERTEXCOLOR = false;
  43342. _this.AMBIENT = false;
  43343. _this.AMBIENTDIRECTUV = 0;
  43344. _this.AMBIENTINGRAYSCALE = false;
  43345. _this.OPACITY = false;
  43346. _this.VERTEXALPHA = false;
  43347. _this.OPACITYDIRECTUV = 0;
  43348. _this.OPACITYRGB = false;
  43349. _this.ALPHATEST = false;
  43350. _this.DEPTHPREPASS = false;
  43351. _this.ALPHABLEND = false;
  43352. _this.ALPHAFROMALBEDO = false;
  43353. _this.ALPHATESTVALUE = "0.5";
  43354. _this.SPECULAROVERALPHA = false;
  43355. _this.RADIANCEOVERALPHA = false;
  43356. _this.ALPHAFRESNEL = false;
  43357. _this.LINEARALPHAFRESNEL = false;
  43358. _this.PREMULTIPLYALPHA = false;
  43359. _this.EMISSIVE = false;
  43360. _this.EMISSIVEDIRECTUV = 0;
  43361. _this.REFLECTIVITY = false;
  43362. _this.REFLECTIVITYDIRECTUV = 0;
  43363. _this.SPECULARTERM = false;
  43364. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43365. _this.MICROSURFACEAUTOMATIC = false;
  43366. _this.LODBASEDMICROSFURACE = false;
  43367. _this.MICROSURFACEMAP = false;
  43368. _this.MICROSURFACEMAPDIRECTUV = 0;
  43369. _this.METALLICWORKFLOW = false;
  43370. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43371. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43372. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43373. _this.AOSTOREINMETALMAPRED = false;
  43374. _this.ENVIRONMENTBRDF = false;
  43375. _this.NORMAL = false;
  43376. _this.TANGENT = false;
  43377. _this.BUMP = false;
  43378. _this.BUMPDIRECTUV = 0;
  43379. _this.OBJECTSPACE_NORMALMAP = false;
  43380. _this.PARALLAX = false;
  43381. _this.PARALLAXOCCLUSION = false;
  43382. _this.NORMALXYSCALE = true;
  43383. _this.LIGHTMAP = false;
  43384. _this.LIGHTMAPDIRECTUV = 0;
  43385. _this.USELIGHTMAPASSHADOWMAP = false;
  43386. _this.GAMMALIGHTMAP = false;
  43387. _this.REFLECTION = false;
  43388. _this.REFLECTIONMAP_3D = false;
  43389. _this.REFLECTIONMAP_SPHERICAL = false;
  43390. _this.REFLECTIONMAP_PLANAR = false;
  43391. _this.REFLECTIONMAP_CUBIC = false;
  43392. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43393. _this.REFLECTIONMAP_PROJECTION = false;
  43394. _this.REFLECTIONMAP_SKYBOX = false;
  43395. _this.REFLECTIONMAP_EXPLICIT = false;
  43396. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43397. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43398. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43399. _this.INVERTCUBICMAP = false;
  43400. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43401. _this.USESPHERICALINVERTEX = false;
  43402. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43403. _this.LODINREFLECTIONALPHA = false;
  43404. _this.GAMMAREFLECTION = false;
  43405. _this.RGBDREFLECTION = false;
  43406. _this.RADIANCEOCCLUSION = false;
  43407. _this.HORIZONOCCLUSION = false;
  43408. _this.REFRACTION = false;
  43409. _this.REFRACTIONMAP_3D = false;
  43410. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43411. _this.LODINREFRACTIONALPHA = false;
  43412. _this.GAMMAREFRACTION = false;
  43413. _this.RGBDREFRACTION = false;
  43414. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43415. _this.INSTANCES = false;
  43416. _this.NUM_BONE_INFLUENCERS = 0;
  43417. _this.BonesPerMesh = 0;
  43418. _this.NONUNIFORMSCALING = false;
  43419. _this.MORPHTARGETS = false;
  43420. _this.MORPHTARGETS_NORMAL = false;
  43421. _this.MORPHTARGETS_TANGENT = false;
  43422. _this.NUM_MORPH_INFLUENCERS = 0;
  43423. _this.IMAGEPROCESSING = false;
  43424. _this.VIGNETTE = false;
  43425. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43426. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43427. _this.TONEMAPPING = false;
  43428. _this.CONTRAST = false;
  43429. _this.COLORCURVES = false;
  43430. _this.COLORGRADING = false;
  43431. _this.COLORGRADING3D = false;
  43432. _this.SAMPLER3DGREENDEPTH = false;
  43433. _this.SAMPLER3DBGRMAP = false;
  43434. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43435. _this.EXPOSURE = false;
  43436. _this.USEPHYSICALLIGHTFALLOFF = false;
  43437. _this.USEGLTFLIGHTFALLOFF = false;
  43438. _this.TWOSIDEDLIGHTING = false;
  43439. _this.SHADOWFLOAT = false;
  43440. _this.CLIPPLANE = false;
  43441. _this.POINTSIZE = false;
  43442. _this.FOG = false;
  43443. _this.LOGARITHMICDEPTH = false;
  43444. _this.FORCENORMALFORWARD = false;
  43445. _this.SPECULARAA = false;
  43446. _this.UNLIT = false;
  43447. _this.rebuild();
  43448. return _this;
  43449. }
  43450. /**
  43451. * Resets the PBR Material defines.
  43452. */
  43453. PBRMaterialDefines.prototype.reset = function () {
  43454. _super.prototype.reset.call(this);
  43455. this.ALPHATESTVALUE = "0.5";
  43456. this.PBR = true;
  43457. };
  43458. return PBRMaterialDefines;
  43459. }(BABYLON.MaterialDefines));
  43460. /**
  43461. * The Physically based material base class of BJS.
  43462. *
  43463. * This offers the main features of a standard PBR material.
  43464. * For more information, please refer to the documentation :
  43465. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43466. */
  43467. var PBRBaseMaterial = /** @class */ (function (_super) {
  43468. __extends(PBRBaseMaterial, _super);
  43469. /**
  43470. * Instantiates a new PBRMaterial instance.
  43471. *
  43472. * @param name The material name
  43473. * @param scene The scene the material will be use in.
  43474. */
  43475. function PBRBaseMaterial(name, scene) {
  43476. var _this = _super.call(this, name, scene) || this;
  43477. /**
  43478. * Intensity of the direct lights e.g. the four lights available in your scene.
  43479. * This impacts both the direct diffuse and specular highlights.
  43480. */
  43481. _this._directIntensity = 1.0;
  43482. /**
  43483. * Intensity of the emissive part of the material.
  43484. * This helps controlling the emissive effect without modifying the emissive color.
  43485. */
  43486. _this._emissiveIntensity = 1.0;
  43487. /**
  43488. * Intensity of the environment e.g. how much the environment will light the object
  43489. * either through harmonics for rough material or through the refelction for shiny ones.
  43490. */
  43491. _this._environmentIntensity = 1.0;
  43492. /**
  43493. * This is a special control allowing the reduction of the specular highlights coming from the
  43494. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43495. */
  43496. _this._specularIntensity = 1.0;
  43497. /**
  43498. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43499. */
  43500. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43501. /**
  43502. * Debug Control allowing disabling the bump map on this material.
  43503. */
  43504. _this._disableBumpMap = false;
  43505. /**
  43506. * AKA Occlusion Texture Intensity in other nomenclature.
  43507. */
  43508. _this._ambientTextureStrength = 1.0;
  43509. /**
  43510. * The color of a material in ambient lighting.
  43511. */
  43512. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43513. /**
  43514. * AKA Diffuse Color in other nomenclature.
  43515. */
  43516. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43517. /**
  43518. * AKA Specular Color in other nomenclature.
  43519. */
  43520. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43521. /**
  43522. * The color applied when light is reflected from a material.
  43523. */
  43524. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43525. /**
  43526. * The color applied when light is emitted from a material.
  43527. */
  43528. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43529. /**
  43530. * AKA Glossiness in other nomenclature.
  43531. */
  43532. _this._microSurface = 0.9;
  43533. /**
  43534. * source material index of refraction (IOR)' / 'destination material IOR.
  43535. */
  43536. _this._indexOfRefraction = 0.66;
  43537. /**
  43538. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43539. */
  43540. _this._invertRefractionY = false;
  43541. /**
  43542. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43543. * Materials half opaque for instance using refraction could benefit from this control.
  43544. */
  43545. _this._linkRefractionWithTransparency = false;
  43546. /**
  43547. * Specifies that the material will use the light map as a show map.
  43548. */
  43549. _this._useLightmapAsShadowmap = false;
  43550. /**
  43551. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43552. * makes the reflect vector face the model (under horizon).
  43553. */
  43554. _this._useHorizonOcclusion = true;
  43555. /**
  43556. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43557. * too much the area relying on ambient texture to define their ambient occlusion.
  43558. */
  43559. _this._useRadianceOcclusion = true;
  43560. /**
  43561. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43562. */
  43563. _this._useAlphaFromAlbedoTexture = false;
  43564. /**
  43565. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43566. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43567. */
  43568. _this._useSpecularOverAlpha = true;
  43569. /**
  43570. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43571. */
  43572. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43573. /**
  43574. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43575. */
  43576. _this._useRoughnessFromMetallicTextureAlpha = true;
  43577. /**
  43578. * Specifies if the metallic texture contains the roughness information in its green channel.
  43579. */
  43580. _this._useRoughnessFromMetallicTextureGreen = false;
  43581. /**
  43582. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43583. */
  43584. _this._useMetallnessFromMetallicTextureBlue = false;
  43585. /**
  43586. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43587. */
  43588. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43589. /**
  43590. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43591. */
  43592. _this._useAmbientInGrayScale = false;
  43593. /**
  43594. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43595. * The material will try to infer what glossiness each pixel should be.
  43596. */
  43597. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43598. /**
  43599. * Defines the falloff type used in this material.
  43600. * It by default is Physical.
  43601. */
  43602. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43603. /**
  43604. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43605. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43606. */
  43607. _this._useRadianceOverAlpha = true;
  43608. /**
  43609. * Allows using an object space normal map (instead of tangent space).
  43610. */
  43611. _this._useObjectSpaceNormalMap = false;
  43612. /**
  43613. * Allows using the bump map in parallax mode.
  43614. */
  43615. _this._useParallax = false;
  43616. /**
  43617. * Allows using the bump map in parallax occlusion mode.
  43618. */
  43619. _this._useParallaxOcclusion = false;
  43620. /**
  43621. * Controls the scale bias of the parallax mode.
  43622. */
  43623. _this._parallaxScaleBias = 0.05;
  43624. /**
  43625. * If sets to true, disables all the lights affecting the material.
  43626. */
  43627. _this._disableLighting = false;
  43628. /**
  43629. * Number of Simultaneous lights allowed on the material.
  43630. */
  43631. _this._maxSimultaneousLights = 4;
  43632. /**
  43633. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43634. */
  43635. _this._invertNormalMapX = false;
  43636. /**
  43637. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43638. */
  43639. _this._invertNormalMapY = false;
  43640. /**
  43641. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43642. */
  43643. _this._twoSidedLighting = false;
  43644. /**
  43645. * Defines the alpha limits in alpha test mode.
  43646. */
  43647. _this._alphaCutOff = 0.4;
  43648. /**
  43649. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43650. */
  43651. _this._forceAlphaTest = false;
  43652. /**
  43653. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43654. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43655. */
  43656. _this._useAlphaFresnel = false;
  43657. /**
  43658. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43659. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43660. */
  43661. _this._useLinearAlphaFresnel = false;
  43662. /**
  43663. * The transparency mode of the material.
  43664. */
  43665. _this._transparencyMode = null;
  43666. /**
  43667. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43668. * from cos thetav and roughness:
  43669. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43670. */
  43671. _this._environmentBRDFTexture = null;
  43672. /**
  43673. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43674. */
  43675. _this._forceIrradianceInFragment = false;
  43676. /**
  43677. * Force normal to face away from face.
  43678. */
  43679. _this._forceNormalForward = false;
  43680. /**
  43681. * Enables specular anti aliasing in the PBR shader.
  43682. * It will both interacts on the Geometry for analytical and IBL lighting.
  43683. * It also prefilter the roughness map based on the bump values.
  43684. */
  43685. _this._enableSpecularAntiAliasing = false;
  43686. /**
  43687. * Stores the available render targets.
  43688. */
  43689. _this._renderTargets = new BABYLON.SmartArray(16);
  43690. /**
  43691. * Sets the global ambient color for the material used in lighting calculations.
  43692. */
  43693. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43694. /**
  43695. * If set to true, no lighting calculations will be applied.
  43696. */
  43697. _this._unlit = false;
  43698. // Setup the default processing configuration to the scene.
  43699. _this._attachImageProcessingConfiguration(null);
  43700. _this.getRenderTargetTextures = function () {
  43701. _this._renderTargets.reset();
  43702. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43703. _this._renderTargets.push(_this._reflectionTexture);
  43704. }
  43705. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43706. _this._renderTargets.push(_this._refractionTexture);
  43707. }
  43708. return _this._renderTargets;
  43709. };
  43710. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43711. return _this;
  43712. }
  43713. /**
  43714. * Attaches a new image processing configuration to the PBR Material.
  43715. * @param configuration
  43716. */
  43717. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43718. var _this = this;
  43719. if (configuration === this._imageProcessingConfiguration) {
  43720. return;
  43721. }
  43722. // Detaches observer.
  43723. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43724. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43725. }
  43726. // Pick the scene configuration if needed.
  43727. if (!configuration) {
  43728. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43729. }
  43730. else {
  43731. this._imageProcessingConfiguration = configuration;
  43732. }
  43733. // Attaches observer.
  43734. if (this._imageProcessingConfiguration) {
  43735. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43736. _this._markAllSubMeshesAsImageProcessingDirty();
  43737. });
  43738. }
  43739. };
  43740. /**
  43741. * Gets the name of the material class.
  43742. */
  43743. PBRBaseMaterial.prototype.getClassName = function () {
  43744. return "PBRBaseMaterial";
  43745. };
  43746. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43747. /**
  43748. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43749. */
  43750. get: function () {
  43751. return this._useLogarithmicDepth;
  43752. },
  43753. /**
  43754. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43755. */
  43756. set: function (value) {
  43757. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43758. },
  43759. enumerable: true,
  43760. configurable: true
  43761. });
  43762. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43763. /**
  43764. * Gets the current transparency mode.
  43765. */
  43766. get: function () {
  43767. return this._transparencyMode;
  43768. },
  43769. /**
  43770. * Sets the transparency mode of the material.
  43771. *
  43772. * | Value | Type | Description |
  43773. * | ----- | ----------------------------------- | ----------- |
  43774. * | 0 | OPAQUE | |
  43775. * | 1 | ALPHATEST | |
  43776. * | 2 | ALPHABLEND | |
  43777. * | 3 | ALPHATESTANDBLEND | |
  43778. *
  43779. */
  43780. set: function (value) {
  43781. if (this._transparencyMode === value) {
  43782. return;
  43783. }
  43784. this._transparencyMode = value;
  43785. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43786. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43787. },
  43788. enumerable: true,
  43789. configurable: true
  43790. });
  43791. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43792. /**
  43793. * Returns true if alpha blending should be disabled.
  43794. */
  43795. get: function () {
  43796. return (this._linkRefractionWithTransparency ||
  43797. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43798. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43799. },
  43800. enumerable: true,
  43801. configurable: true
  43802. });
  43803. /**
  43804. * Specifies whether or not this material should be rendered in alpha blend mode.
  43805. */
  43806. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43807. if (this._disableAlphaBlending) {
  43808. return false;
  43809. }
  43810. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43811. };
  43812. /**
  43813. * Specifies if the mesh will require alpha blending.
  43814. * @param mesh - BJS mesh.
  43815. */
  43816. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43817. if (this._disableAlphaBlending) {
  43818. return false;
  43819. }
  43820. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43821. };
  43822. /**
  43823. * Specifies whether or not this material should be rendered in alpha test mode.
  43824. */
  43825. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43826. if (this._forceAlphaTest) {
  43827. return true;
  43828. }
  43829. if (this._linkRefractionWithTransparency) {
  43830. return false;
  43831. }
  43832. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43833. };
  43834. /**
  43835. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43836. */
  43837. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43838. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43839. };
  43840. /**
  43841. * Gets the texture used for the alpha test.
  43842. */
  43843. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43844. return this._albedoTexture;
  43845. };
  43846. /**
  43847. * Specifies that the submesh is ready to be used.
  43848. * @param mesh - BJS mesh.
  43849. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43850. * @param useInstances - Specifies that instances should be used.
  43851. * @returns - boolean indicating that the submesh is ready or not.
  43852. */
  43853. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43854. if (subMesh.effect && this.isFrozen) {
  43855. if (this._wasPreviouslyReady) {
  43856. return true;
  43857. }
  43858. }
  43859. if (!subMesh._materialDefines) {
  43860. subMesh._materialDefines = new PBRMaterialDefines();
  43861. }
  43862. var defines = subMesh._materialDefines;
  43863. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43864. if (defines._renderId === this.getScene().getRenderId()) {
  43865. return true;
  43866. }
  43867. }
  43868. var scene = this.getScene();
  43869. var engine = scene.getEngine();
  43870. if (defines._areTexturesDirty) {
  43871. if (scene.texturesEnabled) {
  43872. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43873. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43874. return false;
  43875. }
  43876. }
  43877. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43878. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43879. return false;
  43880. }
  43881. }
  43882. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43883. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43884. return false;
  43885. }
  43886. }
  43887. var reflectionTexture = this._getReflectionTexture();
  43888. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43889. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43890. return false;
  43891. }
  43892. }
  43893. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43894. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43895. return false;
  43896. }
  43897. }
  43898. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43899. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43900. return false;
  43901. }
  43902. }
  43903. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43904. if (this._metallicTexture) {
  43905. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43906. return false;
  43907. }
  43908. }
  43909. else if (this._reflectivityTexture) {
  43910. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43911. return false;
  43912. }
  43913. }
  43914. if (this._microSurfaceTexture) {
  43915. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43916. return false;
  43917. }
  43918. }
  43919. }
  43920. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43921. // Bump texture cannot be not blocking.
  43922. if (!this._bumpTexture.isReady()) {
  43923. return false;
  43924. }
  43925. }
  43926. var refractionTexture = this._getRefractionTexture();
  43927. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43928. if (!refractionTexture.isReadyOrNotBlocking()) {
  43929. return false;
  43930. }
  43931. }
  43932. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43933. // This is blocking.
  43934. if (!this._environmentBRDFTexture.isReady()) {
  43935. return false;
  43936. }
  43937. }
  43938. }
  43939. }
  43940. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43941. if (!this._imageProcessingConfiguration.isReady()) {
  43942. return false;
  43943. }
  43944. }
  43945. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43946. mesh.createNormals(true);
  43947. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43948. }
  43949. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43950. if (effect) {
  43951. scene.resetCachedMaterial();
  43952. subMesh.setEffect(effect, defines);
  43953. this.buildUniformLayout();
  43954. }
  43955. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43956. return false;
  43957. }
  43958. defines._renderId = scene.getRenderId();
  43959. this._wasPreviouslyReady = true;
  43960. return true;
  43961. };
  43962. /**
  43963. * Specifies if the material uses metallic roughness workflow.
  43964. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43965. */
  43966. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43967. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43968. return true;
  43969. }
  43970. return false;
  43971. };
  43972. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43973. if (onCompiled === void 0) { onCompiled = null; }
  43974. if (onError === void 0) { onError = null; }
  43975. if (useInstances === void 0) { useInstances = null; }
  43976. if (useClipPlane === void 0) { useClipPlane = null; }
  43977. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43978. if (!defines.isDirty) {
  43979. return null;
  43980. }
  43981. defines.markAsProcessed();
  43982. var scene = this.getScene();
  43983. var engine = scene.getEngine();
  43984. // Fallbacks
  43985. var fallbacks = new BABYLON.EffectFallbacks();
  43986. var fallbackRank = 0;
  43987. if (defines.USESPHERICALINVERTEX) {
  43988. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43989. }
  43990. if (defines.FOG) {
  43991. fallbacks.addFallback(fallbackRank, "FOG");
  43992. }
  43993. if (defines.SPECULARAA) {
  43994. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43995. }
  43996. if (defines.POINTSIZE) {
  43997. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43998. }
  43999. if (defines.LOGARITHMICDEPTH) {
  44000. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44001. }
  44002. if (defines.PARALLAX) {
  44003. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44004. }
  44005. if (defines.PARALLAXOCCLUSION) {
  44006. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44007. }
  44008. if (defines.ENVIRONMENTBRDF) {
  44009. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44010. }
  44011. if (defines.TANGENT) {
  44012. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44013. }
  44014. if (defines.BUMP) {
  44015. fallbacks.addFallback(fallbackRank++, "BUMP");
  44016. }
  44017. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44018. if (defines.SPECULARTERM) {
  44019. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44020. }
  44021. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44022. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44023. }
  44024. if (defines.LIGHTMAP) {
  44025. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44026. }
  44027. if (defines.NORMAL) {
  44028. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44029. }
  44030. if (defines.AMBIENT) {
  44031. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44032. }
  44033. if (defines.EMISSIVE) {
  44034. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44035. }
  44036. if (defines.VERTEXCOLOR) {
  44037. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44038. }
  44039. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44040. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44041. }
  44042. if (defines.MORPHTARGETS) {
  44043. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44044. }
  44045. //Attributes
  44046. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44047. if (defines.NORMAL) {
  44048. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44049. }
  44050. if (defines.TANGENT) {
  44051. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44052. }
  44053. if (defines.UV1) {
  44054. attribs.push(BABYLON.VertexBuffer.UVKind);
  44055. }
  44056. if (defines.UV2) {
  44057. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44058. }
  44059. if (defines.VERTEXCOLOR) {
  44060. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44061. }
  44062. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44063. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44064. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44065. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44066. "vFogInfos", "vFogColor", "pointSize",
  44067. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44068. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44069. "mBones",
  44070. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44071. "vLightingIntensity",
  44072. "logarithmicDepthConstant",
  44073. "vSphericalX", "vSphericalY", "vSphericalZ",
  44074. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44075. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44076. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44077. "vTangentSpaceParams"
  44078. ];
  44079. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44080. "bumpSampler", "lightmapSampler", "opacitySampler",
  44081. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44082. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44083. "microSurfaceSampler", "environmentBrdfSampler"];
  44084. var uniformBuffers = ["Material", "Scene"];
  44085. if (BABYLON.ImageProcessingConfiguration) {
  44086. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44087. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44088. }
  44089. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44090. uniformsNames: uniforms,
  44091. uniformBuffersNames: uniformBuffers,
  44092. samplers: samplers,
  44093. defines: defines,
  44094. maxSimultaneousLights: this._maxSimultaneousLights
  44095. });
  44096. var join = defines.toString();
  44097. return engine.createEffect("pbr", {
  44098. attributes: attribs,
  44099. uniformsNames: uniforms,
  44100. uniformBuffersNames: uniformBuffers,
  44101. samplers: samplers,
  44102. defines: join,
  44103. fallbacks: fallbacks,
  44104. onCompiled: onCompiled,
  44105. onError: onError,
  44106. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44107. }, engine);
  44108. };
  44109. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44110. if (useInstances === void 0) { useInstances = null; }
  44111. if (useClipPlane === void 0) { useClipPlane = null; }
  44112. var scene = this.getScene();
  44113. var engine = scene.getEngine();
  44114. // Lights
  44115. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44116. defines._needNormals = true;
  44117. // Textures
  44118. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44119. if (defines._areTexturesDirty) {
  44120. defines._needUVs = false;
  44121. if (scene.texturesEnabled) {
  44122. if (scene.getEngine().getCaps().textureLOD) {
  44123. defines.LODBASEDMICROSFURACE = true;
  44124. }
  44125. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44126. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44127. }
  44128. else {
  44129. defines.ALBEDO = false;
  44130. }
  44131. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44132. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44133. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44134. }
  44135. else {
  44136. defines.AMBIENT = false;
  44137. }
  44138. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44139. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44140. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44141. }
  44142. else {
  44143. defines.OPACITY = false;
  44144. }
  44145. var reflectionTexture = this._getReflectionTexture();
  44146. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44147. defines.REFLECTION = true;
  44148. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44149. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44150. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44151. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44152. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44153. defines.INVERTCUBICMAP = true;
  44154. }
  44155. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44156. switch (reflectionTexture.coordinatesMode) {
  44157. case BABYLON.Texture.EXPLICIT_MODE:
  44158. defines.REFLECTIONMAP_EXPLICIT = true;
  44159. break;
  44160. case BABYLON.Texture.PLANAR_MODE:
  44161. defines.REFLECTIONMAP_PLANAR = true;
  44162. break;
  44163. case BABYLON.Texture.PROJECTION_MODE:
  44164. defines.REFLECTIONMAP_PROJECTION = true;
  44165. break;
  44166. case BABYLON.Texture.SKYBOX_MODE:
  44167. defines.REFLECTIONMAP_SKYBOX = true;
  44168. break;
  44169. case BABYLON.Texture.SPHERICAL_MODE:
  44170. defines.REFLECTIONMAP_SPHERICAL = true;
  44171. break;
  44172. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44173. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44174. break;
  44175. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44176. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44177. break;
  44178. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44179. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44180. break;
  44181. case BABYLON.Texture.CUBIC_MODE:
  44182. case BABYLON.Texture.INVCUBIC_MODE:
  44183. default:
  44184. defines.REFLECTIONMAP_CUBIC = true;
  44185. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44186. break;
  44187. }
  44188. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44189. if (reflectionTexture.sphericalPolynomial) {
  44190. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44191. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44192. defines.USESPHERICALINVERTEX = false;
  44193. }
  44194. else {
  44195. defines.USESPHERICALINVERTEX = true;
  44196. }
  44197. }
  44198. }
  44199. }
  44200. else {
  44201. defines.REFLECTION = false;
  44202. defines.REFLECTIONMAP_3D = false;
  44203. defines.REFLECTIONMAP_SPHERICAL = false;
  44204. defines.REFLECTIONMAP_PLANAR = false;
  44205. defines.REFLECTIONMAP_CUBIC = false;
  44206. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44207. defines.REFLECTIONMAP_PROJECTION = false;
  44208. defines.REFLECTIONMAP_SKYBOX = false;
  44209. defines.REFLECTIONMAP_EXPLICIT = false;
  44210. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44211. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44212. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44213. defines.INVERTCUBICMAP = false;
  44214. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44215. defines.USESPHERICALINVERTEX = false;
  44216. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44217. defines.LODINREFLECTIONALPHA = false;
  44218. defines.GAMMAREFLECTION = false;
  44219. defines.RGBDREFLECTION = false;
  44220. }
  44221. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44222. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44223. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44224. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44225. }
  44226. else {
  44227. defines.LIGHTMAP = false;
  44228. }
  44229. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44230. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44231. }
  44232. else {
  44233. defines.EMISSIVE = false;
  44234. }
  44235. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44236. if (this._metallicTexture) {
  44237. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44238. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44239. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44240. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44241. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44242. }
  44243. else if (this._reflectivityTexture) {
  44244. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44245. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44246. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44247. }
  44248. else {
  44249. defines.REFLECTIVITY = false;
  44250. }
  44251. if (this._microSurfaceTexture) {
  44252. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44253. }
  44254. else {
  44255. defines.MICROSURFACEMAP = false;
  44256. }
  44257. }
  44258. else {
  44259. defines.REFLECTIVITY = false;
  44260. defines.MICROSURFACEMAP = false;
  44261. }
  44262. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44263. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44264. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44265. defines.PARALLAX = true;
  44266. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44267. }
  44268. else {
  44269. defines.PARALLAX = false;
  44270. }
  44271. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44272. }
  44273. else {
  44274. defines.BUMP = false;
  44275. }
  44276. var refractionTexture = this._getRefractionTexture();
  44277. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44278. defines.REFRACTION = true;
  44279. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44280. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44281. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44282. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44283. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44284. if (this._linkRefractionWithTransparency) {
  44285. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44286. }
  44287. }
  44288. else {
  44289. defines.REFRACTION = false;
  44290. }
  44291. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44292. defines.ENVIRONMENTBRDF = true;
  44293. }
  44294. else {
  44295. defines.ENVIRONMENTBRDF = false;
  44296. }
  44297. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44298. defines.ALPHAFROMALBEDO = true;
  44299. }
  44300. else {
  44301. defines.ALPHAFROMALBEDO = false;
  44302. }
  44303. }
  44304. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44305. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44306. defines.USEPHYSICALLIGHTFALLOFF = false;
  44307. defines.USEGLTFLIGHTFALLOFF = false;
  44308. }
  44309. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44310. defines.USEPHYSICALLIGHTFALLOFF = false;
  44311. defines.USEGLTFLIGHTFALLOFF = true;
  44312. }
  44313. else {
  44314. defines.USEPHYSICALLIGHTFALLOFF = true;
  44315. defines.USEGLTFLIGHTFALLOFF = false;
  44316. }
  44317. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44318. if (!this.backFaceCulling && this._twoSidedLighting) {
  44319. defines.TWOSIDEDLIGHTING = true;
  44320. }
  44321. else {
  44322. defines.TWOSIDEDLIGHTING = false;
  44323. }
  44324. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44325. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44326. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44327. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44328. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44329. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44330. }
  44331. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44332. this._imageProcessingConfiguration.prepareDefines(defines);
  44333. }
  44334. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44335. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44336. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44337. // Misc.
  44338. if (defines._areMiscDirty) {
  44339. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44340. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44341. }
  44342. // Values that need to be evaluated on every frame
  44343. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44344. // Attribs
  44345. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44346. };
  44347. /**
  44348. * Force shader compilation
  44349. */
  44350. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44351. var _this = this;
  44352. var localOptions = __assign({ clipPlane: false }, options);
  44353. var defines = new PBRMaterialDefines();
  44354. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44355. if (effect.isReady()) {
  44356. if (onCompiled) {
  44357. onCompiled(this);
  44358. }
  44359. }
  44360. else {
  44361. effect.onCompileObservable.add(function () {
  44362. if (onCompiled) {
  44363. onCompiled(_this);
  44364. }
  44365. });
  44366. }
  44367. };
  44368. /**
  44369. * Initializes the uniform buffer layout for the shader.
  44370. */
  44371. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44372. // Order is important !
  44373. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44374. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44375. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44376. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44377. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44378. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44379. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44380. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44381. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44382. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44383. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44384. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44385. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44386. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44387. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44388. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44389. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44390. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44391. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44392. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44393. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44394. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44395. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44396. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44397. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44398. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44399. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44400. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44401. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44402. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44403. this._uniformBuffer.addUniform("pointSize", 1);
  44404. this._uniformBuffer.create();
  44405. };
  44406. /**
  44407. * Unbinds the textures.
  44408. */
  44409. PBRBaseMaterial.prototype.unbind = function () {
  44410. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44411. this._uniformBuffer.setTexture("reflectionSampler", null);
  44412. }
  44413. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44414. this._uniformBuffer.setTexture("refractionSampler", null);
  44415. }
  44416. _super.prototype.unbind.call(this);
  44417. };
  44418. /**
  44419. * Binds the submesh data.
  44420. * @param world - The world matrix.
  44421. * @param mesh - The BJS mesh.
  44422. * @param subMesh - A submesh of the BJS mesh.
  44423. */
  44424. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44425. var scene = this.getScene();
  44426. var defines = subMesh._materialDefines;
  44427. if (!defines) {
  44428. return;
  44429. }
  44430. var effect = subMesh.effect;
  44431. if (!effect) {
  44432. return;
  44433. }
  44434. this._activeEffect = effect;
  44435. // Matrices
  44436. this.bindOnlyWorldMatrix(world);
  44437. // Normal Matrix
  44438. if (defines.OBJECTSPACE_NORMALMAP) {
  44439. world.toNormalMatrix(this._normalMatrix);
  44440. this.bindOnlyNormalMatrix(this._normalMatrix);
  44441. }
  44442. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44443. // Bones
  44444. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44445. var reflectionTexture = null;
  44446. if (mustRebind) {
  44447. this._uniformBuffer.bindToEffect(effect, "Material");
  44448. this.bindViewProjection(effect);
  44449. reflectionTexture = this._getReflectionTexture();
  44450. var refractionTexture = this._getRefractionTexture();
  44451. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44452. // Texture uniforms
  44453. if (scene.texturesEnabled) {
  44454. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44455. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44456. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44457. }
  44458. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44459. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44460. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44461. }
  44462. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44463. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44464. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44465. }
  44466. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44467. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44468. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44469. if (reflectionTexture.boundingBoxSize) {
  44470. var cubeTexture = reflectionTexture;
  44471. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44472. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44473. }
  44474. var polynomials = reflectionTexture.sphericalPolynomial;
  44475. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44476. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44477. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44478. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44479. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44480. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44481. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44482. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44483. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44484. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44485. }
  44486. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44487. }
  44488. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44489. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44490. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44491. }
  44492. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44493. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44494. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44495. }
  44496. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44497. if (this._metallicTexture) {
  44498. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44499. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44500. }
  44501. else if (this._reflectivityTexture) {
  44502. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44503. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44504. }
  44505. if (this._microSurfaceTexture) {
  44506. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44507. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44508. }
  44509. }
  44510. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44511. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44512. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44513. if (scene._mirroredCameraPosition) {
  44514. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44515. }
  44516. else {
  44517. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44518. }
  44519. }
  44520. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44521. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44522. var depth = 1.0;
  44523. if (!refractionTexture.isCube) {
  44524. if (refractionTexture.depth) {
  44525. depth = refractionTexture.depth;
  44526. }
  44527. }
  44528. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44529. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44530. }
  44531. }
  44532. // Point size
  44533. if (this.pointsCloud) {
  44534. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44535. }
  44536. // Colors
  44537. if (defines.METALLICWORKFLOW) {
  44538. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44539. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44540. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44541. }
  44542. else {
  44543. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44544. }
  44545. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44546. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44547. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44548. // Misc
  44549. this._lightingInfos.x = this._directIntensity;
  44550. this._lightingInfos.y = this._emissiveIntensity;
  44551. this._lightingInfos.z = this._environmentIntensity;
  44552. this._lightingInfos.w = this._specularIntensity;
  44553. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44554. }
  44555. // Textures
  44556. if (scene.texturesEnabled) {
  44557. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44558. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44559. }
  44560. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44561. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44562. }
  44563. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44564. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44565. }
  44566. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44567. if (defines.LODBASEDMICROSFURACE) {
  44568. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44569. }
  44570. else {
  44571. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44572. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44573. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44574. }
  44575. }
  44576. if (defines.ENVIRONMENTBRDF) {
  44577. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44578. }
  44579. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44580. if (defines.LODBASEDMICROSFURACE) {
  44581. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44582. }
  44583. else {
  44584. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44585. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44586. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44587. }
  44588. }
  44589. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44590. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44591. }
  44592. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44593. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44594. }
  44595. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44596. if (this._metallicTexture) {
  44597. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44598. }
  44599. else if (this._reflectivityTexture) {
  44600. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44601. }
  44602. if (this._microSurfaceTexture) {
  44603. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44604. }
  44605. }
  44606. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44607. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44608. }
  44609. }
  44610. // Clip plane
  44611. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44612. // Colors
  44613. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44614. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44615. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44616. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44617. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44618. }
  44619. if (mustRebind || !this.isFrozen) {
  44620. // Lights
  44621. if (scene.lightsEnabled && !this._disableLighting) {
  44622. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44623. }
  44624. // View
  44625. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44626. this.bindView(effect);
  44627. }
  44628. // Fog
  44629. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44630. // Morph targets
  44631. if (defines.NUM_MORPH_INFLUENCERS) {
  44632. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44633. }
  44634. // image processing
  44635. this._imageProcessingConfiguration.bind(this._activeEffect);
  44636. // Log. depth
  44637. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44638. }
  44639. this._uniformBuffer.update();
  44640. this._afterBind(mesh, this._activeEffect);
  44641. };
  44642. /**
  44643. * Returns the animatable textures.
  44644. * @returns - Array of animatable textures.
  44645. */
  44646. PBRBaseMaterial.prototype.getAnimatables = function () {
  44647. var results = [];
  44648. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44649. results.push(this._albedoTexture);
  44650. }
  44651. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44652. results.push(this._ambientTexture);
  44653. }
  44654. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44655. results.push(this._opacityTexture);
  44656. }
  44657. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44658. results.push(this._reflectionTexture);
  44659. }
  44660. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44661. results.push(this._emissiveTexture);
  44662. }
  44663. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44664. results.push(this._metallicTexture);
  44665. }
  44666. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44667. results.push(this._reflectivityTexture);
  44668. }
  44669. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44670. results.push(this._bumpTexture);
  44671. }
  44672. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44673. results.push(this._lightmapTexture);
  44674. }
  44675. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44676. results.push(this._refractionTexture);
  44677. }
  44678. return results;
  44679. };
  44680. /**
  44681. * Returns the texture used for reflections.
  44682. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44683. */
  44684. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44685. if (this._reflectionTexture) {
  44686. return this._reflectionTexture;
  44687. }
  44688. return this.getScene().environmentTexture;
  44689. };
  44690. /**
  44691. * Returns the texture used for refraction or null if none is used.
  44692. * @returns - Refection texture if present. If no refraction texture and refraction
  44693. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44694. */
  44695. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44696. if (this._refractionTexture) {
  44697. return this._refractionTexture;
  44698. }
  44699. if (this._linkRefractionWithTransparency) {
  44700. return this.getScene().environmentTexture;
  44701. }
  44702. return null;
  44703. };
  44704. /**
  44705. * Disposes the resources of the material.
  44706. * @param forceDisposeEffect - Forces the disposal of effects.
  44707. * @param forceDisposeTextures - Forces the disposal of all textures.
  44708. */
  44709. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44710. if (forceDisposeTextures) {
  44711. if (this._albedoTexture) {
  44712. this._albedoTexture.dispose();
  44713. }
  44714. if (this._ambientTexture) {
  44715. this._ambientTexture.dispose();
  44716. }
  44717. if (this._opacityTexture) {
  44718. this._opacityTexture.dispose();
  44719. }
  44720. if (this._reflectionTexture) {
  44721. this._reflectionTexture.dispose();
  44722. }
  44723. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44724. this._environmentBRDFTexture.dispose();
  44725. }
  44726. if (this._emissiveTexture) {
  44727. this._emissiveTexture.dispose();
  44728. }
  44729. if (this._metallicTexture) {
  44730. this._metallicTexture.dispose();
  44731. }
  44732. if (this._reflectivityTexture) {
  44733. this._reflectivityTexture.dispose();
  44734. }
  44735. if (this._bumpTexture) {
  44736. this._bumpTexture.dispose();
  44737. }
  44738. if (this._lightmapTexture) {
  44739. this._lightmapTexture.dispose();
  44740. }
  44741. if (this._refractionTexture) {
  44742. this._refractionTexture.dispose();
  44743. }
  44744. }
  44745. this._renderTargets.dispose();
  44746. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44747. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44748. }
  44749. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44750. };
  44751. /**
  44752. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44753. */
  44754. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44755. /**
  44756. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44757. * to enhance interoperability with other engines.
  44758. */
  44759. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44760. /**
  44761. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44762. * to enhance interoperability with other materials.
  44763. */
  44764. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44765. /**
  44766. * Stores the reflectivity values based on metallic roughness workflow.
  44767. */
  44768. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44769. __decorate([
  44770. BABYLON.serializeAsImageProcessingConfiguration()
  44771. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44772. __decorate([
  44773. BABYLON.serialize()
  44774. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44775. __decorate([
  44776. BABYLON.serialize()
  44777. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44778. return PBRBaseMaterial;
  44779. }(BABYLON.PushMaterial));
  44780. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44781. })(BABYLON || (BABYLON = {}));
  44782. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44783. var BABYLON;
  44784. (function (BABYLON) {
  44785. /**
  44786. * The Physically based simple base material of BJS.
  44787. *
  44788. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44789. * It is used as the base class for both the specGloss and metalRough conventions.
  44790. */
  44791. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44792. __extends(PBRBaseSimpleMaterial, _super);
  44793. /**
  44794. * Instantiates a new PBRMaterial instance.
  44795. *
  44796. * @param name The material name
  44797. * @param scene The scene the material will be use in.
  44798. */
  44799. function PBRBaseSimpleMaterial(name, scene) {
  44800. var _this = _super.call(this, name, scene) || this;
  44801. /**
  44802. * Number of Simultaneous lights allowed on the material.
  44803. */
  44804. _this.maxSimultaneousLights = 4;
  44805. /**
  44806. * If sets to true, disables all the lights affecting the material.
  44807. */
  44808. _this.disableLighting = false;
  44809. /**
  44810. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44811. */
  44812. _this.invertNormalMapX = false;
  44813. /**
  44814. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44815. */
  44816. _this.invertNormalMapY = false;
  44817. /**
  44818. * Emissivie color used to self-illuminate the model.
  44819. */
  44820. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44821. /**
  44822. * Occlusion Channel Strenght.
  44823. */
  44824. _this.occlusionStrength = 1.0;
  44825. _this.useLightmapAsShadowmap = false;
  44826. _this._useAlphaFromAlbedoTexture = true;
  44827. _this._useAmbientInGrayScale = true;
  44828. return _this;
  44829. }
  44830. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44831. /**
  44832. * Gets the current double sided mode.
  44833. */
  44834. get: function () {
  44835. return this._twoSidedLighting;
  44836. },
  44837. /**
  44838. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44839. */
  44840. set: function (value) {
  44841. if (this._twoSidedLighting === value) {
  44842. return;
  44843. }
  44844. this._twoSidedLighting = value;
  44845. this.backFaceCulling = !value;
  44846. this._markAllSubMeshesAsTexturesDirty();
  44847. },
  44848. enumerable: true,
  44849. configurable: true
  44850. });
  44851. /**
  44852. * Return the active textures of the material.
  44853. */
  44854. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44855. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44856. if (this.environmentTexture) {
  44857. activeTextures.push(this.environmentTexture);
  44858. }
  44859. if (this.normalTexture) {
  44860. activeTextures.push(this.normalTexture);
  44861. }
  44862. if (this.emissiveTexture) {
  44863. activeTextures.push(this.emissiveTexture);
  44864. }
  44865. if (this.occlusionTexture) {
  44866. activeTextures.push(this.occlusionTexture);
  44867. }
  44868. if (this.lightmapTexture) {
  44869. activeTextures.push(this.lightmapTexture);
  44870. }
  44871. return activeTextures;
  44872. };
  44873. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44874. if (_super.prototype.hasTexture.call(this, texture)) {
  44875. return true;
  44876. }
  44877. if (this.lightmapTexture === texture) {
  44878. return true;
  44879. }
  44880. return false;
  44881. };
  44882. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44883. return "PBRBaseSimpleMaterial";
  44884. };
  44885. __decorate([
  44886. BABYLON.serialize(),
  44887. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44888. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44889. __decorate([
  44890. BABYLON.serialize(),
  44891. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44892. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44893. __decorate([
  44894. BABYLON.serializeAsTexture(),
  44895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44896. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44897. __decorate([
  44898. BABYLON.serialize(),
  44899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44900. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44901. __decorate([
  44902. BABYLON.serialize(),
  44903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44904. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44905. __decorate([
  44906. BABYLON.serializeAsTexture(),
  44907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44908. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44909. __decorate([
  44910. BABYLON.serializeAsColor3("emissive"),
  44911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44912. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44913. __decorate([
  44914. BABYLON.serializeAsTexture(),
  44915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44916. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44917. __decorate([
  44918. BABYLON.serialize(),
  44919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44920. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44921. __decorate([
  44922. BABYLON.serializeAsTexture(),
  44923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44924. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44925. __decorate([
  44926. BABYLON.serialize(),
  44927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44928. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44929. __decorate([
  44930. BABYLON.serialize()
  44931. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44932. __decorate([
  44933. BABYLON.serializeAsTexture(),
  44934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44935. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44936. __decorate([
  44937. BABYLON.serialize(),
  44938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44939. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44940. return PBRBaseSimpleMaterial;
  44941. }(BABYLON.PBRBaseMaterial));
  44942. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44943. })(BABYLON || (BABYLON = {}));
  44944. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44945. var BABYLON;
  44946. (function (BABYLON) {
  44947. /**
  44948. * The Physically based material of BJS.
  44949. *
  44950. * This offers the main features of a standard PBR material.
  44951. * For more information, please refer to the documentation :
  44952. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44953. */
  44954. var PBRMaterial = /** @class */ (function (_super) {
  44955. __extends(PBRMaterial, _super);
  44956. /**
  44957. * Instantiates a new PBRMaterial instance.
  44958. *
  44959. * @param name The material name
  44960. * @param scene The scene the material will be use in.
  44961. */
  44962. function PBRMaterial(name, scene) {
  44963. var _this = _super.call(this, name, scene) || this;
  44964. /**
  44965. * Intensity of the direct lights e.g. the four lights available in your scene.
  44966. * This impacts both the direct diffuse and specular highlights.
  44967. */
  44968. _this.directIntensity = 1.0;
  44969. /**
  44970. * Intensity of the emissive part of the material.
  44971. * This helps controlling the emissive effect without modifying the emissive color.
  44972. */
  44973. _this.emissiveIntensity = 1.0;
  44974. /**
  44975. * Intensity of the environment e.g. how much the environment will light the object
  44976. * either through harmonics for rough material or through the refelction for shiny ones.
  44977. */
  44978. _this.environmentIntensity = 1.0;
  44979. /**
  44980. * This is a special control allowing the reduction of the specular highlights coming from the
  44981. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44982. */
  44983. _this.specularIntensity = 1.0;
  44984. /**
  44985. * Debug Control allowing disabling the bump map on this material.
  44986. */
  44987. _this.disableBumpMap = false;
  44988. /**
  44989. * AKA Occlusion Texture Intensity in other nomenclature.
  44990. */
  44991. _this.ambientTextureStrength = 1.0;
  44992. /**
  44993. * The color of a material in ambient lighting.
  44994. */
  44995. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44996. /**
  44997. * AKA Diffuse Color in other nomenclature.
  44998. */
  44999. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45000. /**
  45001. * AKA Specular Color in other nomenclature.
  45002. */
  45003. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45004. /**
  45005. * The color reflected from the material.
  45006. */
  45007. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45008. /**
  45009. * The color emitted from the material.
  45010. */
  45011. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45012. /**
  45013. * AKA Glossiness in other nomenclature.
  45014. */
  45015. _this.microSurface = 1.0;
  45016. /**
  45017. * source material index of refraction (IOR)' / 'destination material IOR.
  45018. */
  45019. _this.indexOfRefraction = 0.66;
  45020. /**
  45021. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45022. */
  45023. _this.invertRefractionY = false;
  45024. /**
  45025. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45026. * Materials half opaque for instance using refraction could benefit from this control.
  45027. */
  45028. _this.linkRefractionWithTransparency = false;
  45029. _this.useLightmapAsShadowmap = false;
  45030. /**
  45031. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45032. */
  45033. _this.useAlphaFromAlbedoTexture = false;
  45034. /**
  45035. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45036. */
  45037. _this.forceAlphaTest = false;
  45038. /**
  45039. * Defines the alpha limits in alpha test mode.
  45040. */
  45041. _this.alphaCutOff = 0.4;
  45042. /**
  45043. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45044. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45045. */
  45046. _this.useSpecularOverAlpha = true;
  45047. /**
  45048. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45049. */
  45050. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45051. /**
  45052. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45053. */
  45054. _this.useRoughnessFromMetallicTextureAlpha = true;
  45055. /**
  45056. * Specifies if the metallic texture contains the roughness information in its green channel.
  45057. */
  45058. _this.useRoughnessFromMetallicTextureGreen = false;
  45059. /**
  45060. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45061. */
  45062. _this.useMetallnessFromMetallicTextureBlue = false;
  45063. /**
  45064. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45065. */
  45066. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45067. /**
  45068. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45069. */
  45070. _this.useAmbientInGrayScale = false;
  45071. /**
  45072. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45073. * The material will try to infer what glossiness each pixel should be.
  45074. */
  45075. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45076. /**
  45077. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45078. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45079. */
  45080. _this.useRadianceOverAlpha = true;
  45081. /**
  45082. * Allows using an object space normal map (instead of tangent space).
  45083. */
  45084. _this.useObjectSpaceNormalMap = false;
  45085. /**
  45086. * Allows using the bump map in parallax mode.
  45087. */
  45088. _this.useParallax = false;
  45089. /**
  45090. * Allows using the bump map in parallax occlusion mode.
  45091. */
  45092. _this.useParallaxOcclusion = false;
  45093. /**
  45094. * Controls the scale bias of the parallax mode.
  45095. */
  45096. _this.parallaxScaleBias = 0.05;
  45097. /**
  45098. * If sets to true, disables all the lights affecting the material.
  45099. */
  45100. _this.disableLighting = false;
  45101. /**
  45102. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45103. */
  45104. _this.forceIrradianceInFragment = false;
  45105. /**
  45106. * Number of Simultaneous lights allowed on the material.
  45107. */
  45108. _this.maxSimultaneousLights = 4;
  45109. /**
  45110. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45111. */
  45112. _this.invertNormalMapX = false;
  45113. /**
  45114. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45115. */
  45116. _this.invertNormalMapY = false;
  45117. /**
  45118. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45119. */
  45120. _this.twoSidedLighting = false;
  45121. /**
  45122. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45123. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45124. */
  45125. _this.useAlphaFresnel = false;
  45126. /**
  45127. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45128. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45129. */
  45130. _this.useLinearAlphaFresnel = false;
  45131. /**
  45132. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45133. * And/Or occlude the blended part.
  45134. */
  45135. _this.environmentBRDFTexture = null;
  45136. /**
  45137. * Force normal to face away from face.
  45138. */
  45139. _this.forceNormalForward = false;
  45140. /**
  45141. * Enables specular anti aliasing in the PBR shader.
  45142. * It will both interacts on the Geometry for analytical and IBL lighting.
  45143. * It also prefilter the roughness map based on the bump values.
  45144. */
  45145. _this.enableSpecularAntiAliasing = false;
  45146. /**
  45147. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45148. * makes the reflect vector face the model (under horizon).
  45149. */
  45150. _this.useHorizonOcclusion = true;
  45151. /**
  45152. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45153. * too much the area relying on ambient texture to define their ambient occlusion.
  45154. */
  45155. _this.useRadianceOcclusion = true;
  45156. /**
  45157. * If set to true, no lighting calculations will be applied.
  45158. */
  45159. _this.unlit = false;
  45160. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45161. return _this;
  45162. }
  45163. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45164. /**
  45165. * BJS is using an harcoded light falloff based on a manually sets up range.
  45166. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45167. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45168. */
  45169. get: function () {
  45170. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45171. },
  45172. /**
  45173. * BJS is using an harcoded light falloff based on a manually sets up range.
  45174. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45175. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45176. */
  45177. set: function (value) {
  45178. if (value !== this.usePhysicalLightFalloff) {
  45179. // Ensure the effect will be rebuilt.
  45180. this._markAllSubMeshesAsTexturesDirty();
  45181. if (value) {
  45182. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45183. }
  45184. else {
  45185. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45186. }
  45187. }
  45188. },
  45189. enumerable: true,
  45190. configurable: true
  45191. });
  45192. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45193. /**
  45194. * In order to support the falloff compatibility with gltf, a special mode has been added
  45195. * to reproduce the gltf light falloff.
  45196. */
  45197. get: function () {
  45198. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45199. },
  45200. /**
  45201. * In order to support the falloff compatibility with gltf, a special mode has been added
  45202. * to reproduce the gltf light falloff.
  45203. */
  45204. set: function (value) {
  45205. if (value !== this.useGLTFLightFalloff) {
  45206. // Ensure the effect will be rebuilt.
  45207. this._markAllSubMeshesAsTexturesDirty();
  45208. if (value) {
  45209. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45210. }
  45211. else {
  45212. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45213. }
  45214. }
  45215. },
  45216. enumerable: true,
  45217. configurable: true
  45218. });
  45219. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45220. /**
  45221. * Gets the image processing configuration used either in this material.
  45222. */
  45223. get: function () {
  45224. return this._imageProcessingConfiguration;
  45225. },
  45226. /**
  45227. * Sets the Default image processing configuration used either in the this material.
  45228. *
  45229. * If sets to null, the scene one is in use.
  45230. */
  45231. set: function (value) {
  45232. this._attachImageProcessingConfiguration(value);
  45233. // Ensure the effect will be rebuilt.
  45234. this._markAllSubMeshesAsTexturesDirty();
  45235. },
  45236. enumerable: true,
  45237. configurable: true
  45238. });
  45239. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45240. /**
  45241. * Gets wether the color curves effect is enabled.
  45242. */
  45243. get: function () {
  45244. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45245. },
  45246. /**
  45247. * Sets wether the color curves effect is enabled.
  45248. */
  45249. set: function (value) {
  45250. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45251. },
  45252. enumerable: true,
  45253. configurable: true
  45254. });
  45255. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45256. /**
  45257. * Gets wether the color grading effect is enabled.
  45258. */
  45259. get: function () {
  45260. return this.imageProcessingConfiguration.colorGradingEnabled;
  45261. },
  45262. /**
  45263. * Gets wether the color grading effect is enabled.
  45264. */
  45265. set: function (value) {
  45266. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45267. },
  45268. enumerable: true,
  45269. configurable: true
  45270. });
  45271. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45272. /**
  45273. * Gets wether tonemapping is enabled or not.
  45274. */
  45275. get: function () {
  45276. return this._imageProcessingConfiguration.toneMappingEnabled;
  45277. },
  45278. /**
  45279. * Sets wether tonemapping is enabled or not
  45280. */
  45281. set: function (value) {
  45282. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45283. },
  45284. enumerable: true,
  45285. configurable: true
  45286. });
  45287. ;
  45288. ;
  45289. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45290. /**
  45291. * The camera exposure used on this material.
  45292. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45293. * This corresponds to a photographic exposure.
  45294. */
  45295. get: function () {
  45296. return this._imageProcessingConfiguration.exposure;
  45297. },
  45298. /**
  45299. * The camera exposure used on this material.
  45300. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45301. * This corresponds to a photographic exposure.
  45302. */
  45303. set: function (value) {
  45304. this._imageProcessingConfiguration.exposure = value;
  45305. },
  45306. enumerable: true,
  45307. configurable: true
  45308. });
  45309. ;
  45310. ;
  45311. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45312. /**
  45313. * Gets The camera contrast used on this material.
  45314. */
  45315. get: function () {
  45316. return this._imageProcessingConfiguration.contrast;
  45317. },
  45318. /**
  45319. * Sets The camera contrast used on this material.
  45320. */
  45321. set: function (value) {
  45322. this._imageProcessingConfiguration.contrast = value;
  45323. },
  45324. enumerable: true,
  45325. configurable: true
  45326. });
  45327. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45328. /**
  45329. * Gets the Color Grading 2D Lookup Texture.
  45330. */
  45331. get: function () {
  45332. return this._imageProcessingConfiguration.colorGradingTexture;
  45333. },
  45334. /**
  45335. * Sets the Color Grading 2D Lookup Texture.
  45336. */
  45337. set: function (value) {
  45338. this._imageProcessingConfiguration.colorGradingTexture = value;
  45339. },
  45340. enumerable: true,
  45341. configurable: true
  45342. });
  45343. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45344. /**
  45345. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45346. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45347. * 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;
  45348. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45349. */
  45350. get: function () {
  45351. return this._imageProcessingConfiguration.colorCurves;
  45352. },
  45353. /**
  45354. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45355. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45356. * 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;
  45357. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45358. */
  45359. set: function (value) {
  45360. this._imageProcessingConfiguration.colorCurves = value;
  45361. },
  45362. enumerable: true,
  45363. configurable: true
  45364. });
  45365. /**
  45366. * Returns the name of this material class.
  45367. */
  45368. PBRMaterial.prototype.getClassName = function () {
  45369. return "PBRMaterial";
  45370. };
  45371. /**
  45372. * Returns an array of the actively used textures.
  45373. * @returns - Array of BaseTextures
  45374. */
  45375. PBRMaterial.prototype.getActiveTextures = function () {
  45376. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45377. if (this._albedoTexture) {
  45378. activeTextures.push(this._albedoTexture);
  45379. }
  45380. if (this._ambientTexture) {
  45381. activeTextures.push(this._ambientTexture);
  45382. }
  45383. if (this._opacityTexture) {
  45384. activeTextures.push(this._opacityTexture);
  45385. }
  45386. if (this._reflectionTexture) {
  45387. activeTextures.push(this._reflectionTexture);
  45388. }
  45389. if (this._emissiveTexture) {
  45390. activeTextures.push(this._emissiveTexture);
  45391. }
  45392. if (this._reflectivityTexture) {
  45393. activeTextures.push(this._reflectivityTexture);
  45394. }
  45395. if (this._metallicTexture) {
  45396. activeTextures.push(this._metallicTexture);
  45397. }
  45398. if (this._microSurfaceTexture) {
  45399. activeTextures.push(this._microSurfaceTexture);
  45400. }
  45401. if (this._bumpTexture) {
  45402. activeTextures.push(this._bumpTexture);
  45403. }
  45404. if (this._lightmapTexture) {
  45405. activeTextures.push(this._lightmapTexture);
  45406. }
  45407. if (this._refractionTexture) {
  45408. activeTextures.push(this._refractionTexture);
  45409. }
  45410. return activeTextures;
  45411. };
  45412. /**
  45413. * Checks to see if a texture is used in the material.
  45414. * @param texture - Base texture to use.
  45415. * @returns - Boolean specifying if a texture is used in the material.
  45416. */
  45417. PBRMaterial.prototype.hasTexture = function (texture) {
  45418. if (_super.prototype.hasTexture.call(this, texture)) {
  45419. return true;
  45420. }
  45421. if (this._albedoTexture === texture) {
  45422. return true;
  45423. }
  45424. if (this._ambientTexture === texture) {
  45425. return true;
  45426. }
  45427. if (this._opacityTexture === texture) {
  45428. return true;
  45429. }
  45430. if (this._reflectionTexture === texture) {
  45431. return true;
  45432. }
  45433. if (this._reflectivityTexture === texture) {
  45434. return true;
  45435. }
  45436. if (this._metallicTexture === texture) {
  45437. return true;
  45438. }
  45439. if (this._microSurfaceTexture === texture) {
  45440. return true;
  45441. }
  45442. if (this._bumpTexture === texture) {
  45443. return true;
  45444. }
  45445. if (this._lightmapTexture === texture) {
  45446. return true;
  45447. }
  45448. if (this._refractionTexture === texture) {
  45449. return true;
  45450. }
  45451. return false;
  45452. };
  45453. /**
  45454. * Makes a duplicate of the current material.
  45455. * @param name - name to use for the new material.
  45456. */
  45457. PBRMaterial.prototype.clone = function (name) {
  45458. var _this = this;
  45459. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45460. clone.id = name;
  45461. clone.name = name;
  45462. return clone;
  45463. };
  45464. /**
  45465. * Serializes this PBR Material.
  45466. * @returns - An object with the serialized material.
  45467. */
  45468. PBRMaterial.prototype.serialize = function () {
  45469. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45470. serializationObject.customType = "BABYLON.PBRMaterial";
  45471. return serializationObject;
  45472. };
  45473. // Statics
  45474. /**
  45475. * Parses a PBR Material from a serialized object.
  45476. * @param source - Serialized object.
  45477. * @param scene - BJS scene instance.
  45478. * @param rootUrl - url for the scene object
  45479. * @returns - PBRMaterial
  45480. */
  45481. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45482. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45483. };
  45484. /**
  45485. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45486. */
  45487. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45488. /**
  45489. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45490. */
  45491. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45492. /**
  45493. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45494. */
  45495. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45496. /**
  45497. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45498. * They are also discarded below the alpha cutoff threshold to improve performances.
  45499. */
  45500. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45501. __decorate([
  45502. BABYLON.serialize(),
  45503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45504. ], PBRMaterial.prototype, "directIntensity", void 0);
  45505. __decorate([
  45506. BABYLON.serialize(),
  45507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45508. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45509. __decorate([
  45510. BABYLON.serialize(),
  45511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45512. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45513. __decorate([
  45514. BABYLON.serialize(),
  45515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45516. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45517. __decorate([
  45518. BABYLON.serialize(),
  45519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45520. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45521. __decorate([
  45522. BABYLON.serializeAsTexture(),
  45523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45524. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45525. __decorate([
  45526. BABYLON.serializeAsTexture(),
  45527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45528. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45529. __decorate([
  45530. BABYLON.serialize(),
  45531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45532. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45533. __decorate([
  45534. BABYLON.serializeAsTexture(),
  45535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45536. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45537. __decorate([
  45538. BABYLON.serializeAsTexture(),
  45539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45540. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45541. __decorate([
  45542. BABYLON.serializeAsTexture(),
  45543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45544. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45545. __decorate([
  45546. BABYLON.serializeAsTexture(),
  45547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45548. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45549. __decorate([
  45550. BABYLON.serializeAsTexture(),
  45551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45552. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45553. __decorate([
  45554. BABYLON.serialize(),
  45555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45556. ], PBRMaterial.prototype, "metallic", void 0);
  45557. __decorate([
  45558. BABYLON.serialize(),
  45559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45560. ], PBRMaterial.prototype, "roughness", void 0);
  45561. __decorate([
  45562. BABYLON.serializeAsTexture(),
  45563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45564. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45565. __decorate([
  45566. BABYLON.serializeAsTexture(),
  45567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45568. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45569. __decorate([
  45570. BABYLON.serializeAsTexture(),
  45571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45572. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45573. __decorate([
  45574. BABYLON.serializeAsTexture(),
  45575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45576. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45577. __decorate([
  45578. BABYLON.serializeAsColor3("ambient"),
  45579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45580. ], PBRMaterial.prototype, "ambientColor", void 0);
  45581. __decorate([
  45582. BABYLON.serializeAsColor3("albedo"),
  45583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45584. ], PBRMaterial.prototype, "albedoColor", void 0);
  45585. __decorate([
  45586. BABYLON.serializeAsColor3("reflectivity"),
  45587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45588. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45589. __decorate([
  45590. BABYLON.serializeAsColor3("reflection"),
  45591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45592. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45593. __decorate([
  45594. BABYLON.serializeAsColor3("emissive"),
  45595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45596. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45597. __decorate([
  45598. BABYLON.serialize(),
  45599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45600. ], PBRMaterial.prototype, "microSurface", void 0);
  45601. __decorate([
  45602. BABYLON.serialize(),
  45603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45604. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45605. __decorate([
  45606. BABYLON.serialize(),
  45607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45608. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45609. __decorate([
  45610. BABYLON.serialize(),
  45611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45612. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45613. __decorate([
  45614. BABYLON.serialize(),
  45615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45616. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45617. __decorate([
  45618. BABYLON.serialize(),
  45619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45620. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45621. __decorate([
  45622. BABYLON.serialize(),
  45623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45624. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45625. __decorate([
  45626. BABYLON.serialize(),
  45627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45628. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45629. __decorate([
  45630. BABYLON.serialize(),
  45631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45632. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45633. __decorate([
  45634. BABYLON.serialize(),
  45635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45636. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45637. __decorate([
  45638. BABYLON.serialize(),
  45639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45640. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45641. __decorate([
  45642. BABYLON.serialize(),
  45643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45644. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45645. __decorate([
  45646. BABYLON.serialize(),
  45647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45648. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45649. __decorate([
  45650. BABYLON.serialize(),
  45651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45652. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45653. __decorate([
  45654. BABYLON.serialize(),
  45655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45656. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45657. __decorate([
  45658. BABYLON.serialize(),
  45659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45660. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45661. __decorate([
  45662. BABYLON.serialize()
  45663. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45664. __decorate([
  45665. BABYLON.serialize()
  45666. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45667. __decorate([
  45668. BABYLON.serialize(),
  45669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45670. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45671. __decorate([
  45672. BABYLON.serialize(),
  45673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45674. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45675. __decorate([
  45676. BABYLON.serialize(),
  45677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45678. ], PBRMaterial.prototype, "useParallax", void 0);
  45679. __decorate([
  45680. BABYLON.serialize(),
  45681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45682. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45683. __decorate([
  45684. BABYLON.serialize(),
  45685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45686. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45687. __decorate([
  45688. BABYLON.serialize(),
  45689. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45690. ], PBRMaterial.prototype, "disableLighting", void 0);
  45691. __decorate([
  45692. BABYLON.serialize(),
  45693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45694. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45695. __decorate([
  45696. BABYLON.serialize(),
  45697. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45698. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45699. __decorate([
  45700. BABYLON.serialize(),
  45701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45702. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45703. __decorate([
  45704. BABYLON.serialize(),
  45705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45706. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45707. __decorate([
  45708. BABYLON.serialize(),
  45709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45710. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45711. __decorate([
  45712. BABYLON.serialize(),
  45713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45714. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45715. __decorate([
  45716. BABYLON.serialize(),
  45717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45718. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45719. __decorate([
  45720. BABYLON.serializeAsTexture(),
  45721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45722. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45723. __decorate([
  45724. BABYLON.serialize(),
  45725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45726. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45727. __decorate([
  45728. BABYLON.serialize(),
  45729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45730. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45731. __decorate([
  45732. BABYLON.serialize(),
  45733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45734. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45735. __decorate([
  45736. BABYLON.serialize(),
  45737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45738. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45739. __decorate([
  45740. BABYLON.serialize(),
  45741. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45742. ], PBRMaterial.prototype, "unlit", void 0);
  45743. return PBRMaterial;
  45744. }(BABYLON.PBRBaseMaterial));
  45745. BABYLON.PBRMaterial = PBRMaterial;
  45746. })(BABYLON || (BABYLON = {}));
  45747. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45748. var BABYLON;
  45749. (function (BABYLON) {
  45750. /**
  45751. * The PBR material of BJS following the metal roughness convention.
  45752. *
  45753. * This fits to the PBR convention in the GLTF definition:
  45754. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45755. */
  45756. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45757. __extends(PBRMetallicRoughnessMaterial, _super);
  45758. /**
  45759. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45760. *
  45761. * @param name The material name
  45762. * @param scene The scene the material will be use in.
  45763. */
  45764. function PBRMetallicRoughnessMaterial(name, scene) {
  45765. var _this = _super.call(this, name, scene) || this;
  45766. _this._useRoughnessFromMetallicTextureAlpha = false;
  45767. _this._useRoughnessFromMetallicTextureGreen = true;
  45768. _this._useMetallnessFromMetallicTextureBlue = true;
  45769. _this.metallic = 1.0;
  45770. _this.roughness = 1.0;
  45771. return _this;
  45772. }
  45773. /**
  45774. * Return the currrent class name of the material.
  45775. */
  45776. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45777. return "PBRMetallicRoughnessMaterial";
  45778. };
  45779. /**
  45780. * Return the active textures of the material.
  45781. */
  45782. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45783. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45784. if (this.baseTexture) {
  45785. activeTextures.push(this.baseTexture);
  45786. }
  45787. if (this.metallicRoughnessTexture) {
  45788. activeTextures.push(this.metallicRoughnessTexture);
  45789. }
  45790. return activeTextures;
  45791. };
  45792. /**
  45793. * Checks to see if a texture is used in the material.
  45794. * @param texture - Base texture to use.
  45795. * @returns - Boolean specifying if a texture is used in the material.
  45796. */
  45797. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45798. if (_super.prototype.hasTexture.call(this, texture)) {
  45799. return true;
  45800. }
  45801. if (this.baseTexture === texture) {
  45802. return true;
  45803. }
  45804. if (this.metallicRoughnessTexture === texture) {
  45805. return true;
  45806. }
  45807. return false;
  45808. };
  45809. /**
  45810. * Makes a duplicate of the current material.
  45811. * @param name - name to use for the new material.
  45812. */
  45813. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45814. var _this = this;
  45815. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45816. clone.id = name;
  45817. clone.name = name;
  45818. return clone;
  45819. };
  45820. /**
  45821. * Serialize the material to a parsable JSON object.
  45822. */
  45823. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45824. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45825. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45826. return serializationObject;
  45827. };
  45828. /**
  45829. * Parses a JSON object correponding to the serialize function.
  45830. */
  45831. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45832. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45833. };
  45834. __decorate([
  45835. BABYLON.serializeAsColor3(),
  45836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45837. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45838. __decorate([
  45839. BABYLON.serializeAsTexture(),
  45840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45841. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45842. __decorate([
  45843. BABYLON.serialize(),
  45844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45845. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45846. __decorate([
  45847. BABYLON.serialize(),
  45848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45849. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45850. __decorate([
  45851. BABYLON.serializeAsTexture(),
  45852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45853. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45854. return PBRMetallicRoughnessMaterial;
  45855. }(BABYLON.PBRBaseSimpleMaterial));
  45856. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45857. })(BABYLON || (BABYLON = {}));
  45858. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45859. var BABYLON;
  45860. (function (BABYLON) {
  45861. /**
  45862. * The PBR material of BJS following the specular glossiness convention.
  45863. *
  45864. * This fits to the PBR convention in the GLTF definition:
  45865. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45866. */
  45867. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45868. __extends(PBRSpecularGlossinessMaterial, _super);
  45869. /**
  45870. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45871. *
  45872. * @param name The material name
  45873. * @param scene The scene the material will be use in.
  45874. */
  45875. function PBRSpecularGlossinessMaterial(name, scene) {
  45876. var _this = _super.call(this, name, scene) || this;
  45877. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45878. return _this;
  45879. }
  45880. /**
  45881. * Return the currrent class name of the material.
  45882. */
  45883. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45884. return "PBRSpecularGlossinessMaterial";
  45885. };
  45886. /**
  45887. * Return the active textures of the material.
  45888. */
  45889. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45890. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45891. if (this.diffuseTexture) {
  45892. activeTextures.push(this.diffuseTexture);
  45893. }
  45894. if (this.specularGlossinessTexture) {
  45895. activeTextures.push(this.specularGlossinessTexture);
  45896. }
  45897. return activeTextures;
  45898. };
  45899. /**
  45900. * Checks to see if a texture is used in the material.
  45901. * @param texture - Base texture to use.
  45902. * @returns - Boolean specifying if a texture is used in the material.
  45903. */
  45904. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45905. if (_super.prototype.hasTexture.call(this, texture)) {
  45906. return true;
  45907. }
  45908. if (this.diffuseTexture === texture) {
  45909. return true;
  45910. }
  45911. if (this.specularGlossinessTexture === texture) {
  45912. return true;
  45913. }
  45914. return false;
  45915. };
  45916. /**
  45917. * Makes a duplicate of the current material.
  45918. * @param name - name to use for the new material.
  45919. */
  45920. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45921. var _this = this;
  45922. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45923. clone.id = name;
  45924. clone.name = name;
  45925. return clone;
  45926. };
  45927. /**
  45928. * Serialize the material to a parsable JSON object.
  45929. */
  45930. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45931. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45932. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45933. return serializationObject;
  45934. };
  45935. /**
  45936. * Parses a JSON object correponding to the serialize function.
  45937. */
  45938. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45939. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45940. };
  45941. __decorate([
  45942. BABYLON.serializeAsColor3("diffuse"),
  45943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45944. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45945. __decorate([
  45946. BABYLON.serializeAsTexture(),
  45947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45948. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45949. __decorate([
  45950. BABYLON.serializeAsColor3("specular"),
  45951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45952. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45953. __decorate([
  45954. BABYLON.serialize(),
  45955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45956. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45957. __decorate([
  45958. BABYLON.serializeAsTexture(),
  45959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45960. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45961. return PBRSpecularGlossinessMaterial;
  45962. }(BABYLON.PBRBaseSimpleMaterial));
  45963. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45964. })(BABYLON || (BABYLON = {}));
  45965. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45966. var BABYLON;
  45967. (function (BABYLON) {
  45968. BABYLON.CameraInputTypes = {};
  45969. var CameraInputsManager = /** @class */ (function () {
  45970. function CameraInputsManager(camera) {
  45971. this.attached = {};
  45972. this.camera = camera;
  45973. this.checkInputs = function () { };
  45974. }
  45975. /**
  45976. * Add an input method to a camera
  45977. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45978. * @param input camera input method
  45979. */
  45980. CameraInputsManager.prototype.add = function (input) {
  45981. var type = input.getSimpleName();
  45982. if (this.attached[type]) {
  45983. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45984. return;
  45985. }
  45986. this.attached[type] = input;
  45987. input.camera = this.camera;
  45988. //for checkInputs, we are dynamically creating a function
  45989. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45990. if (input.checkInputs) {
  45991. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45992. }
  45993. if (this.attachedElement) {
  45994. input.attachControl(this.attachedElement);
  45995. }
  45996. };
  45997. /**
  45998. * Remove a specific input method from a camera
  45999. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46000. * @param inputToRemove camera input method
  46001. */
  46002. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46003. for (var cam in this.attached) {
  46004. var input = this.attached[cam];
  46005. if (input === inputToRemove) {
  46006. input.detachControl(this.attachedElement);
  46007. input.camera = null;
  46008. delete this.attached[cam];
  46009. this.rebuildInputCheck();
  46010. }
  46011. }
  46012. };
  46013. CameraInputsManager.prototype.removeByType = function (inputType) {
  46014. for (var cam in this.attached) {
  46015. var input = this.attached[cam];
  46016. if (input.getClassName() === inputType) {
  46017. input.detachControl(this.attachedElement);
  46018. input.camera = null;
  46019. delete this.attached[cam];
  46020. this.rebuildInputCheck();
  46021. }
  46022. }
  46023. };
  46024. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46025. var current = this.checkInputs;
  46026. return function () {
  46027. current();
  46028. fn();
  46029. };
  46030. };
  46031. CameraInputsManager.prototype.attachInput = function (input) {
  46032. if (this.attachedElement) {
  46033. input.attachControl(this.attachedElement, this.noPreventDefault);
  46034. }
  46035. };
  46036. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46037. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46038. if (this.attachedElement) {
  46039. return;
  46040. }
  46041. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46042. this.attachedElement = element;
  46043. this.noPreventDefault = noPreventDefault;
  46044. for (var cam in this.attached) {
  46045. this.attached[cam].attachControl(element, noPreventDefault);
  46046. }
  46047. };
  46048. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46049. if (disconnect === void 0) { disconnect = false; }
  46050. if (this.attachedElement !== element) {
  46051. return;
  46052. }
  46053. for (var cam in this.attached) {
  46054. this.attached[cam].detachControl(element);
  46055. if (disconnect) {
  46056. this.attached[cam].camera = null;
  46057. }
  46058. }
  46059. this.attachedElement = null;
  46060. };
  46061. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46062. this.checkInputs = function () { };
  46063. for (var cam in this.attached) {
  46064. var input = this.attached[cam];
  46065. if (input.checkInputs) {
  46066. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46067. }
  46068. }
  46069. };
  46070. /**
  46071. * Remove all attached input methods from a camera
  46072. */
  46073. CameraInputsManager.prototype.clear = function () {
  46074. if (this.attachedElement) {
  46075. this.detachElement(this.attachedElement, true);
  46076. }
  46077. this.attached = {};
  46078. this.attachedElement = null;
  46079. this.checkInputs = function () { };
  46080. };
  46081. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46082. var inputs = {};
  46083. for (var cam in this.attached) {
  46084. var input = this.attached[cam];
  46085. var res = BABYLON.SerializationHelper.Serialize(input);
  46086. inputs[input.getClassName()] = res;
  46087. }
  46088. serializedCamera.inputsmgr = inputs;
  46089. };
  46090. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46091. var parsedInputs = parsedCamera.inputsmgr;
  46092. if (parsedInputs) {
  46093. this.clear();
  46094. for (var n in parsedInputs) {
  46095. var construct = BABYLON.CameraInputTypes[n];
  46096. if (construct) {
  46097. var parsedinput = parsedInputs[n];
  46098. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46099. this.add(input);
  46100. }
  46101. }
  46102. }
  46103. else {
  46104. //2016-03-08 this part is for managing backward compatibility
  46105. for (var n in this.attached) {
  46106. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46107. if (construct) {
  46108. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46109. this.remove(this.attached[n]);
  46110. this.add(input);
  46111. }
  46112. }
  46113. }
  46114. };
  46115. return CameraInputsManager;
  46116. }());
  46117. BABYLON.CameraInputsManager = CameraInputsManager;
  46118. })(BABYLON || (BABYLON = {}));
  46119. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46120. var BABYLON;
  46121. (function (BABYLON) {
  46122. var TargetCamera = /** @class */ (function (_super) {
  46123. __extends(TargetCamera, _super);
  46124. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46125. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46126. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46127. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46128. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46129. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46130. _this.speed = 2.0;
  46131. _this.noRotationConstraint = false;
  46132. _this.lockedTarget = null;
  46133. _this._currentTarget = BABYLON.Vector3.Zero();
  46134. _this._viewMatrix = BABYLON.Matrix.Zero();
  46135. _this._camMatrix = BABYLON.Matrix.Zero();
  46136. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46137. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46138. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46139. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46140. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46141. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46142. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46143. return _this;
  46144. }
  46145. TargetCamera.prototype.getFrontPosition = function (distance) {
  46146. this.getWorldMatrix();
  46147. var direction = this.getTarget().subtract(this.position);
  46148. direction.normalize();
  46149. direction.scaleInPlace(distance);
  46150. return this.globalPosition.add(direction);
  46151. };
  46152. TargetCamera.prototype._getLockedTargetPosition = function () {
  46153. if (!this.lockedTarget) {
  46154. return null;
  46155. }
  46156. if (this.lockedTarget.absolutePosition) {
  46157. this.lockedTarget.computeWorldMatrix();
  46158. }
  46159. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46160. };
  46161. TargetCamera.prototype.storeState = function () {
  46162. this._storedPosition = this.position.clone();
  46163. this._storedRotation = this.rotation.clone();
  46164. if (this.rotationQuaternion) {
  46165. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46166. }
  46167. return _super.prototype.storeState.call(this);
  46168. };
  46169. /**
  46170. * Restored camera state. You must call storeState() first
  46171. */
  46172. TargetCamera.prototype._restoreStateValues = function () {
  46173. if (!_super.prototype._restoreStateValues.call(this)) {
  46174. return false;
  46175. }
  46176. this.position = this._storedPosition.clone();
  46177. this.rotation = this._storedRotation.clone();
  46178. if (this.rotationQuaternion) {
  46179. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46180. }
  46181. this.cameraDirection.copyFromFloats(0, 0, 0);
  46182. this.cameraRotation.copyFromFloats(0, 0);
  46183. return true;
  46184. };
  46185. // Cache
  46186. TargetCamera.prototype._initCache = function () {
  46187. _super.prototype._initCache.call(this);
  46188. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46189. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46190. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46191. };
  46192. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46193. if (!ignoreParentClass) {
  46194. _super.prototype._updateCache.call(this);
  46195. }
  46196. var lockedTargetPosition = this._getLockedTargetPosition();
  46197. if (!lockedTargetPosition) {
  46198. this._cache.lockedTarget = null;
  46199. }
  46200. else {
  46201. if (!this._cache.lockedTarget) {
  46202. this._cache.lockedTarget = lockedTargetPosition.clone();
  46203. }
  46204. else {
  46205. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46206. }
  46207. }
  46208. this._cache.rotation.copyFrom(this.rotation);
  46209. if (this.rotationQuaternion)
  46210. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46211. };
  46212. // Synchronized
  46213. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46214. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46215. return false;
  46216. }
  46217. var lockedTargetPosition = this._getLockedTargetPosition();
  46218. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46219. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46220. };
  46221. // Methods
  46222. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46223. var engine = this.getEngine();
  46224. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46225. };
  46226. // Target
  46227. TargetCamera.prototype.setTarget = function (target) {
  46228. this.upVector.normalize();
  46229. if (this.position.z === target.z) {
  46230. this.position.z += BABYLON.Epsilon;
  46231. }
  46232. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46233. this._camMatrix.invert();
  46234. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46235. var vDir = target.subtract(this.position);
  46236. if (vDir.x >= 0.0) {
  46237. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46238. }
  46239. else {
  46240. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46241. }
  46242. this.rotation.z = 0;
  46243. if (isNaN(this.rotation.x)) {
  46244. this.rotation.x = 0;
  46245. }
  46246. if (isNaN(this.rotation.y)) {
  46247. this.rotation.y = 0;
  46248. }
  46249. if (isNaN(this.rotation.z)) {
  46250. this.rotation.z = 0;
  46251. }
  46252. if (this.rotationQuaternion) {
  46253. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46254. }
  46255. };
  46256. /**
  46257. * Return the current target position of the camera. This value is expressed in local space.
  46258. */
  46259. TargetCamera.prototype.getTarget = function () {
  46260. return this._currentTarget;
  46261. };
  46262. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46263. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46264. };
  46265. TargetCamera.prototype._updatePosition = function () {
  46266. if (this.parent) {
  46267. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46268. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46269. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46270. return;
  46271. }
  46272. this.position.addInPlace(this.cameraDirection);
  46273. };
  46274. TargetCamera.prototype._checkInputs = function () {
  46275. var needToMove = this._decideIfNeedsToMove();
  46276. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46277. // Move
  46278. if (needToMove) {
  46279. this._updatePosition();
  46280. }
  46281. // Rotate
  46282. if (needToRotate) {
  46283. this.rotation.x += this.cameraRotation.x;
  46284. this.rotation.y += this.cameraRotation.y;
  46285. //rotate, if quaternion is set and rotation was used
  46286. if (this.rotationQuaternion) {
  46287. var len = this.rotation.lengthSquared();
  46288. if (len) {
  46289. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46290. }
  46291. }
  46292. if (!this.noRotationConstraint) {
  46293. var limit = (Math.PI / 2) * 0.95;
  46294. if (this.rotation.x > limit)
  46295. this.rotation.x = limit;
  46296. if (this.rotation.x < -limit)
  46297. this.rotation.x = -limit;
  46298. }
  46299. }
  46300. // Inertia
  46301. if (needToMove) {
  46302. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46303. this.cameraDirection.x = 0;
  46304. }
  46305. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46306. this.cameraDirection.y = 0;
  46307. }
  46308. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46309. this.cameraDirection.z = 0;
  46310. }
  46311. this.cameraDirection.scaleInPlace(this.inertia);
  46312. }
  46313. if (needToRotate) {
  46314. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46315. this.cameraRotation.x = 0;
  46316. }
  46317. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46318. this.cameraRotation.y = 0;
  46319. }
  46320. this.cameraRotation.scaleInPlace(this.inertia);
  46321. }
  46322. _super.prototype._checkInputs.call(this);
  46323. };
  46324. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46325. if (this.rotationQuaternion) {
  46326. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46327. }
  46328. else {
  46329. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46330. }
  46331. //update the up vector!
  46332. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46333. };
  46334. TargetCamera.prototype._getViewMatrix = function () {
  46335. if (this.lockedTarget) {
  46336. this.setTarget(this._getLockedTargetPosition());
  46337. }
  46338. // Compute
  46339. this._updateCameraRotationMatrix();
  46340. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46341. // Computing target and final matrix
  46342. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46343. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46344. return this._viewMatrix;
  46345. };
  46346. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46347. if (this.parent) {
  46348. var parentWorldMatrix = this.parent.getWorldMatrix();
  46349. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46350. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46351. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46352. this._markSyncedWithParent();
  46353. }
  46354. else {
  46355. this._globalPosition.copyFrom(position);
  46356. this._globalCurrentTarget.copyFrom(target);
  46357. this._globalCurrentUpVector.copyFrom(up);
  46358. }
  46359. if (this.getScene().useRightHandedSystem) {
  46360. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46361. }
  46362. else {
  46363. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46364. }
  46365. };
  46366. /**
  46367. * @override
  46368. * Override Camera.createRigCamera
  46369. */
  46370. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46371. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46372. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46373. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46374. if (!this.rotationQuaternion) {
  46375. this.rotationQuaternion = new BABYLON.Quaternion();
  46376. }
  46377. rigCamera._cameraRigParams = {};
  46378. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46379. }
  46380. return rigCamera;
  46381. }
  46382. return null;
  46383. };
  46384. /**
  46385. * @override
  46386. * Override Camera._updateRigCameras
  46387. */
  46388. TargetCamera.prototype._updateRigCameras = function () {
  46389. var camLeft = this._rigCameras[0];
  46390. var camRight = this._rigCameras[1];
  46391. switch (this.cameraRigMode) {
  46392. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46393. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46394. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46395. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46396. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46397. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46398. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46399. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46400. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46401. camLeft.setTarget(this.getTarget());
  46402. camRight.setTarget(this.getTarget());
  46403. break;
  46404. case BABYLON.Camera.RIG_MODE_VR:
  46405. if (camLeft.rotationQuaternion) {
  46406. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46407. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46408. }
  46409. else {
  46410. camLeft.rotation.copyFrom(this.rotation);
  46411. camRight.rotation.copyFrom(this.rotation);
  46412. }
  46413. camLeft.position.copyFrom(this.position);
  46414. camRight.position.copyFrom(this.position);
  46415. break;
  46416. }
  46417. _super.prototype._updateRigCameras.call(this);
  46418. };
  46419. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46420. if (!this._rigCamTransformMatrix) {
  46421. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46422. }
  46423. var target = this.getTarget();
  46424. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46425. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46426. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46427. };
  46428. TargetCamera.prototype.getClassName = function () {
  46429. return "TargetCamera";
  46430. };
  46431. __decorate([
  46432. BABYLON.serializeAsVector3()
  46433. ], TargetCamera.prototype, "rotation", void 0);
  46434. __decorate([
  46435. BABYLON.serialize()
  46436. ], TargetCamera.prototype, "speed", void 0);
  46437. __decorate([
  46438. BABYLON.serializeAsMeshReference("lockedTargetId")
  46439. ], TargetCamera.prototype, "lockedTarget", void 0);
  46440. return TargetCamera;
  46441. }(BABYLON.Camera));
  46442. BABYLON.TargetCamera = TargetCamera;
  46443. })(BABYLON || (BABYLON = {}));
  46444. //# sourceMappingURL=babylon.targetCamera.js.map
  46445. var BABYLON;
  46446. (function (BABYLON) {
  46447. var FreeCameraMouseInput = /** @class */ (function () {
  46448. function FreeCameraMouseInput(touchEnabled) {
  46449. if (touchEnabled === void 0) { touchEnabled = true; }
  46450. this.touchEnabled = touchEnabled;
  46451. this.buttons = [0, 1, 2];
  46452. this.angularSensibility = 2000.0;
  46453. this.previousPosition = null;
  46454. }
  46455. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46456. var _this = this;
  46457. var engine = this.camera.getEngine();
  46458. if (!this._pointerInput) {
  46459. this._pointerInput = function (p, s) {
  46460. var evt = p.event;
  46461. if (engine.isInVRExclusivePointerMode) {
  46462. return;
  46463. }
  46464. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46465. return;
  46466. }
  46467. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46468. return;
  46469. }
  46470. var srcElement = (evt.srcElement || evt.target);
  46471. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46472. try {
  46473. srcElement.setPointerCapture(evt.pointerId);
  46474. }
  46475. catch (e) {
  46476. //Nothing to do with the error. Execution will continue.
  46477. }
  46478. _this.previousPosition = {
  46479. x: evt.clientX,
  46480. y: evt.clientY
  46481. };
  46482. if (!noPreventDefault) {
  46483. evt.preventDefault();
  46484. element.focus();
  46485. }
  46486. }
  46487. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46488. try {
  46489. srcElement.releasePointerCapture(evt.pointerId);
  46490. }
  46491. catch (e) {
  46492. //Nothing to do with the error.
  46493. }
  46494. _this.previousPosition = null;
  46495. if (!noPreventDefault) {
  46496. evt.preventDefault();
  46497. }
  46498. }
  46499. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46500. if (!_this.previousPosition || engine.isPointerLock) {
  46501. return;
  46502. }
  46503. var offsetX = evt.clientX - _this.previousPosition.x;
  46504. if (_this.camera.getScene().useRightHandedSystem)
  46505. offsetX *= -1;
  46506. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46507. offsetX *= -1;
  46508. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46509. var offsetY = evt.clientY - _this.previousPosition.y;
  46510. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46511. _this.previousPosition = {
  46512. x: evt.clientX,
  46513. y: evt.clientY
  46514. };
  46515. if (!noPreventDefault) {
  46516. evt.preventDefault();
  46517. }
  46518. }
  46519. };
  46520. }
  46521. this._onMouseMove = function (evt) {
  46522. if (!engine.isPointerLock) {
  46523. return;
  46524. }
  46525. if (engine.isInVRExclusivePointerMode) {
  46526. return;
  46527. }
  46528. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46529. if (_this.camera.getScene().useRightHandedSystem)
  46530. offsetX *= -1;
  46531. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46532. offsetX *= -1;
  46533. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46534. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46535. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46536. _this.previousPosition = null;
  46537. if (!noPreventDefault) {
  46538. evt.preventDefault();
  46539. }
  46540. };
  46541. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46542. element.addEventListener("mousemove", this._onMouseMove, false);
  46543. };
  46544. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46545. if (this._observer && element) {
  46546. this.camera.getScene().onPointerObservable.remove(this._observer);
  46547. if (this._onMouseMove) {
  46548. element.removeEventListener("mousemove", this._onMouseMove);
  46549. }
  46550. this._observer = null;
  46551. this._onMouseMove = null;
  46552. this.previousPosition = null;
  46553. }
  46554. };
  46555. FreeCameraMouseInput.prototype.getClassName = function () {
  46556. return "FreeCameraMouseInput";
  46557. };
  46558. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46559. return "mouse";
  46560. };
  46561. __decorate([
  46562. BABYLON.serialize()
  46563. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46564. __decorate([
  46565. BABYLON.serialize()
  46566. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46567. return FreeCameraMouseInput;
  46568. }());
  46569. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46570. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46571. })(BABYLON || (BABYLON = {}));
  46572. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46573. var BABYLON;
  46574. (function (BABYLON) {
  46575. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46576. function FreeCameraKeyboardMoveInput() {
  46577. this._keys = new Array();
  46578. this.keysUp = [38];
  46579. this.keysDown = [40];
  46580. this.keysLeft = [37];
  46581. this.keysRight = [39];
  46582. }
  46583. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46584. var _this = this;
  46585. if (this._onCanvasBlurObserver) {
  46586. return;
  46587. }
  46588. this._scene = this.camera.getScene();
  46589. this._engine = this._scene.getEngine();
  46590. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46591. _this._keys = [];
  46592. });
  46593. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46594. var evt = info.event;
  46595. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46596. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46597. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46598. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46599. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46600. var index = _this._keys.indexOf(evt.keyCode);
  46601. if (index === -1) {
  46602. _this._keys.push(evt.keyCode);
  46603. }
  46604. if (!noPreventDefault) {
  46605. evt.preventDefault();
  46606. }
  46607. }
  46608. }
  46609. else {
  46610. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46611. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46612. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46613. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46614. var index = _this._keys.indexOf(evt.keyCode);
  46615. if (index >= 0) {
  46616. _this._keys.splice(index, 1);
  46617. }
  46618. if (!noPreventDefault) {
  46619. evt.preventDefault();
  46620. }
  46621. }
  46622. }
  46623. });
  46624. };
  46625. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46626. if (this._scene) {
  46627. if (this._onKeyboardObserver) {
  46628. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46629. }
  46630. if (this._onCanvasBlurObserver) {
  46631. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46632. }
  46633. this._onKeyboardObserver = null;
  46634. this._onCanvasBlurObserver = null;
  46635. }
  46636. this._keys = [];
  46637. };
  46638. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46639. if (this._onKeyboardObserver) {
  46640. var camera = this.camera;
  46641. // Keyboard
  46642. for (var index = 0; index < this._keys.length; index++) {
  46643. var keyCode = this._keys[index];
  46644. var speed = camera._computeLocalCameraSpeed();
  46645. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46646. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46647. }
  46648. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46649. camera._localDirection.copyFromFloats(0, 0, speed);
  46650. }
  46651. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46652. camera._localDirection.copyFromFloats(speed, 0, 0);
  46653. }
  46654. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46655. camera._localDirection.copyFromFloats(0, 0, -speed);
  46656. }
  46657. if (camera.getScene().useRightHandedSystem) {
  46658. camera._localDirection.z *= -1;
  46659. }
  46660. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46661. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46662. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46663. }
  46664. }
  46665. };
  46666. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46667. return "FreeCameraKeyboardMoveInput";
  46668. };
  46669. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46670. this._keys = [];
  46671. };
  46672. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46673. return "keyboard";
  46674. };
  46675. __decorate([
  46676. BABYLON.serialize()
  46677. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46678. __decorate([
  46679. BABYLON.serialize()
  46680. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46681. __decorate([
  46682. BABYLON.serialize()
  46683. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46684. __decorate([
  46685. BABYLON.serialize()
  46686. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46687. return FreeCameraKeyboardMoveInput;
  46688. }());
  46689. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46690. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46691. })(BABYLON || (BABYLON = {}));
  46692. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46693. var BABYLON;
  46694. (function (BABYLON) {
  46695. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46696. __extends(FreeCameraInputsManager, _super);
  46697. function FreeCameraInputsManager(camera) {
  46698. return _super.call(this, camera) || this;
  46699. }
  46700. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46701. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46702. return this;
  46703. };
  46704. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46705. if (touchEnabled === void 0) { touchEnabled = true; }
  46706. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46707. return this;
  46708. };
  46709. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46710. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46711. return this;
  46712. };
  46713. FreeCameraInputsManager.prototype.addTouch = function () {
  46714. this.add(new BABYLON.FreeCameraTouchInput());
  46715. return this;
  46716. };
  46717. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46718. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46719. return this;
  46720. };
  46721. return FreeCameraInputsManager;
  46722. }(BABYLON.CameraInputsManager));
  46723. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46724. })(BABYLON || (BABYLON = {}));
  46725. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46726. var BABYLON;
  46727. (function (BABYLON) {
  46728. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46729. // Forcing to use the Universal camera
  46730. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46731. });
  46732. var FreeCamera = /** @class */ (function (_super) {
  46733. __extends(FreeCamera, _super);
  46734. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46735. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46736. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46737. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46738. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46739. _this.checkCollisions = false;
  46740. _this.applyGravity = false;
  46741. _this._needMoveForGravity = false;
  46742. _this._oldPosition = BABYLON.Vector3.Zero();
  46743. _this._diffPosition = BABYLON.Vector3.Zero();
  46744. _this._newPosition = BABYLON.Vector3.Zero();
  46745. // Collisions
  46746. _this._collisionMask = -1;
  46747. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46748. if (collidedMesh === void 0) { collidedMesh = null; }
  46749. //TODO move this to the collision coordinator!
  46750. if (_this.getScene().workerCollisions)
  46751. newPosition.multiplyInPlace(_this._collider._radius);
  46752. var updatePosition = function (newPos) {
  46753. _this._newPosition.copyFrom(newPos);
  46754. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46755. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46756. _this.position.addInPlace(_this._diffPosition);
  46757. if (_this.onCollide && collidedMesh) {
  46758. _this.onCollide(collidedMesh);
  46759. }
  46760. }
  46761. };
  46762. updatePosition(newPosition);
  46763. };
  46764. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46765. _this.inputs.addKeyboard().addMouse();
  46766. return _this;
  46767. }
  46768. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46769. //-- begin properties for backward compatibility for inputs
  46770. /**
  46771. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46772. * Higher values reduce sensitivity.
  46773. */
  46774. get: function () {
  46775. var mouse = this.inputs.attached["mouse"];
  46776. if (mouse)
  46777. return mouse.angularSensibility;
  46778. return 0;
  46779. },
  46780. /**
  46781. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46782. * Higher values reduce sensitivity.
  46783. */
  46784. set: function (value) {
  46785. var mouse = this.inputs.attached["mouse"];
  46786. if (mouse)
  46787. mouse.angularSensibility = value;
  46788. },
  46789. enumerable: true,
  46790. configurable: true
  46791. });
  46792. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46793. get: function () {
  46794. var keyboard = this.inputs.attached["keyboard"];
  46795. if (keyboard)
  46796. return keyboard.keysUp;
  46797. return [];
  46798. },
  46799. set: function (value) {
  46800. var keyboard = this.inputs.attached["keyboard"];
  46801. if (keyboard)
  46802. keyboard.keysUp = value;
  46803. },
  46804. enumerable: true,
  46805. configurable: true
  46806. });
  46807. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46808. get: function () {
  46809. var keyboard = this.inputs.attached["keyboard"];
  46810. if (keyboard)
  46811. return keyboard.keysDown;
  46812. return [];
  46813. },
  46814. set: function (value) {
  46815. var keyboard = this.inputs.attached["keyboard"];
  46816. if (keyboard)
  46817. keyboard.keysDown = value;
  46818. },
  46819. enumerable: true,
  46820. configurable: true
  46821. });
  46822. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46823. get: function () {
  46824. var keyboard = this.inputs.attached["keyboard"];
  46825. if (keyboard)
  46826. return keyboard.keysLeft;
  46827. return [];
  46828. },
  46829. set: function (value) {
  46830. var keyboard = this.inputs.attached["keyboard"];
  46831. if (keyboard)
  46832. keyboard.keysLeft = value;
  46833. },
  46834. enumerable: true,
  46835. configurable: true
  46836. });
  46837. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46838. get: function () {
  46839. var keyboard = this.inputs.attached["keyboard"];
  46840. if (keyboard)
  46841. return keyboard.keysRight;
  46842. return [];
  46843. },
  46844. set: function (value) {
  46845. var keyboard = this.inputs.attached["keyboard"];
  46846. if (keyboard)
  46847. keyboard.keysRight = value;
  46848. },
  46849. enumerable: true,
  46850. configurable: true
  46851. });
  46852. // Controls
  46853. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46854. this.inputs.attachElement(element, noPreventDefault);
  46855. };
  46856. FreeCamera.prototype.detachControl = function (element) {
  46857. this.inputs.detachElement(element);
  46858. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46859. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46860. };
  46861. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46862. get: function () {
  46863. return this._collisionMask;
  46864. },
  46865. set: function (mask) {
  46866. this._collisionMask = !isNaN(mask) ? mask : -1;
  46867. },
  46868. enumerable: true,
  46869. configurable: true
  46870. });
  46871. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46872. var globalPosition;
  46873. if (this.parent) {
  46874. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46875. }
  46876. else {
  46877. globalPosition = this.position;
  46878. }
  46879. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46880. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46881. if (!this._collider) {
  46882. this._collider = new BABYLON.Collider();
  46883. }
  46884. this._collider._radius = this.ellipsoid;
  46885. this._collider.collisionMask = this._collisionMask;
  46886. //no need for clone, as long as gravity is not on.
  46887. var actualDisplacement = displacement;
  46888. //add gravity to the direction to prevent the dual-collision checking
  46889. if (this.applyGravity) {
  46890. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46891. actualDisplacement = displacement.add(this.getScene().gravity);
  46892. }
  46893. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46894. };
  46895. FreeCamera.prototype._checkInputs = function () {
  46896. if (!this._localDirection) {
  46897. this._localDirection = BABYLON.Vector3.Zero();
  46898. this._transformedDirection = BABYLON.Vector3.Zero();
  46899. }
  46900. this.inputs.checkInputs();
  46901. _super.prototype._checkInputs.call(this);
  46902. };
  46903. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46904. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46905. };
  46906. FreeCamera.prototype._updatePosition = function () {
  46907. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46908. this._collideWithWorld(this.cameraDirection);
  46909. }
  46910. else {
  46911. _super.prototype._updatePosition.call(this);
  46912. }
  46913. };
  46914. FreeCamera.prototype.dispose = function () {
  46915. this.inputs.clear();
  46916. _super.prototype.dispose.call(this);
  46917. };
  46918. FreeCamera.prototype.getClassName = function () {
  46919. return "FreeCamera";
  46920. };
  46921. __decorate([
  46922. BABYLON.serializeAsVector3()
  46923. ], FreeCamera.prototype, "ellipsoid", void 0);
  46924. __decorate([
  46925. BABYLON.serializeAsVector3()
  46926. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46927. __decorate([
  46928. BABYLON.serialize()
  46929. ], FreeCamera.prototype, "checkCollisions", void 0);
  46930. __decorate([
  46931. BABYLON.serialize()
  46932. ], FreeCamera.prototype, "applyGravity", void 0);
  46933. return FreeCamera;
  46934. }(BABYLON.TargetCamera));
  46935. BABYLON.FreeCamera = FreeCamera;
  46936. })(BABYLON || (BABYLON = {}));
  46937. //# sourceMappingURL=babylon.freeCamera.js.map
  46938. var BABYLON;
  46939. (function (BABYLON) {
  46940. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46941. function ArcRotateCameraKeyboardMoveInput() {
  46942. this._keys = new Array();
  46943. this.keysUp = [38];
  46944. this.keysDown = [40];
  46945. this.keysLeft = [37];
  46946. this.keysRight = [39];
  46947. this.keysReset = [220];
  46948. this.panningSensibility = 50.0;
  46949. this.zoomingSensibility = 25.0;
  46950. this.useAltToZoom = true;
  46951. }
  46952. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46953. var _this = this;
  46954. if (this._onCanvasBlurObserver) {
  46955. return;
  46956. }
  46957. this._scene = this.camera.getScene();
  46958. this._engine = this._scene.getEngine();
  46959. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46960. _this._keys = [];
  46961. });
  46962. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46963. var evt = info.event;
  46964. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46965. _this._ctrlPressed = evt.ctrlKey;
  46966. _this._altPressed = evt.altKey;
  46967. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46968. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46969. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46970. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46971. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46972. var index = _this._keys.indexOf(evt.keyCode);
  46973. if (index === -1) {
  46974. _this._keys.push(evt.keyCode);
  46975. }
  46976. if (evt.preventDefault) {
  46977. if (!noPreventDefault) {
  46978. evt.preventDefault();
  46979. }
  46980. }
  46981. }
  46982. }
  46983. else {
  46984. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46985. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46986. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46987. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46988. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46989. var index = _this._keys.indexOf(evt.keyCode);
  46990. if (index >= 0) {
  46991. _this._keys.splice(index, 1);
  46992. }
  46993. if (evt.preventDefault) {
  46994. if (!noPreventDefault) {
  46995. evt.preventDefault();
  46996. }
  46997. }
  46998. }
  46999. }
  47000. });
  47001. };
  47002. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47003. if (this._scene) {
  47004. if (this._onKeyboardObserver) {
  47005. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47006. }
  47007. if (this._onCanvasBlurObserver) {
  47008. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47009. }
  47010. this._onKeyboardObserver = null;
  47011. this._onCanvasBlurObserver = null;
  47012. }
  47013. this._keys = [];
  47014. };
  47015. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47016. if (this._onKeyboardObserver) {
  47017. var camera = this.camera;
  47018. for (var index = 0; index < this._keys.length; index++) {
  47019. var keyCode = this._keys[index];
  47020. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47021. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47022. camera.inertialPanningX -= 1 / this.panningSensibility;
  47023. }
  47024. else {
  47025. camera.inertialAlphaOffset -= 0.01;
  47026. }
  47027. }
  47028. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47029. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47030. camera.inertialPanningY += 1 / this.panningSensibility;
  47031. }
  47032. else if (this._altPressed && this.useAltToZoom) {
  47033. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47034. }
  47035. else {
  47036. camera.inertialBetaOffset -= 0.01;
  47037. }
  47038. }
  47039. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47040. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47041. camera.inertialPanningX += 1 / this.panningSensibility;
  47042. }
  47043. else {
  47044. camera.inertialAlphaOffset += 0.01;
  47045. }
  47046. }
  47047. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47048. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47049. camera.inertialPanningY -= 1 / this.panningSensibility;
  47050. }
  47051. else if (this._altPressed && this.useAltToZoom) {
  47052. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47053. }
  47054. else {
  47055. camera.inertialBetaOffset += 0.01;
  47056. }
  47057. }
  47058. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47059. camera.restoreState();
  47060. }
  47061. }
  47062. }
  47063. };
  47064. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47065. return "ArcRotateCameraKeyboardMoveInput";
  47066. };
  47067. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47068. return "keyboard";
  47069. };
  47070. __decorate([
  47071. BABYLON.serialize()
  47072. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47073. __decorate([
  47074. BABYLON.serialize()
  47075. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47076. __decorate([
  47077. BABYLON.serialize()
  47078. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47079. __decorate([
  47080. BABYLON.serialize()
  47081. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47082. __decorate([
  47083. BABYLON.serialize()
  47084. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47085. __decorate([
  47086. BABYLON.serialize()
  47087. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47088. __decorate([
  47089. BABYLON.serialize()
  47090. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47091. __decorate([
  47092. BABYLON.serialize()
  47093. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47094. return ArcRotateCameraKeyboardMoveInput;
  47095. }());
  47096. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47097. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47098. })(BABYLON || (BABYLON = {}));
  47099. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47100. var BABYLON;
  47101. (function (BABYLON) {
  47102. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47103. function ArcRotateCameraMouseWheelInput() {
  47104. this.wheelPrecision = 3.0;
  47105. /**
  47106. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47107. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47108. */
  47109. this.wheelDeltaPercentage = 0;
  47110. }
  47111. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47112. var _this = this;
  47113. this._wheel = function (p, s) {
  47114. //sanity check - this should be a PointerWheel event.
  47115. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47116. return;
  47117. var event = p.event;
  47118. var delta = 0;
  47119. if (event.wheelDelta) {
  47120. if (_this.wheelDeltaPercentage) {
  47121. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47122. if (event.wheelDelta > 0) {
  47123. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47124. }
  47125. else {
  47126. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47127. }
  47128. }
  47129. else {
  47130. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47131. }
  47132. }
  47133. else if (event.detail) {
  47134. delta = -event.detail / _this.wheelPrecision;
  47135. }
  47136. if (delta)
  47137. _this.camera.inertialRadiusOffset += delta;
  47138. if (event.preventDefault) {
  47139. if (!noPreventDefault) {
  47140. event.preventDefault();
  47141. }
  47142. }
  47143. };
  47144. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47145. };
  47146. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47147. if (this._observer && element) {
  47148. this.camera.getScene().onPointerObservable.remove(this._observer);
  47149. this._observer = null;
  47150. this._wheel = null;
  47151. }
  47152. };
  47153. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47154. return "ArcRotateCameraMouseWheelInput";
  47155. };
  47156. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47157. return "mousewheel";
  47158. };
  47159. __decorate([
  47160. BABYLON.serialize()
  47161. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47162. __decorate([
  47163. BABYLON.serialize()
  47164. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47165. return ArcRotateCameraMouseWheelInput;
  47166. }());
  47167. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47168. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47169. })(BABYLON || (BABYLON = {}));
  47170. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47171. var BABYLON;
  47172. (function (BABYLON) {
  47173. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47174. function ArcRotateCameraPointersInput() {
  47175. this.buttons = [0, 1, 2];
  47176. this.angularSensibilityX = 1000.0;
  47177. this.angularSensibilityY = 1000.0;
  47178. this.pinchPrecision = 12.0;
  47179. /**
  47180. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47181. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47182. */
  47183. this.pinchDeltaPercentage = 0;
  47184. this.panningSensibility = 1000.0;
  47185. this.multiTouchPanning = true;
  47186. this.multiTouchPanAndZoom = true;
  47187. this._isPanClick = false;
  47188. this.pinchInwards = true;
  47189. }
  47190. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47191. var _this = this;
  47192. var engine = this.camera.getEngine();
  47193. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47194. var pointA = null;
  47195. var pointB = null;
  47196. var previousPinchSquaredDistance = 0;
  47197. var initialDistance = 0;
  47198. var twoFingerActivityCount = 0;
  47199. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47200. this._pointerInput = function (p, s) {
  47201. var evt = p.event;
  47202. var isTouch = p.event.pointerType === "touch";
  47203. if (engine.isInVRExclusivePointerMode) {
  47204. return;
  47205. }
  47206. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47207. return;
  47208. }
  47209. var srcElement = (evt.srcElement || evt.target);
  47210. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47211. try {
  47212. srcElement.setPointerCapture(evt.pointerId);
  47213. }
  47214. catch (e) {
  47215. //Nothing to do with the error. Execution will continue.
  47216. }
  47217. // Manage panning with pan button click
  47218. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47219. // manage pointers
  47220. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47221. if (pointA === null) {
  47222. pointA = cacheSoloPointer;
  47223. }
  47224. else if (pointB === null) {
  47225. pointB = cacheSoloPointer;
  47226. }
  47227. if (!noPreventDefault) {
  47228. evt.preventDefault();
  47229. element.focus();
  47230. }
  47231. }
  47232. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47233. _this.camera.restoreState();
  47234. }
  47235. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47236. try {
  47237. srcElement.releasePointerCapture(evt.pointerId);
  47238. }
  47239. catch (e) {
  47240. //Nothing to do with the error.
  47241. }
  47242. cacheSoloPointer = null;
  47243. previousPinchSquaredDistance = 0;
  47244. previousMultiTouchPanPosition.isPaning = false;
  47245. previousMultiTouchPanPosition.isPinching = false;
  47246. twoFingerActivityCount = 0;
  47247. initialDistance = 0;
  47248. if (!isTouch) {
  47249. pointB = null; // Mouse and pen are mono pointer
  47250. }
  47251. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47252. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47253. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47254. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47255. if (engine._badOS) {
  47256. pointA = pointB = null;
  47257. }
  47258. else {
  47259. //only remove the impacted pointer in case of multitouch allowing on most
  47260. //platforms switching from rotate to zoom and pan seamlessly.
  47261. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47262. pointA = pointB;
  47263. pointB = null;
  47264. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47265. }
  47266. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47267. pointB = null;
  47268. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47269. }
  47270. else {
  47271. pointA = pointB = null;
  47272. }
  47273. }
  47274. if (!noPreventDefault) {
  47275. evt.preventDefault();
  47276. }
  47277. }
  47278. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47279. if (!noPreventDefault) {
  47280. evt.preventDefault();
  47281. }
  47282. // One button down
  47283. if (pointA && pointB === null && cacheSoloPointer) {
  47284. if (_this.panningSensibility !== 0 &&
  47285. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47286. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47287. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47288. }
  47289. else {
  47290. var offsetX = evt.clientX - cacheSoloPointer.x;
  47291. var offsetY = evt.clientY - cacheSoloPointer.y;
  47292. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47293. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47294. }
  47295. cacheSoloPointer.x = evt.clientX;
  47296. cacheSoloPointer.y = evt.clientY;
  47297. }
  47298. // Two buttons down: pinch/pan
  47299. else if (pointA && pointB) {
  47300. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47301. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47302. ed.x = evt.clientX;
  47303. ed.y = evt.clientY;
  47304. var direction = _this.pinchInwards ? 1 : -1;
  47305. var distX = pointA.x - pointB.x;
  47306. var distY = pointA.y - pointB.y;
  47307. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47308. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47309. if (previousPinchSquaredDistance === 0) {
  47310. initialDistance = pinchDistance;
  47311. previousPinchSquaredDistance = pinchSquaredDistance;
  47312. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47313. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47314. return;
  47315. }
  47316. if (_this.multiTouchPanAndZoom) {
  47317. if (_this.pinchDeltaPercentage) {
  47318. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47319. }
  47320. else {
  47321. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47322. (_this.pinchPrecision *
  47323. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47324. direction);
  47325. }
  47326. if (_this.panningSensibility !== 0) {
  47327. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47328. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47329. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47330. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47331. previousMultiTouchPanPosition.x = pointersCenterX;
  47332. previousMultiTouchPanPosition.y = pointersCenterY;
  47333. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47334. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47335. }
  47336. }
  47337. else {
  47338. twoFingerActivityCount++;
  47339. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47340. if (_this.pinchDeltaPercentage) {
  47341. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47342. }
  47343. else {
  47344. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47345. (_this.pinchPrecision *
  47346. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47347. direction);
  47348. }
  47349. previousMultiTouchPanPosition.isPaning = false;
  47350. previousMultiTouchPanPosition.isPinching = true;
  47351. }
  47352. else {
  47353. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47354. if (!previousMultiTouchPanPosition.isPaning) {
  47355. previousMultiTouchPanPosition.isPaning = true;
  47356. previousMultiTouchPanPosition.isPinching = false;
  47357. previousMultiTouchPanPosition.x = ed.x;
  47358. previousMultiTouchPanPosition.y = ed.y;
  47359. return;
  47360. }
  47361. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47362. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47363. }
  47364. }
  47365. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47366. previousMultiTouchPanPosition.x = ed.x;
  47367. previousMultiTouchPanPosition.y = ed.y;
  47368. }
  47369. }
  47370. previousPinchSquaredDistance = pinchSquaredDistance;
  47371. }
  47372. }
  47373. };
  47374. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47375. this._onContextMenu = function (evt) {
  47376. evt.preventDefault();
  47377. };
  47378. if (!this.camera._useCtrlForPanning) {
  47379. element.addEventListener("contextmenu", this._onContextMenu, false);
  47380. }
  47381. this._onLostFocus = function () {
  47382. //this._keys = [];
  47383. pointA = pointB = null;
  47384. previousPinchSquaredDistance = 0;
  47385. previousMultiTouchPanPosition.isPaning = false;
  47386. previousMultiTouchPanPosition.isPinching = false;
  47387. twoFingerActivityCount = 0;
  47388. cacheSoloPointer = null;
  47389. initialDistance = 0;
  47390. };
  47391. this._onMouseMove = function (evt) {
  47392. if (!engine.isPointerLock) {
  47393. return;
  47394. }
  47395. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47396. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47397. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47398. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47399. if (!noPreventDefault) {
  47400. evt.preventDefault();
  47401. }
  47402. };
  47403. this._onGestureStart = function (e) {
  47404. if (window.MSGesture === undefined) {
  47405. return;
  47406. }
  47407. if (!_this._MSGestureHandler) {
  47408. _this._MSGestureHandler = new MSGesture();
  47409. _this._MSGestureHandler.target = element;
  47410. }
  47411. _this._MSGestureHandler.addPointer(e.pointerId);
  47412. };
  47413. this._onGesture = function (e) {
  47414. _this.camera.radius *= e.scale;
  47415. if (e.preventDefault) {
  47416. if (!noPreventDefault) {
  47417. e.stopPropagation();
  47418. e.preventDefault();
  47419. }
  47420. }
  47421. };
  47422. element.addEventListener("mousemove", this._onMouseMove, false);
  47423. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47424. element.addEventListener("MSGestureChange", this._onGesture, false);
  47425. BABYLON.Tools.RegisterTopRootEvents([
  47426. { name: "blur", handler: this._onLostFocus }
  47427. ]);
  47428. };
  47429. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47430. if (this._onLostFocus) {
  47431. BABYLON.Tools.UnregisterTopRootEvents([
  47432. { name: "blur", handler: this._onLostFocus }
  47433. ]);
  47434. }
  47435. if (element && this._observer) {
  47436. this.camera.getScene().onPointerObservable.remove(this._observer);
  47437. this._observer = null;
  47438. if (this._onContextMenu) {
  47439. element.removeEventListener("contextmenu", this._onContextMenu);
  47440. }
  47441. if (this._onMouseMove) {
  47442. element.removeEventListener("mousemove", this._onMouseMove);
  47443. }
  47444. if (this._onGestureStart) {
  47445. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47446. }
  47447. if (this._onGesture) {
  47448. element.removeEventListener("MSGestureChange", this._onGesture);
  47449. }
  47450. this._isPanClick = false;
  47451. this.pinchInwards = true;
  47452. this._onMouseMove = null;
  47453. this._onGestureStart = null;
  47454. this._onGesture = null;
  47455. this._MSGestureHandler = null;
  47456. this._onLostFocus = null;
  47457. this._onContextMenu = null;
  47458. }
  47459. };
  47460. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47461. return "ArcRotateCameraPointersInput";
  47462. };
  47463. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47464. return "pointers";
  47465. };
  47466. __decorate([
  47467. BABYLON.serialize()
  47468. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47469. __decorate([
  47470. BABYLON.serialize()
  47471. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47472. __decorate([
  47473. BABYLON.serialize()
  47474. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47475. __decorate([
  47476. BABYLON.serialize()
  47477. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47478. __decorate([
  47479. BABYLON.serialize()
  47480. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47481. __decorate([
  47482. BABYLON.serialize()
  47483. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47484. __decorate([
  47485. BABYLON.serialize()
  47486. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47487. __decorate([
  47488. BABYLON.serialize()
  47489. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47490. return ArcRotateCameraPointersInput;
  47491. }());
  47492. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47493. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47494. })(BABYLON || (BABYLON = {}));
  47495. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47496. var BABYLON;
  47497. (function (BABYLON) {
  47498. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47499. __extends(ArcRotateCameraInputsManager, _super);
  47500. function ArcRotateCameraInputsManager(camera) {
  47501. return _super.call(this, camera) || this;
  47502. }
  47503. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47504. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47505. return this;
  47506. };
  47507. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47508. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47509. return this;
  47510. };
  47511. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47512. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47513. return this;
  47514. };
  47515. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47516. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47517. return this;
  47518. };
  47519. return ArcRotateCameraInputsManager;
  47520. }(BABYLON.CameraInputsManager));
  47521. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47522. })(BABYLON || (BABYLON = {}));
  47523. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47524. var BABYLON;
  47525. (function (BABYLON) {
  47526. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47527. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47528. });
  47529. var ArcRotateCamera = /** @class */ (function (_super) {
  47530. __extends(ArcRotateCamera, _super);
  47531. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47532. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47533. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47534. _this.inertialAlphaOffset = 0;
  47535. _this.inertialBetaOffset = 0;
  47536. _this.inertialRadiusOffset = 0;
  47537. _this.lowerAlphaLimit = null;
  47538. _this.upperAlphaLimit = null;
  47539. _this.lowerBetaLimit = 0.01;
  47540. _this.upperBetaLimit = Math.PI;
  47541. _this.lowerRadiusLimit = null;
  47542. _this.upperRadiusLimit = null;
  47543. _this.inertialPanningX = 0;
  47544. _this.inertialPanningY = 0;
  47545. _this.pinchToPanMaxDistance = 20;
  47546. _this.panningDistanceLimit = null;
  47547. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47548. _this.panningInertia = 0.9;
  47549. //-- end properties for backward compatibility for inputs
  47550. _this.zoomOnFactor = 1;
  47551. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47552. _this.allowUpsideDown = true;
  47553. _this._viewMatrix = new BABYLON.Matrix();
  47554. // Panning
  47555. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47556. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47557. _this.checkCollisions = false;
  47558. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47559. _this._previousPosition = BABYLON.Vector3.Zero();
  47560. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47561. _this._newPosition = BABYLON.Vector3.Zero();
  47562. _this._computationVector = BABYLON.Vector3.Zero();
  47563. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47564. if (collidedMesh === void 0) { collidedMesh = null; }
  47565. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47566. newPosition.multiplyInPlace(_this._collider._radius);
  47567. }
  47568. if (!collidedMesh) {
  47569. _this._previousPosition.copyFrom(_this.position);
  47570. }
  47571. else {
  47572. _this.setPosition(newPosition);
  47573. if (_this.onCollide) {
  47574. _this.onCollide(collidedMesh);
  47575. }
  47576. }
  47577. // Recompute because of constraints
  47578. var cosa = Math.cos(_this.alpha);
  47579. var sina = Math.sin(_this.alpha);
  47580. var cosb = Math.cos(_this.beta);
  47581. var sinb = Math.sin(_this.beta);
  47582. if (sinb === 0) {
  47583. sinb = 0.0001;
  47584. }
  47585. var target = _this._getTargetPosition();
  47586. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47587. target.addToRef(_this._computationVector, _this._newPosition);
  47588. _this.position.copyFrom(_this._newPosition);
  47589. var up = _this.upVector;
  47590. if (_this.allowUpsideDown && _this.beta < 0) {
  47591. up = up.clone();
  47592. up = up.negate();
  47593. }
  47594. _this._computeViewMatrix(_this.position, target, up);
  47595. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47596. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47597. _this._collisionTriggered = false;
  47598. };
  47599. _this._target = BABYLON.Vector3.Zero();
  47600. if (target) {
  47601. _this.setTarget(target);
  47602. }
  47603. _this.alpha = alpha;
  47604. _this.beta = beta;
  47605. _this.radius = radius;
  47606. _this.getViewMatrix();
  47607. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47608. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47609. return _this;
  47610. }
  47611. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47612. get: function () {
  47613. return this._target;
  47614. },
  47615. set: function (value) {
  47616. this.setTarget(value);
  47617. },
  47618. enumerable: true,
  47619. configurable: true
  47620. });
  47621. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47622. //-- begin properties for backward compatibility for inputs
  47623. get: function () {
  47624. var pointers = this.inputs.attached["pointers"];
  47625. if (pointers)
  47626. return pointers.angularSensibilityX;
  47627. return 0;
  47628. },
  47629. set: function (value) {
  47630. var pointers = this.inputs.attached["pointers"];
  47631. if (pointers) {
  47632. pointers.angularSensibilityX = value;
  47633. }
  47634. },
  47635. enumerable: true,
  47636. configurable: true
  47637. });
  47638. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47639. get: function () {
  47640. var pointers = this.inputs.attached["pointers"];
  47641. if (pointers)
  47642. return pointers.angularSensibilityY;
  47643. return 0;
  47644. },
  47645. set: function (value) {
  47646. var pointers = this.inputs.attached["pointers"];
  47647. if (pointers) {
  47648. pointers.angularSensibilityY = value;
  47649. }
  47650. },
  47651. enumerable: true,
  47652. configurable: true
  47653. });
  47654. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47655. get: function () {
  47656. var pointers = this.inputs.attached["pointers"];
  47657. if (pointers)
  47658. return pointers.pinchPrecision;
  47659. return 0;
  47660. },
  47661. set: function (value) {
  47662. var pointers = this.inputs.attached["pointers"];
  47663. if (pointers) {
  47664. pointers.pinchPrecision = value;
  47665. }
  47666. },
  47667. enumerable: true,
  47668. configurable: true
  47669. });
  47670. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47671. get: function () {
  47672. var pointers = this.inputs.attached["pointers"];
  47673. if (pointers)
  47674. return pointers.pinchDeltaPercentage;
  47675. return 0;
  47676. },
  47677. set: function (value) {
  47678. var pointers = this.inputs.attached["pointers"];
  47679. if (pointers) {
  47680. pointers.pinchDeltaPercentage = value;
  47681. }
  47682. },
  47683. enumerable: true,
  47684. configurable: true
  47685. });
  47686. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47687. get: function () {
  47688. var pointers = this.inputs.attached["pointers"];
  47689. if (pointers)
  47690. return pointers.panningSensibility;
  47691. return 0;
  47692. },
  47693. set: function (value) {
  47694. var pointers = this.inputs.attached["pointers"];
  47695. if (pointers) {
  47696. pointers.panningSensibility = value;
  47697. }
  47698. },
  47699. enumerable: true,
  47700. configurable: true
  47701. });
  47702. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47703. get: function () {
  47704. var keyboard = this.inputs.attached["keyboard"];
  47705. if (keyboard)
  47706. return keyboard.keysUp;
  47707. return [];
  47708. },
  47709. set: function (value) {
  47710. var keyboard = this.inputs.attached["keyboard"];
  47711. if (keyboard)
  47712. keyboard.keysUp = value;
  47713. },
  47714. enumerable: true,
  47715. configurable: true
  47716. });
  47717. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47718. get: function () {
  47719. var keyboard = this.inputs.attached["keyboard"];
  47720. if (keyboard)
  47721. return keyboard.keysDown;
  47722. return [];
  47723. },
  47724. set: function (value) {
  47725. var keyboard = this.inputs.attached["keyboard"];
  47726. if (keyboard)
  47727. keyboard.keysDown = value;
  47728. },
  47729. enumerable: true,
  47730. configurable: true
  47731. });
  47732. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47733. get: function () {
  47734. var keyboard = this.inputs.attached["keyboard"];
  47735. if (keyboard)
  47736. return keyboard.keysLeft;
  47737. return [];
  47738. },
  47739. set: function (value) {
  47740. var keyboard = this.inputs.attached["keyboard"];
  47741. if (keyboard)
  47742. keyboard.keysLeft = value;
  47743. },
  47744. enumerable: true,
  47745. configurable: true
  47746. });
  47747. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47748. get: function () {
  47749. var keyboard = this.inputs.attached["keyboard"];
  47750. if (keyboard)
  47751. return keyboard.keysRight;
  47752. return [];
  47753. },
  47754. set: function (value) {
  47755. var keyboard = this.inputs.attached["keyboard"];
  47756. if (keyboard)
  47757. keyboard.keysRight = value;
  47758. },
  47759. enumerable: true,
  47760. configurable: true
  47761. });
  47762. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47763. get: function () {
  47764. var mousewheel = this.inputs.attached["mousewheel"];
  47765. if (mousewheel)
  47766. return mousewheel.wheelPrecision;
  47767. return 0;
  47768. },
  47769. set: function (value) {
  47770. var mousewheel = this.inputs.attached["mousewheel"];
  47771. if (mousewheel)
  47772. mousewheel.wheelPrecision = value;
  47773. },
  47774. enumerable: true,
  47775. configurable: true
  47776. });
  47777. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47778. get: function () {
  47779. var mousewheel = this.inputs.attached["mousewheel"];
  47780. if (mousewheel)
  47781. return mousewheel.wheelDeltaPercentage;
  47782. return 0;
  47783. },
  47784. set: function (value) {
  47785. var mousewheel = this.inputs.attached["mousewheel"];
  47786. if (mousewheel)
  47787. mousewheel.wheelDeltaPercentage = value;
  47788. },
  47789. enumerable: true,
  47790. configurable: true
  47791. });
  47792. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47793. get: function () {
  47794. return this._bouncingBehavior;
  47795. },
  47796. enumerable: true,
  47797. configurable: true
  47798. });
  47799. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47800. get: function () {
  47801. return this._bouncingBehavior != null;
  47802. },
  47803. set: function (value) {
  47804. if (value === this.useBouncingBehavior) {
  47805. return;
  47806. }
  47807. if (value) {
  47808. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47809. this.addBehavior(this._bouncingBehavior);
  47810. }
  47811. else if (this._bouncingBehavior) {
  47812. this.removeBehavior(this._bouncingBehavior);
  47813. this._bouncingBehavior = null;
  47814. }
  47815. },
  47816. enumerable: true,
  47817. configurable: true
  47818. });
  47819. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47820. get: function () {
  47821. return this._framingBehavior;
  47822. },
  47823. enumerable: true,
  47824. configurable: true
  47825. });
  47826. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47827. get: function () {
  47828. return this._framingBehavior != null;
  47829. },
  47830. set: function (value) {
  47831. if (value === this.useFramingBehavior) {
  47832. return;
  47833. }
  47834. if (value) {
  47835. this._framingBehavior = new BABYLON.FramingBehavior();
  47836. this.addBehavior(this._framingBehavior);
  47837. }
  47838. else if (this._framingBehavior) {
  47839. this.removeBehavior(this._framingBehavior);
  47840. this._framingBehavior = null;
  47841. }
  47842. },
  47843. enumerable: true,
  47844. configurable: true
  47845. });
  47846. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47847. get: function () {
  47848. return this._autoRotationBehavior;
  47849. },
  47850. enumerable: true,
  47851. configurable: true
  47852. });
  47853. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47854. get: function () {
  47855. return this._autoRotationBehavior != null;
  47856. },
  47857. set: function (value) {
  47858. if (value === this.useAutoRotationBehavior) {
  47859. return;
  47860. }
  47861. if (value) {
  47862. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47863. this.addBehavior(this._autoRotationBehavior);
  47864. }
  47865. else if (this._autoRotationBehavior) {
  47866. this.removeBehavior(this._autoRotationBehavior);
  47867. this._autoRotationBehavior = null;
  47868. }
  47869. },
  47870. enumerable: true,
  47871. configurable: true
  47872. });
  47873. // Cache
  47874. ArcRotateCamera.prototype._initCache = function () {
  47875. _super.prototype._initCache.call(this);
  47876. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47877. this._cache.alpha = undefined;
  47878. this._cache.beta = undefined;
  47879. this._cache.radius = undefined;
  47880. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47881. };
  47882. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47883. if (!ignoreParentClass) {
  47884. _super.prototype._updateCache.call(this);
  47885. }
  47886. this._cache._target.copyFrom(this._getTargetPosition());
  47887. this._cache.alpha = this.alpha;
  47888. this._cache.beta = this.beta;
  47889. this._cache.radius = this.radius;
  47890. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47891. };
  47892. ArcRotateCamera.prototype._getTargetPosition = function () {
  47893. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47894. var pos = this._targetHost.getAbsolutePosition();
  47895. if (this._targetBoundingCenter) {
  47896. pos.addToRef(this._targetBoundingCenter, this._target);
  47897. }
  47898. else {
  47899. this._target.copyFrom(pos);
  47900. }
  47901. }
  47902. var lockedTargetPosition = this._getLockedTargetPosition();
  47903. if (lockedTargetPosition) {
  47904. return lockedTargetPosition;
  47905. }
  47906. return this._target;
  47907. };
  47908. ArcRotateCamera.prototype.storeState = function () {
  47909. this._storedAlpha = this.alpha;
  47910. this._storedBeta = this.beta;
  47911. this._storedRadius = this.radius;
  47912. this._storedTarget = this._getTargetPosition().clone();
  47913. return _super.prototype.storeState.call(this);
  47914. };
  47915. /**
  47916. * Restored camera state. You must call storeState() first
  47917. */
  47918. ArcRotateCamera.prototype._restoreStateValues = function () {
  47919. if (!_super.prototype._restoreStateValues.call(this)) {
  47920. return false;
  47921. }
  47922. this.alpha = this._storedAlpha;
  47923. this.beta = this._storedBeta;
  47924. this.radius = this._storedRadius;
  47925. this.setTarget(this._storedTarget.clone());
  47926. this.inertialAlphaOffset = 0;
  47927. this.inertialBetaOffset = 0;
  47928. this.inertialRadiusOffset = 0;
  47929. this.inertialPanningX = 0;
  47930. this.inertialPanningY = 0;
  47931. return true;
  47932. };
  47933. // Synchronized
  47934. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47935. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47936. return false;
  47937. return this._cache._target.equals(this._getTargetPosition())
  47938. && this._cache.alpha === this.alpha
  47939. && this._cache.beta === this.beta
  47940. && this._cache.radius === this.radius
  47941. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47942. };
  47943. // Methods
  47944. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47945. var _this = this;
  47946. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47947. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47948. this._useCtrlForPanning = useCtrlForPanning;
  47949. this._panningMouseButton = panningMouseButton;
  47950. this.inputs.attachElement(element, noPreventDefault);
  47951. this._reset = function () {
  47952. _this.inertialAlphaOffset = 0;
  47953. _this.inertialBetaOffset = 0;
  47954. _this.inertialRadiusOffset = 0;
  47955. _this.inertialPanningX = 0;
  47956. _this.inertialPanningY = 0;
  47957. };
  47958. };
  47959. ArcRotateCamera.prototype.detachControl = function (element) {
  47960. this.inputs.detachElement(element);
  47961. if (this._reset) {
  47962. this._reset();
  47963. }
  47964. };
  47965. ArcRotateCamera.prototype._checkInputs = function () {
  47966. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47967. if (this._collisionTriggered) {
  47968. return;
  47969. }
  47970. this.inputs.checkInputs();
  47971. // Inertia
  47972. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47973. var inertialAlphaOffset = this.inertialAlphaOffset;
  47974. if (this.beta <= 0)
  47975. inertialAlphaOffset *= -1;
  47976. if (this.getScene().useRightHandedSystem)
  47977. inertialAlphaOffset *= -1;
  47978. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47979. inertialAlphaOffset *= -1;
  47980. this.alpha += inertialAlphaOffset;
  47981. this.beta += this.inertialBetaOffset;
  47982. this.radius -= this.inertialRadiusOffset;
  47983. this.inertialAlphaOffset *= this.inertia;
  47984. this.inertialBetaOffset *= this.inertia;
  47985. this.inertialRadiusOffset *= this.inertia;
  47986. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47987. this.inertialAlphaOffset = 0;
  47988. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47989. this.inertialBetaOffset = 0;
  47990. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47991. this.inertialRadiusOffset = 0;
  47992. }
  47993. // Panning inertia
  47994. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47995. if (!this._localDirection) {
  47996. this._localDirection = BABYLON.Vector3.Zero();
  47997. this._transformedDirection = BABYLON.Vector3.Zero();
  47998. }
  47999. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48000. this._localDirection.multiplyInPlace(this.panningAxis);
  48001. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48002. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48003. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48004. if (!this.panningAxis.y) {
  48005. this._transformedDirection.y = 0;
  48006. }
  48007. if (!this._targetHost) {
  48008. if (this.panningDistanceLimit) {
  48009. this._transformedDirection.addInPlace(this._target);
  48010. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48011. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48012. this._target.copyFrom(this._transformedDirection);
  48013. }
  48014. }
  48015. else {
  48016. this._target.addInPlace(this._transformedDirection);
  48017. }
  48018. }
  48019. this.inertialPanningX *= this.panningInertia;
  48020. this.inertialPanningY *= this.panningInertia;
  48021. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48022. this.inertialPanningX = 0;
  48023. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48024. this.inertialPanningY = 0;
  48025. }
  48026. // Limits
  48027. this._checkLimits();
  48028. _super.prototype._checkInputs.call(this);
  48029. };
  48030. ArcRotateCamera.prototype._checkLimits = function () {
  48031. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48032. if (this.allowUpsideDown && this.beta > Math.PI) {
  48033. this.beta = this.beta - (2 * Math.PI);
  48034. }
  48035. }
  48036. else {
  48037. if (this.beta < this.lowerBetaLimit) {
  48038. this.beta = this.lowerBetaLimit;
  48039. }
  48040. }
  48041. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48042. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48043. this.beta = this.beta + (2 * Math.PI);
  48044. }
  48045. }
  48046. else {
  48047. if (this.beta > this.upperBetaLimit) {
  48048. this.beta = this.upperBetaLimit;
  48049. }
  48050. }
  48051. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48052. this.alpha = this.lowerAlphaLimit;
  48053. }
  48054. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48055. this.alpha = this.upperAlphaLimit;
  48056. }
  48057. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48058. this.radius = this.lowerRadiusLimit;
  48059. }
  48060. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48061. this.radius = this.upperRadiusLimit;
  48062. }
  48063. };
  48064. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48065. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48066. this.radius = this._computationVector.length();
  48067. if (this.radius === 0) {
  48068. this.radius = 0.0001; // Just to avoid division by zero
  48069. }
  48070. // Alpha
  48071. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48072. if (this._computationVector.z < 0) {
  48073. this.alpha = 2 * Math.PI - this.alpha;
  48074. }
  48075. // Beta
  48076. this.beta = Math.acos(this._computationVector.y / this.radius);
  48077. this._checkLimits();
  48078. };
  48079. ArcRotateCamera.prototype.setPosition = function (position) {
  48080. if (this.position.equals(position)) {
  48081. return;
  48082. }
  48083. this.position.copyFrom(position);
  48084. this.rebuildAnglesAndRadius();
  48085. };
  48086. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48087. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48088. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48089. if (target.getBoundingInfo) {
  48090. if (toBoundingCenter) {
  48091. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48092. }
  48093. else {
  48094. this._targetBoundingCenter = null;
  48095. }
  48096. this._targetHost = target;
  48097. this._target = this._getTargetPosition();
  48098. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48099. }
  48100. else {
  48101. var newTarget = target;
  48102. var currentTarget = this._getTargetPosition();
  48103. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48104. return;
  48105. }
  48106. this._targetHost = null;
  48107. this._target = newTarget;
  48108. this._targetBoundingCenter = null;
  48109. this.onMeshTargetChangedObservable.notifyObservers(null);
  48110. }
  48111. this.rebuildAnglesAndRadius();
  48112. };
  48113. ArcRotateCamera.prototype._getViewMatrix = function () {
  48114. // Compute
  48115. var cosa = Math.cos(this.alpha);
  48116. var sina = Math.sin(this.alpha);
  48117. var cosb = Math.cos(this.beta);
  48118. var sinb = Math.sin(this.beta);
  48119. if (sinb === 0) {
  48120. sinb = 0.0001;
  48121. }
  48122. var target = this._getTargetPosition();
  48123. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48124. target.addToRef(this._computationVector, this._newPosition);
  48125. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48126. if (!this._collider) {
  48127. this._collider = new BABYLON.Collider();
  48128. }
  48129. this._collider._radius = this.collisionRadius;
  48130. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48131. this._collisionTriggered = true;
  48132. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48133. }
  48134. else {
  48135. this.position.copyFrom(this._newPosition);
  48136. var up = this.upVector;
  48137. if (this.allowUpsideDown && sinb < 0) {
  48138. up = up.clone();
  48139. up = up.negate();
  48140. }
  48141. this._computeViewMatrix(this.position, target, up);
  48142. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48143. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48144. }
  48145. this._currentTarget = target;
  48146. return this._viewMatrix;
  48147. };
  48148. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48149. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48150. meshes = meshes || this.getScene().meshes;
  48151. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48152. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48153. this.radius = distance * this.zoomOnFactor;
  48154. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48155. };
  48156. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48157. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48158. var meshesOrMinMaxVector;
  48159. var distance;
  48160. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48161. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48162. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48163. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48164. }
  48165. else { //minMaxVector and distance
  48166. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48167. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48168. distance = minMaxVectorAndDistance.distance;
  48169. }
  48170. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48171. if (!doNotUpdateMaxZ) {
  48172. this.maxZ = distance * 2;
  48173. }
  48174. };
  48175. /**
  48176. * @override
  48177. * Override Camera.createRigCamera
  48178. */
  48179. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48180. var alphaShift = 0;
  48181. switch (this.cameraRigMode) {
  48182. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48183. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48184. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48185. case BABYLON.Camera.RIG_MODE_VR:
  48186. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48187. break;
  48188. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48189. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48190. break;
  48191. }
  48192. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48193. rigCam._cameraRigParams = {};
  48194. return rigCam;
  48195. };
  48196. /**
  48197. * @override
  48198. * Override Camera._updateRigCameras
  48199. */
  48200. ArcRotateCamera.prototype._updateRigCameras = function () {
  48201. var camLeft = this._rigCameras[0];
  48202. var camRight = this._rigCameras[1];
  48203. camLeft.beta = camRight.beta = this.beta;
  48204. camLeft.radius = camRight.radius = this.radius;
  48205. switch (this.cameraRigMode) {
  48206. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48207. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48208. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48209. case BABYLON.Camera.RIG_MODE_VR:
  48210. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48211. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48212. break;
  48213. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48214. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48215. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48216. break;
  48217. }
  48218. _super.prototype._updateRigCameras.call(this);
  48219. };
  48220. ArcRotateCamera.prototype.dispose = function () {
  48221. this.inputs.clear();
  48222. _super.prototype.dispose.call(this);
  48223. };
  48224. ArcRotateCamera.prototype.getClassName = function () {
  48225. return "ArcRotateCamera";
  48226. };
  48227. __decorate([
  48228. BABYLON.serialize()
  48229. ], ArcRotateCamera.prototype, "alpha", void 0);
  48230. __decorate([
  48231. BABYLON.serialize()
  48232. ], ArcRotateCamera.prototype, "beta", void 0);
  48233. __decorate([
  48234. BABYLON.serialize()
  48235. ], ArcRotateCamera.prototype, "radius", void 0);
  48236. __decorate([
  48237. BABYLON.serializeAsVector3("target")
  48238. ], ArcRotateCamera.prototype, "_target", void 0);
  48239. __decorate([
  48240. BABYLON.serialize()
  48241. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48242. __decorate([
  48243. BABYLON.serialize()
  48244. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48245. __decorate([
  48246. BABYLON.serialize()
  48247. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48248. __decorate([
  48249. BABYLON.serialize()
  48250. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48251. __decorate([
  48252. BABYLON.serialize()
  48253. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48254. __decorate([
  48255. BABYLON.serialize()
  48256. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48257. __decorate([
  48258. BABYLON.serialize()
  48259. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48260. __decorate([
  48261. BABYLON.serialize()
  48262. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48263. __decorate([
  48264. BABYLON.serialize()
  48265. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48266. __decorate([
  48267. BABYLON.serialize()
  48268. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48269. __decorate([
  48270. BABYLON.serialize()
  48271. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48272. __decorate([
  48273. BABYLON.serialize()
  48274. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48275. __decorate([
  48276. BABYLON.serialize()
  48277. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48278. __decorate([
  48279. BABYLON.serializeAsVector3()
  48280. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48281. __decorate([
  48282. BABYLON.serialize()
  48283. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48284. __decorate([
  48285. BABYLON.serialize()
  48286. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48287. __decorate([
  48288. BABYLON.serialize()
  48289. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48290. return ArcRotateCamera;
  48291. }(BABYLON.TargetCamera));
  48292. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48293. })(BABYLON || (BABYLON = {}));
  48294. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48295. var BABYLON;
  48296. (function (BABYLON) {
  48297. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48298. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48299. });
  48300. /**
  48301. * The HemisphericLight simulates the ambient environment light,
  48302. * so the passed direction is the light reflection direction, not the incoming direction.
  48303. */
  48304. var HemisphericLight = /** @class */ (function (_super) {
  48305. __extends(HemisphericLight, _super);
  48306. /**
  48307. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48308. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48309. * The HemisphericLight can't cast shadows.
  48310. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48311. * @param name The friendly name of the light
  48312. * @param direction The direction of the light reflection
  48313. * @param scene The scene the light belongs to
  48314. */
  48315. function HemisphericLight(name, direction, scene) {
  48316. var _this = _super.call(this, name, scene) || this;
  48317. /**
  48318. * The groundColor is the light in the opposite direction to the one specified during creation.
  48319. * 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.
  48320. */
  48321. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48322. _this.direction = direction || BABYLON.Vector3.Up();
  48323. return _this;
  48324. }
  48325. HemisphericLight.prototype._buildUniformLayout = function () {
  48326. this._uniformBuffer.addUniform("vLightData", 4);
  48327. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48328. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48329. this._uniformBuffer.addUniform("vLightGround", 3);
  48330. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48331. this._uniformBuffer.addUniform("depthValues", 2);
  48332. this._uniformBuffer.create();
  48333. };
  48334. /**
  48335. * Returns the string "HemisphericLight".
  48336. * @return The class name
  48337. */
  48338. HemisphericLight.prototype.getClassName = function () {
  48339. return "HemisphericLight";
  48340. };
  48341. /**
  48342. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48343. * Returns the updated direction.
  48344. * @param target The target the direction should point to
  48345. * @return The computed direction
  48346. */
  48347. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48348. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48349. return this.direction;
  48350. };
  48351. /**
  48352. * Returns the shadow generator associated to the light.
  48353. * @returns Always null for hemispheric lights because it does not support shadows.
  48354. */
  48355. HemisphericLight.prototype.getShadowGenerator = function () {
  48356. return null;
  48357. };
  48358. /**
  48359. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48360. * @param effect The effect to update
  48361. * @param lightIndex The index of the light in the effect to update
  48362. * @returns The hemispheric light
  48363. */
  48364. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48365. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48366. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48367. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48368. return this;
  48369. };
  48370. /**
  48371. * @hidden internal use only.
  48372. */
  48373. HemisphericLight.prototype._getWorldMatrix = function () {
  48374. if (!this._worldMatrix) {
  48375. this._worldMatrix = BABYLON.Matrix.Identity();
  48376. }
  48377. return this._worldMatrix;
  48378. };
  48379. /**
  48380. * Returns the integer 3.
  48381. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48382. */
  48383. HemisphericLight.prototype.getTypeID = function () {
  48384. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48385. };
  48386. /**
  48387. * Prepares the list of defines specific to the light type.
  48388. * @param defines the list of defines
  48389. * @param lightIndex defines the index of the light for the effect
  48390. */
  48391. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48392. defines["HEMILIGHT" + lightIndex] = true;
  48393. };
  48394. __decorate([
  48395. BABYLON.serializeAsColor3()
  48396. ], HemisphericLight.prototype, "groundColor", void 0);
  48397. __decorate([
  48398. BABYLON.serializeAsVector3()
  48399. ], HemisphericLight.prototype, "direction", void 0);
  48400. return HemisphericLight;
  48401. }(BABYLON.Light));
  48402. BABYLON.HemisphericLight = HemisphericLight;
  48403. })(BABYLON || (BABYLON = {}));
  48404. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48405. var BABYLON;
  48406. (function (BABYLON) {
  48407. /**
  48408. * Base implementation IShadowLight
  48409. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48410. */
  48411. var ShadowLight = /** @class */ (function (_super) {
  48412. __extends(ShadowLight, _super);
  48413. function ShadowLight() {
  48414. var _this = _super !== null && _super.apply(this, arguments) || this;
  48415. _this._needProjectionMatrixCompute = true;
  48416. return _this;
  48417. }
  48418. ShadowLight.prototype._setPosition = function (value) {
  48419. this._position = value;
  48420. };
  48421. Object.defineProperty(ShadowLight.prototype, "position", {
  48422. /**
  48423. * Sets the position the shadow will be casted from. Also use as the light position for both
  48424. * point and spot lights.
  48425. */
  48426. get: function () {
  48427. return this._position;
  48428. },
  48429. /**
  48430. * Sets the position the shadow will be casted from. Also use as the light position for both
  48431. * point and spot lights.
  48432. */
  48433. set: function (value) {
  48434. this._setPosition(value);
  48435. },
  48436. enumerable: true,
  48437. configurable: true
  48438. });
  48439. ShadowLight.prototype._setDirection = function (value) {
  48440. this._direction = value;
  48441. };
  48442. Object.defineProperty(ShadowLight.prototype, "direction", {
  48443. /**
  48444. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48445. * Also use as the light direction on spot and directional lights.
  48446. */
  48447. get: function () {
  48448. return this._direction;
  48449. },
  48450. /**
  48451. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48452. * Also use as the light direction on spot and directional lights.
  48453. */
  48454. set: function (value) {
  48455. this._setDirection(value);
  48456. },
  48457. enumerable: true,
  48458. configurable: true
  48459. });
  48460. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48461. /**
  48462. * Gets the shadow projection clipping minimum z value.
  48463. */
  48464. get: function () {
  48465. return this._shadowMinZ;
  48466. },
  48467. /**
  48468. * Sets the shadow projection clipping minimum z value.
  48469. */
  48470. set: function (value) {
  48471. this._shadowMinZ = value;
  48472. this.forceProjectionMatrixCompute();
  48473. },
  48474. enumerable: true,
  48475. configurable: true
  48476. });
  48477. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48478. /**
  48479. * Sets the shadow projection clipping maximum z value.
  48480. */
  48481. get: function () {
  48482. return this._shadowMaxZ;
  48483. },
  48484. /**
  48485. * Gets the shadow projection clipping maximum z value.
  48486. */
  48487. set: function (value) {
  48488. this._shadowMaxZ = value;
  48489. this.forceProjectionMatrixCompute();
  48490. },
  48491. enumerable: true,
  48492. configurable: true
  48493. });
  48494. /**
  48495. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48496. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48497. */
  48498. ShadowLight.prototype.computeTransformedInformation = function () {
  48499. if (this.parent && this.parent.getWorldMatrix) {
  48500. if (!this.transformedPosition) {
  48501. this.transformedPosition = BABYLON.Vector3.Zero();
  48502. }
  48503. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48504. // In case the direction is present.
  48505. if (this.direction) {
  48506. if (!this.transformedDirection) {
  48507. this.transformedDirection = BABYLON.Vector3.Zero();
  48508. }
  48509. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48510. }
  48511. return true;
  48512. }
  48513. return false;
  48514. };
  48515. /**
  48516. * Return the depth scale used for the shadow map.
  48517. * @returns the depth scale.
  48518. */
  48519. ShadowLight.prototype.getDepthScale = function () {
  48520. return 50.0;
  48521. };
  48522. /**
  48523. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48524. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48525. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48526. */
  48527. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48528. return this.transformedDirection ? this.transformedDirection : this.direction;
  48529. };
  48530. /**
  48531. * Returns the ShadowLight absolute position in the World.
  48532. * @returns the position vector in world space
  48533. */
  48534. ShadowLight.prototype.getAbsolutePosition = function () {
  48535. return this.transformedPosition ? this.transformedPosition : this.position;
  48536. };
  48537. /**
  48538. * Sets the ShadowLight direction toward the passed target.
  48539. * @param target The point tot target in local space
  48540. * @returns the updated ShadowLight direction
  48541. */
  48542. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48543. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48544. return this.direction;
  48545. };
  48546. /**
  48547. * Returns the light rotation in euler definition.
  48548. * @returns the x y z rotation in local space.
  48549. */
  48550. ShadowLight.prototype.getRotation = function () {
  48551. this.direction.normalize();
  48552. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48553. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48554. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48555. };
  48556. /**
  48557. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48558. * @returns true if a cube texture needs to be use
  48559. */
  48560. ShadowLight.prototype.needCube = function () {
  48561. return false;
  48562. };
  48563. /**
  48564. * Detects if the projection matrix requires to be recomputed this frame.
  48565. * @returns true if it requires to be recomputed otherwise, false.
  48566. */
  48567. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48568. return this._needProjectionMatrixCompute;
  48569. };
  48570. /**
  48571. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48572. */
  48573. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48574. this._needProjectionMatrixCompute = true;
  48575. };
  48576. /**
  48577. * Get the world matrix of the sahdow lights.
  48578. * @hidden Internal Use Only
  48579. */
  48580. ShadowLight.prototype._getWorldMatrix = function () {
  48581. if (!this._worldMatrix) {
  48582. this._worldMatrix = BABYLON.Matrix.Identity();
  48583. }
  48584. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48585. return this._worldMatrix;
  48586. };
  48587. /**
  48588. * Gets the minZ used for shadow according to both the scene and the light.
  48589. * @param activeCamera The camera we are returning the min for
  48590. * @returns the depth min z
  48591. */
  48592. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48593. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48594. };
  48595. /**
  48596. * Gets the maxZ used for shadow according to both the scene and the light.
  48597. * @param activeCamera The camera we are returning the max for
  48598. * @returns the depth max z
  48599. */
  48600. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48601. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48602. };
  48603. /**
  48604. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48605. * @param matrix The materix to updated with the projection information
  48606. * @param viewMatrix The transform matrix of the light
  48607. * @param renderList The list of mesh to render in the map
  48608. * @returns The current light
  48609. */
  48610. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48611. if (this.customProjectionMatrixBuilder) {
  48612. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48613. }
  48614. else {
  48615. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48616. }
  48617. return this;
  48618. };
  48619. __decorate([
  48620. BABYLON.serializeAsVector3()
  48621. ], ShadowLight.prototype, "position", null);
  48622. __decorate([
  48623. BABYLON.serializeAsVector3()
  48624. ], ShadowLight.prototype, "direction", null);
  48625. __decorate([
  48626. BABYLON.serialize()
  48627. ], ShadowLight.prototype, "shadowMinZ", null);
  48628. __decorate([
  48629. BABYLON.serialize()
  48630. ], ShadowLight.prototype, "shadowMaxZ", null);
  48631. return ShadowLight;
  48632. }(BABYLON.Light));
  48633. BABYLON.ShadowLight = ShadowLight;
  48634. })(BABYLON || (BABYLON = {}));
  48635. //# sourceMappingURL=babylon.shadowLight.js.map
  48636. var BABYLON;
  48637. (function (BABYLON) {
  48638. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48639. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48640. });
  48641. /**
  48642. * A point light is a light defined by an unique point in world space.
  48643. * The light is emitted in every direction from this point.
  48644. * A good example of a point light is a standard light bulb.
  48645. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48646. */
  48647. var PointLight = /** @class */ (function (_super) {
  48648. __extends(PointLight, _super);
  48649. /**
  48650. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48651. * A PointLight emits the light in every direction.
  48652. * It can cast shadows.
  48653. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48654. * ```javascript
  48655. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48656. * ```
  48657. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48658. * @param name The light friendly name
  48659. * @param position The position of the point light in the scene
  48660. * @param scene The scene the lights belongs to
  48661. */
  48662. function PointLight(name, position, scene) {
  48663. var _this = _super.call(this, name, scene) || this;
  48664. _this._shadowAngle = Math.PI / 2;
  48665. _this.position = position;
  48666. return _this;
  48667. }
  48668. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48669. /**
  48670. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48671. * This specifies what angle the shadow will use to be created.
  48672. *
  48673. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48674. */
  48675. get: function () {
  48676. return this._shadowAngle;
  48677. },
  48678. /**
  48679. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48680. * This specifies what angle the shadow will use to be created.
  48681. *
  48682. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48683. */
  48684. set: function (value) {
  48685. this._shadowAngle = value;
  48686. this.forceProjectionMatrixCompute();
  48687. },
  48688. enumerable: true,
  48689. configurable: true
  48690. });
  48691. Object.defineProperty(PointLight.prototype, "direction", {
  48692. /**
  48693. * Gets the direction if it has been set.
  48694. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48695. */
  48696. get: function () {
  48697. return this._direction;
  48698. },
  48699. /**
  48700. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48701. */
  48702. set: function (value) {
  48703. var previousNeedCube = this.needCube();
  48704. this._direction = value;
  48705. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48706. this._shadowGenerator.recreateShadowMap();
  48707. }
  48708. },
  48709. enumerable: true,
  48710. configurable: true
  48711. });
  48712. /**
  48713. * Returns the string "PointLight"
  48714. * @returns the class name
  48715. */
  48716. PointLight.prototype.getClassName = function () {
  48717. return "PointLight";
  48718. };
  48719. /**
  48720. * Returns the integer 0.
  48721. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48722. */
  48723. PointLight.prototype.getTypeID = function () {
  48724. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48725. };
  48726. /**
  48727. * Specifies wether or not the shadowmap should be a cube texture.
  48728. * @returns true if the shadowmap needs to be a cube texture.
  48729. */
  48730. PointLight.prototype.needCube = function () {
  48731. return !this.direction;
  48732. };
  48733. /**
  48734. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48735. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48736. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48737. */
  48738. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48739. if (this.direction) {
  48740. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48741. }
  48742. else {
  48743. switch (faceIndex) {
  48744. case 0:
  48745. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48746. case 1:
  48747. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48748. case 2:
  48749. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48750. case 3:
  48751. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48752. case 4:
  48753. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48754. case 5:
  48755. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48756. }
  48757. }
  48758. return BABYLON.Vector3.Zero();
  48759. };
  48760. /**
  48761. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48762. * - fov = PI / 2
  48763. * - aspect ratio : 1.0
  48764. * - z-near and far equal to the active camera minZ and maxZ.
  48765. * Returns the PointLight.
  48766. */
  48767. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48768. var activeCamera = this.getScene().activeCamera;
  48769. if (!activeCamera) {
  48770. return;
  48771. }
  48772. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48773. };
  48774. PointLight.prototype._buildUniformLayout = function () {
  48775. this._uniformBuffer.addUniform("vLightData", 4);
  48776. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48777. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48778. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48779. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48780. this._uniformBuffer.addUniform("depthValues", 2);
  48781. this._uniformBuffer.create();
  48782. };
  48783. /**
  48784. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48785. * @param effect The effect to update
  48786. * @param lightIndex The index of the light in the effect to update
  48787. * @returns The point light
  48788. */
  48789. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48790. if (this.computeTransformedInformation()) {
  48791. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48792. }
  48793. else {
  48794. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48795. }
  48796. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48797. return this;
  48798. };
  48799. /**
  48800. * Prepares the list of defines specific to the light type.
  48801. * @param defines the list of defines
  48802. * @param lightIndex defines the index of the light for the effect
  48803. */
  48804. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48805. defines["POINTLIGHT" + lightIndex] = true;
  48806. };
  48807. __decorate([
  48808. BABYLON.serialize()
  48809. ], PointLight.prototype, "shadowAngle", null);
  48810. return PointLight;
  48811. }(BABYLON.ShadowLight));
  48812. BABYLON.PointLight = PointLight;
  48813. })(BABYLON || (BABYLON = {}));
  48814. //# sourceMappingURL=babylon.pointLight.js.map
  48815. var BABYLON;
  48816. (function (BABYLON) {
  48817. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48818. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48819. });
  48820. /**
  48821. * A directional light is defined by a direction (what a surprise!).
  48822. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48823. * 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.
  48824. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48825. */
  48826. var DirectionalLight = /** @class */ (function (_super) {
  48827. __extends(DirectionalLight, _super);
  48828. /**
  48829. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48830. * The directional light is emitted from everywhere in the given direction.
  48831. * It can cast shawdows.
  48832. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48833. * @param name The friendly name of the light
  48834. * @param direction The direction of the light
  48835. * @param scene The scene the light belongs to
  48836. */
  48837. function DirectionalLight(name, direction, scene) {
  48838. var _this = _super.call(this, name, scene) || this;
  48839. _this._shadowFrustumSize = 0;
  48840. _this._shadowOrthoScale = 0.1;
  48841. /**
  48842. * Automatically compute the projection matrix to best fit (including all the casters)
  48843. * on each frame.
  48844. */
  48845. _this.autoUpdateExtends = true;
  48846. // Cache
  48847. _this._orthoLeft = Number.MAX_VALUE;
  48848. _this._orthoRight = Number.MIN_VALUE;
  48849. _this._orthoTop = Number.MIN_VALUE;
  48850. _this._orthoBottom = Number.MAX_VALUE;
  48851. _this.position = direction.scale(-1.0);
  48852. _this.direction = direction;
  48853. return _this;
  48854. }
  48855. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48856. /**
  48857. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48858. */
  48859. get: function () {
  48860. return this._shadowFrustumSize;
  48861. },
  48862. /**
  48863. * Specifies a fix frustum size for the shadow generation.
  48864. */
  48865. set: function (value) {
  48866. this._shadowFrustumSize = value;
  48867. this.forceProjectionMatrixCompute();
  48868. },
  48869. enumerable: true,
  48870. configurable: true
  48871. });
  48872. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48873. /**
  48874. * Gets the shadow projection scale against the optimal computed one.
  48875. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48876. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48877. */
  48878. get: function () {
  48879. return this._shadowOrthoScale;
  48880. },
  48881. /**
  48882. * Sets the shadow projection scale against the optimal computed one.
  48883. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48884. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48885. */
  48886. set: function (value) {
  48887. this._shadowOrthoScale = value;
  48888. this.forceProjectionMatrixCompute();
  48889. },
  48890. enumerable: true,
  48891. configurable: true
  48892. });
  48893. /**
  48894. * Returns the string "DirectionalLight".
  48895. * @return The class name
  48896. */
  48897. DirectionalLight.prototype.getClassName = function () {
  48898. return "DirectionalLight";
  48899. };
  48900. /**
  48901. * Returns the integer 1.
  48902. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48903. */
  48904. DirectionalLight.prototype.getTypeID = function () {
  48905. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48906. };
  48907. /**
  48908. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48909. * Returns the DirectionalLight Shadow projection matrix.
  48910. */
  48911. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48912. if (this.shadowFrustumSize > 0) {
  48913. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48914. }
  48915. else {
  48916. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48917. }
  48918. };
  48919. /**
  48920. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48921. * Returns the DirectionalLight Shadow projection matrix.
  48922. */
  48923. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48924. var activeCamera = this.getScene().activeCamera;
  48925. if (!activeCamera) {
  48926. return;
  48927. }
  48928. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48929. };
  48930. /**
  48931. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48932. * Returns the DirectionalLight Shadow projection matrix.
  48933. */
  48934. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48935. var activeCamera = this.getScene().activeCamera;
  48936. if (!activeCamera) {
  48937. return;
  48938. }
  48939. // Check extends
  48940. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48941. var tempVector3 = BABYLON.Vector3.Zero();
  48942. this._orthoLeft = Number.MAX_VALUE;
  48943. this._orthoRight = Number.MIN_VALUE;
  48944. this._orthoTop = Number.MIN_VALUE;
  48945. this._orthoBottom = Number.MAX_VALUE;
  48946. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48947. var mesh = renderList[meshIndex];
  48948. if (!mesh) {
  48949. continue;
  48950. }
  48951. var boundingInfo = mesh.getBoundingInfo();
  48952. var boundingBox = boundingInfo.boundingBox;
  48953. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48954. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48955. if (tempVector3.x < this._orthoLeft)
  48956. this._orthoLeft = tempVector3.x;
  48957. if (tempVector3.y < this._orthoBottom)
  48958. this._orthoBottom = tempVector3.y;
  48959. if (tempVector3.x > this._orthoRight)
  48960. this._orthoRight = tempVector3.x;
  48961. if (tempVector3.y > this._orthoTop)
  48962. this._orthoTop = tempVector3.y;
  48963. }
  48964. }
  48965. }
  48966. var xOffset = this._orthoRight - this._orthoLeft;
  48967. var yOffset = this._orthoTop - this._orthoBottom;
  48968. 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);
  48969. };
  48970. DirectionalLight.prototype._buildUniformLayout = function () {
  48971. this._uniformBuffer.addUniform("vLightData", 4);
  48972. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48973. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48974. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48975. this._uniformBuffer.addUniform("depthValues", 2);
  48976. this._uniformBuffer.create();
  48977. };
  48978. /**
  48979. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48980. * @param effect The effect to update
  48981. * @param lightIndex The index of the light in the effect to update
  48982. * @returns The directional light
  48983. */
  48984. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48985. if (this.computeTransformedInformation()) {
  48986. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48987. return this;
  48988. }
  48989. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48990. return this;
  48991. };
  48992. /**
  48993. * Gets the minZ used for shadow according to both the scene and the light.
  48994. *
  48995. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48996. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48997. * @param activeCamera The camera we are returning the min for
  48998. * @returns the depth min z
  48999. */
  49000. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49001. return 1;
  49002. };
  49003. /**
  49004. * Gets the maxZ used for shadow according to both the scene and the light.
  49005. *
  49006. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49007. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49008. * @param activeCamera The camera we are returning the max for
  49009. * @returns the depth max z
  49010. */
  49011. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49012. return 1;
  49013. };
  49014. /**
  49015. * Prepares the list of defines specific to the light type.
  49016. * @param defines the list of defines
  49017. * @param lightIndex defines the index of the light for the effect
  49018. */
  49019. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49020. defines["DIRLIGHT" + lightIndex] = true;
  49021. };
  49022. __decorate([
  49023. BABYLON.serialize()
  49024. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49025. __decorate([
  49026. BABYLON.serialize()
  49027. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49028. __decorate([
  49029. BABYLON.serialize()
  49030. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49031. return DirectionalLight;
  49032. }(BABYLON.ShadowLight));
  49033. BABYLON.DirectionalLight = DirectionalLight;
  49034. })(BABYLON || (BABYLON = {}));
  49035. //# sourceMappingURL=babylon.directionalLight.js.map
  49036. var BABYLON;
  49037. (function (BABYLON) {
  49038. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49039. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49040. });
  49041. /**
  49042. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49043. * These values define a cone of light starting from the position, emitting toward the direction.
  49044. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49045. * and the exponent defines the speed of the decay of the light with distance (reach).
  49046. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49047. */
  49048. var SpotLight = /** @class */ (function (_super) {
  49049. __extends(SpotLight, _super);
  49050. /**
  49051. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49052. * It can cast shadows.
  49053. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49054. * @param name The light friendly name
  49055. * @param position The position of the spot light in the scene
  49056. * @param direction The direction of the light in the scene
  49057. * @param angle The cone angle of the light in Radians
  49058. * @param exponent The light decay speed with the distance from the emission spot
  49059. * @param scene The scene the lights belongs to
  49060. */
  49061. function SpotLight(name, position, direction, angle, exponent, scene) {
  49062. var _this = _super.call(this, name, scene) || this;
  49063. _this._innerAngle = 0;
  49064. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49065. _this._projectionTextureLightNear = 1e-6;
  49066. _this._projectionTextureLightFar = 1000.0;
  49067. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49068. _this._projectionTextureViewLightDirty = true;
  49069. _this._projectionTextureProjectionLightDirty = true;
  49070. _this._projectionTextureDirty = true;
  49071. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49072. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49073. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49074. _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);
  49075. _this.position = position;
  49076. _this.direction = direction;
  49077. _this.angle = angle;
  49078. _this.exponent = exponent;
  49079. return _this;
  49080. }
  49081. Object.defineProperty(SpotLight.prototype, "angle", {
  49082. /**
  49083. * Gets the cone angle of the spot light in Radians.
  49084. */
  49085. get: function () {
  49086. return this._angle;
  49087. },
  49088. /**
  49089. * Sets the cone angle of the spot light in Radians.
  49090. */
  49091. set: function (value) {
  49092. this._angle = value;
  49093. this._cosHalfAngle = Math.cos(value * 0.5);
  49094. this._projectionTextureProjectionLightDirty = true;
  49095. this.forceProjectionMatrixCompute();
  49096. this._computeAngleValues();
  49097. },
  49098. enumerable: true,
  49099. configurable: true
  49100. });
  49101. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49102. /**
  49103. * Only used in gltf falloff mode, this defines the angle where
  49104. * the directional falloff will start before cutting at angle which could be seen
  49105. * as outer angle.
  49106. */
  49107. get: function () {
  49108. return this._angle;
  49109. },
  49110. /**
  49111. * Only used in gltf falloff mode, this defines the angle where
  49112. * the directional falloff will start before cutting at angle which could be seen
  49113. * as outer angle.
  49114. */
  49115. set: function (value) {
  49116. this._innerAngle = value;
  49117. this._computeAngleValues();
  49118. },
  49119. enumerable: true,
  49120. configurable: true
  49121. });
  49122. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49123. /**
  49124. * Allows scaling the angle of the light for shadow generation only.
  49125. */
  49126. get: function () {
  49127. return this._shadowAngleScale;
  49128. },
  49129. /**
  49130. * Allows scaling the angle of the light for shadow generation only.
  49131. */
  49132. set: function (value) {
  49133. this._shadowAngleScale = value;
  49134. this.forceProjectionMatrixCompute();
  49135. },
  49136. enumerable: true,
  49137. configurable: true
  49138. });
  49139. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49140. /**
  49141. * Allows reading the projecton texture
  49142. */
  49143. get: function () {
  49144. return this._projectionTextureMatrix;
  49145. },
  49146. enumerable: true,
  49147. configurable: true
  49148. });
  49149. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49150. /**
  49151. * Gets the near clip of the Spotlight for texture projection.
  49152. */
  49153. get: function () {
  49154. return this._projectionTextureLightNear;
  49155. },
  49156. /**
  49157. * Sets the near clip of the Spotlight for texture projection.
  49158. */
  49159. set: function (value) {
  49160. this._projectionTextureLightNear = value;
  49161. this._projectionTextureProjectionLightDirty = true;
  49162. },
  49163. enumerable: true,
  49164. configurable: true
  49165. });
  49166. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49167. /**
  49168. * Gets the far clip of the Spotlight for texture projection.
  49169. */
  49170. get: function () {
  49171. return this._projectionTextureLightFar;
  49172. },
  49173. /**
  49174. * Sets the far clip of the Spotlight for texture projection.
  49175. */
  49176. set: function (value) {
  49177. this._projectionTextureLightFar = value;
  49178. this._projectionTextureProjectionLightDirty = true;
  49179. },
  49180. enumerable: true,
  49181. configurable: true
  49182. });
  49183. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49184. /**
  49185. * Gets the Up vector of the Spotlight for texture projection.
  49186. */
  49187. get: function () {
  49188. return this._projectionTextureUpDirection;
  49189. },
  49190. /**
  49191. * Sets the Up vector of the Spotlight for texture projection.
  49192. */
  49193. set: function (value) {
  49194. this._projectionTextureUpDirection = value;
  49195. this._projectionTextureProjectionLightDirty = true;
  49196. },
  49197. enumerable: true,
  49198. configurable: true
  49199. });
  49200. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49201. /**
  49202. * Gets the projection texture of the light.
  49203. */
  49204. get: function () {
  49205. return this._projectionTexture;
  49206. },
  49207. /**
  49208. * Sets the projection texture of the light.
  49209. */
  49210. set: function (value) {
  49211. this._projectionTexture = value;
  49212. this._projectionTextureDirty = true;
  49213. },
  49214. enumerable: true,
  49215. configurable: true
  49216. });
  49217. /**
  49218. * Returns the string "SpotLight".
  49219. * @returns the class name
  49220. */
  49221. SpotLight.prototype.getClassName = function () {
  49222. return "SpotLight";
  49223. };
  49224. /**
  49225. * Returns the integer 2.
  49226. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49227. */
  49228. SpotLight.prototype.getTypeID = function () {
  49229. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49230. };
  49231. /**
  49232. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49233. */
  49234. SpotLight.prototype._setDirection = function (value) {
  49235. _super.prototype._setDirection.call(this, value);
  49236. this._projectionTextureViewLightDirty = true;
  49237. };
  49238. /**
  49239. * Overrides the position setter to recompute the projection texture view light Matrix.
  49240. */
  49241. SpotLight.prototype._setPosition = function (value) {
  49242. _super.prototype._setPosition.call(this, value);
  49243. this._projectionTextureViewLightDirty = true;
  49244. };
  49245. /**
  49246. * 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.
  49247. * Returns the SpotLight.
  49248. */
  49249. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49250. var activeCamera = this.getScene().activeCamera;
  49251. if (!activeCamera) {
  49252. return;
  49253. }
  49254. this._shadowAngleScale = this._shadowAngleScale || 1;
  49255. var angle = this._shadowAngleScale * this._angle;
  49256. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49257. };
  49258. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49259. this._projectionTextureViewLightDirty = false;
  49260. this._projectionTextureDirty = true;
  49261. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49262. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49263. };
  49264. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49265. this._projectionTextureProjectionLightDirty = false;
  49266. this._projectionTextureDirty = true;
  49267. var light_far = this.projectionTextureLightFar;
  49268. var light_near = this.projectionTextureLightNear;
  49269. var P = light_far / (light_far - light_near);
  49270. var Q = -P * light_near;
  49271. var S = 1.0 / Math.tan(this._angle / 2.0);
  49272. var A = 1.0;
  49273. 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);
  49274. };
  49275. /**
  49276. * Main function for light texture projection matrix computing.
  49277. */
  49278. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49279. this._projectionTextureDirty = false;
  49280. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49281. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49282. };
  49283. SpotLight.prototype._buildUniformLayout = function () {
  49284. this._uniformBuffer.addUniform("vLightData", 4);
  49285. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49286. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49287. this._uniformBuffer.addUniform("vLightDirection", 3);
  49288. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49289. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49290. this._uniformBuffer.addUniform("depthValues", 2);
  49291. this._uniformBuffer.create();
  49292. };
  49293. SpotLight.prototype._computeAngleValues = function () {
  49294. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49295. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49296. };
  49297. /**
  49298. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49299. * @param effect The effect to update
  49300. * @param lightIndex The index of the light in the effect to update
  49301. * @returns The spot light
  49302. */
  49303. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49304. var normalizeDirection;
  49305. if (this.computeTransformedInformation()) {
  49306. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49307. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49308. }
  49309. else {
  49310. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49311. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49312. }
  49313. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49314. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49315. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49316. if (this._projectionTextureViewLightDirty) {
  49317. this._computeProjectionTextureViewLightMatrix();
  49318. }
  49319. if (this._projectionTextureProjectionLightDirty) {
  49320. this._computeProjectionTextureProjectionLightMatrix();
  49321. }
  49322. if (this._projectionTextureDirty) {
  49323. this._computeProjectionTextureMatrix();
  49324. }
  49325. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49326. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49327. }
  49328. return this;
  49329. };
  49330. /**
  49331. * Disposes the light and the associated resources.
  49332. */
  49333. SpotLight.prototype.dispose = function () {
  49334. _super.prototype.dispose.call(this);
  49335. if (this._projectionTexture) {
  49336. this._projectionTexture.dispose();
  49337. }
  49338. };
  49339. /**
  49340. * Prepares the list of defines specific to the light type.
  49341. * @param defines the list of defines
  49342. * @param lightIndex defines the index of the light for the effect
  49343. */
  49344. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49345. defines["SPOTLIGHT" + lightIndex] = true;
  49346. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49347. };
  49348. __decorate([
  49349. BABYLON.serialize()
  49350. ], SpotLight.prototype, "angle", null);
  49351. __decorate([
  49352. BABYLON.serialize()
  49353. ], SpotLight.prototype, "innerAngle", null);
  49354. __decorate([
  49355. BABYLON.serialize()
  49356. ], SpotLight.prototype, "shadowAngleScale", null);
  49357. __decorate([
  49358. BABYLON.serialize()
  49359. ], SpotLight.prototype, "exponent", void 0);
  49360. __decorate([
  49361. BABYLON.serialize()
  49362. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49363. __decorate([
  49364. BABYLON.serialize()
  49365. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49366. __decorate([
  49367. BABYLON.serialize()
  49368. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49369. __decorate([
  49370. BABYLON.serializeAsTexture("projectedLightTexture")
  49371. ], SpotLight.prototype, "_projectionTexture", void 0);
  49372. return SpotLight;
  49373. }(BABYLON.ShadowLight));
  49374. BABYLON.SpotLight = SpotLight;
  49375. })(BABYLON || (BABYLON = {}));
  49376. //# sourceMappingURL=babylon.spotLight.js.map
  49377. var BABYLON;
  49378. (function (BABYLON) {
  49379. /**
  49380. * Class used to override all child animations of a given target
  49381. */
  49382. var AnimationPropertiesOverride = /** @class */ (function () {
  49383. function AnimationPropertiesOverride() {
  49384. /**
  49385. * Gets or sets a value indicating if animation blending must be used
  49386. */
  49387. this.enableBlending = false;
  49388. /**
  49389. * Gets or sets the blending speed to use when enableBlending is true
  49390. */
  49391. this.blendingSpeed = 0.01;
  49392. /**
  49393. * Gets or sets the default loop mode to use
  49394. */
  49395. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49396. }
  49397. return AnimationPropertiesOverride;
  49398. }());
  49399. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49400. })(BABYLON || (BABYLON = {}));
  49401. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49402. var BABYLON;
  49403. (function (BABYLON) {
  49404. /**
  49405. * Represents the range of an animation
  49406. */
  49407. var AnimationRange = /** @class */ (function () {
  49408. /**
  49409. * Initializes the range of an animation
  49410. * @param name The name of the animation range
  49411. * @param from The starting frame of the animation
  49412. * @param to The ending frame of the animation
  49413. */
  49414. function AnimationRange(
  49415. /**The name of the animation range**/
  49416. name,
  49417. /**The starting frame of the animation */
  49418. from,
  49419. /**The ending frame of the animation*/
  49420. to) {
  49421. this.name = name;
  49422. this.from = from;
  49423. this.to = to;
  49424. }
  49425. /**
  49426. * Makes a copy of the animation range
  49427. * @returns A copy of the animation range
  49428. */
  49429. AnimationRange.prototype.clone = function () {
  49430. return new AnimationRange(this.name, this.from, this.to);
  49431. };
  49432. return AnimationRange;
  49433. }());
  49434. BABYLON.AnimationRange = AnimationRange;
  49435. /**
  49436. * Composed of a frame, and an action function
  49437. */
  49438. var AnimationEvent = /** @class */ (function () {
  49439. /**
  49440. * Initializes the animation event
  49441. * @param frame The frame for which the event is triggered
  49442. * @param action The event to perform when triggered
  49443. * @param onlyOnce Specifies if the event should be triggered only once
  49444. */
  49445. function AnimationEvent(
  49446. /** The frame for which the event is triggered **/
  49447. frame,
  49448. /** The event to perform when triggered **/
  49449. action,
  49450. /** Specifies if the event should be triggered only once**/
  49451. onlyOnce) {
  49452. this.frame = frame;
  49453. this.action = action;
  49454. this.onlyOnce = onlyOnce;
  49455. /**
  49456. * Specifies if the animation event is done
  49457. */
  49458. this.isDone = false;
  49459. }
  49460. /** @hidden */
  49461. AnimationEvent.prototype._clone = function () {
  49462. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49463. };
  49464. return AnimationEvent;
  49465. }());
  49466. BABYLON.AnimationEvent = AnimationEvent;
  49467. /**
  49468. * A cursor which tracks a point on a path
  49469. */
  49470. var PathCursor = /** @class */ (function () {
  49471. /**
  49472. * Initializes the path cursor
  49473. * @param path The path to track
  49474. */
  49475. function PathCursor(path) {
  49476. this.path = path;
  49477. /**
  49478. * Stores path cursor callbacks for when an onchange event is triggered
  49479. */
  49480. this._onchange = new Array();
  49481. /**
  49482. * The value of the path cursor
  49483. */
  49484. this.value = 0;
  49485. /**
  49486. * The animation array of the path cursor
  49487. */
  49488. this.animations = new Array();
  49489. }
  49490. /**
  49491. * Gets the cursor point on the path
  49492. * @returns A point on the path cursor at the cursor location
  49493. */
  49494. PathCursor.prototype.getPoint = function () {
  49495. var point = this.path.getPointAtLengthPosition(this.value);
  49496. return new BABYLON.Vector3(point.x, 0, point.y);
  49497. };
  49498. /**
  49499. * Moves the cursor ahead by the step amount
  49500. * @param step The amount to move the cursor forward
  49501. * @returns This path cursor
  49502. */
  49503. PathCursor.prototype.moveAhead = function (step) {
  49504. if (step === void 0) { step = 0.002; }
  49505. this.move(step);
  49506. return this;
  49507. };
  49508. /**
  49509. * Moves the cursor behind by the step amount
  49510. * @param step The amount to move the cursor back
  49511. * @returns This path cursor
  49512. */
  49513. PathCursor.prototype.moveBack = function (step) {
  49514. if (step === void 0) { step = 0.002; }
  49515. this.move(-step);
  49516. return this;
  49517. };
  49518. /**
  49519. * Moves the cursor by the step amount
  49520. * If the step amount is greater than one, an exception is thrown
  49521. * @param step The amount to move the cursor
  49522. * @returns This path cursor
  49523. */
  49524. PathCursor.prototype.move = function (step) {
  49525. if (Math.abs(step) > 1) {
  49526. throw "step size should be less than 1.";
  49527. }
  49528. this.value += step;
  49529. this.ensureLimits();
  49530. this.raiseOnChange();
  49531. return this;
  49532. };
  49533. /**
  49534. * Ensures that the value is limited between zero and one
  49535. * @returns This path cursor
  49536. */
  49537. PathCursor.prototype.ensureLimits = function () {
  49538. while (this.value > 1) {
  49539. this.value -= 1;
  49540. }
  49541. while (this.value < 0) {
  49542. this.value += 1;
  49543. }
  49544. return this;
  49545. };
  49546. /**
  49547. * Runs onchange callbacks on change (used by the animation engine)
  49548. * @returns This path cursor
  49549. */
  49550. PathCursor.prototype.raiseOnChange = function () {
  49551. var _this = this;
  49552. this._onchange.forEach(function (f) { return f(_this); });
  49553. return this;
  49554. };
  49555. /**
  49556. * Executes a function on change
  49557. * @param f A path cursor onchange callback
  49558. * @returns This path cursor
  49559. */
  49560. PathCursor.prototype.onchange = function (f) {
  49561. this._onchange.push(f);
  49562. return this;
  49563. };
  49564. return PathCursor;
  49565. }());
  49566. BABYLON.PathCursor = PathCursor;
  49567. /**
  49568. * Enum for the animation key frame interpolation type
  49569. */
  49570. var AnimationKeyInterpolation;
  49571. (function (AnimationKeyInterpolation) {
  49572. /**
  49573. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49574. */
  49575. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49576. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49577. /**
  49578. * Class used to store any kind of animation
  49579. */
  49580. var Animation = /** @class */ (function () {
  49581. /**
  49582. * Initializes the animation
  49583. * @param name Name of the animation
  49584. * @param targetProperty Property to animate
  49585. * @param framePerSecond The frames per second of the animation
  49586. * @param dataType The data type of the animation
  49587. * @param loopMode The loop mode of the animation
  49588. * @param enableBlendings Specifies if blending should be enabled
  49589. */
  49590. function Animation(
  49591. /**Name of the animation */
  49592. name,
  49593. /**Property to animate */
  49594. targetProperty,
  49595. /**The frames per second of the animation */
  49596. framePerSecond,
  49597. /**The data type of the animation */
  49598. dataType,
  49599. /**The loop mode of the animation */
  49600. loopMode,
  49601. /**Specifies if blending should be enabled */
  49602. enableBlending) {
  49603. this.name = name;
  49604. this.targetProperty = targetProperty;
  49605. this.framePerSecond = framePerSecond;
  49606. this.dataType = dataType;
  49607. this.loopMode = loopMode;
  49608. this.enableBlending = enableBlending;
  49609. /**
  49610. * @hidden Internal use only
  49611. */
  49612. this._runtimeAnimations = new Array();
  49613. /**
  49614. * The set of event that will be linked to this animation
  49615. */
  49616. this._events = new Array();
  49617. /**
  49618. * Stores the blending speed of the animation
  49619. */
  49620. this.blendingSpeed = 0.01;
  49621. /**
  49622. * Stores the animation ranges for the animation
  49623. */
  49624. this._ranges = {};
  49625. this.targetPropertyPath = targetProperty.split(".");
  49626. this.dataType = dataType;
  49627. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49628. }
  49629. /**
  49630. * @hidden Internal use
  49631. */
  49632. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49633. var dataType = undefined;
  49634. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49635. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49636. }
  49637. else if (from instanceof BABYLON.Quaternion) {
  49638. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49639. }
  49640. else if (from instanceof BABYLON.Vector3) {
  49641. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49642. }
  49643. else if (from instanceof BABYLON.Vector2) {
  49644. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49645. }
  49646. else if (from instanceof BABYLON.Color3) {
  49647. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49648. }
  49649. else if (from instanceof BABYLON.Size) {
  49650. dataType = Animation.ANIMATIONTYPE_SIZE;
  49651. }
  49652. if (dataType == undefined) {
  49653. return null;
  49654. }
  49655. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49656. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49657. animation.setKeys(keys);
  49658. if (easingFunction !== undefined) {
  49659. animation.setEasingFunction(easingFunction);
  49660. }
  49661. return animation;
  49662. };
  49663. /**
  49664. * Sets up an animation
  49665. * @param property The property to animate
  49666. * @param animationType The animation type to apply
  49667. * @param framePerSecond The frames per second of the animation
  49668. * @param easingFunction The easing function used in the animation
  49669. * @returns The created animation
  49670. */
  49671. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49672. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49673. animation.setEasingFunction(easingFunction);
  49674. return animation;
  49675. };
  49676. /**
  49677. * Create and start an animation on a node
  49678. * @param name defines the name of the global animation that will be run on all nodes
  49679. * @param node defines the root node where the animation will take place
  49680. * @param targetProperty defines property to animate
  49681. * @param framePerSecond defines the number of frame per second yo use
  49682. * @param totalFrame defines the number of frames in total
  49683. * @param from defines the initial value
  49684. * @param to defines the final value
  49685. * @param loopMode defines which loop mode you want to use (off by default)
  49686. * @param easingFunction defines the easing function to use (linear by default)
  49687. * @param onAnimationEnd defines the callback to call when animation end
  49688. * @returns the animatable created for this animation
  49689. */
  49690. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49691. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49692. if (!animation) {
  49693. return null;
  49694. }
  49695. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49696. };
  49697. /**
  49698. * Create and start an animation on a node and its descendants
  49699. * @param name defines the name of the global animation that will be run on all nodes
  49700. * @param node defines the root node where the animation will take place
  49701. * @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
  49702. * @param targetProperty defines property to animate
  49703. * @param framePerSecond defines the number of frame per second to use
  49704. * @param totalFrame defines the number of frames in total
  49705. * @param from defines the initial value
  49706. * @param to defines the final value
  49707. * @param loopMode defines which loop mode you want to use (off by default)
  49708. * @param easingFunction defines the easing function to use (linear by default)
  49709. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49710. * @returns the list of animatables created for all nodes
  49711. * @example https://www.babylonjs-playground.com/#MH0VLI
  49712. */
  49713. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49714. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49715. if (!animation) {
  49716. return null;
  49717. }
  49718. var scene = node.getScene();
  49719. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49720. };
  49721. /**
  49722. * Creates a new animation, merges it with the existing animations and starts it
  49723. * @param name Name of the animation
  49724. * @param node Node which contains the scene that begins the animations
  49725. * @param targetProperty Specifies which property to animate
  49726. * @param framePerSecond The frames per second of the animation
  49727. * @param totalFrame The total number of frames
  49728. * @param from The frame at the beginning of the animation
  49729. * @param to The frame at the end of the animation
  49730. * @param loopMode Specifies the loop mode of the animation
  49731. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49732. * @param onAnimationEnd Callback to run once the animation is complete
  49733. * @returns Nullable animation
  49734. */
  49735. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49736. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49737. if (!animation) {
  49738. return null;
  49739. }
  49740. node.animations.push(animation);
  49741. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49742. };
  49743. /**
  49744. * Transition property of an host to the target Value
  49745. * @param property The property to transition
  49746. * @param targetValue The target Value of the property
  49747. * @param host The object where the property to animate belongs
  49748. * @param scene Scene used to run the animation
  49749. * @param frameRate Framerate (in frame/s) to use
  49750. * @param transition The transition type we want to use
  49751. * @param duration The duration of the animation, in milliseconds
  49752. * @param onAnimationEnd Callback trigger at the end of the animation
  49753. * @returns Nullable animation
  49754. */
  49755. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49756. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49757. if (duration <= 0) {
  49758. host[property] = targetValue;
  49759. if (onAnimationEnd) {
  49760. onAnimationEnd();
  49761. }
  49762. return null;
  49763. }
  49764. var endFrame = frameRate * (duration / 1000);
  49765. transition.setKeys([{
  49766. frame: 0,
  49767. value: host[property].clone ? host[property].clone() : host[property]
  49768. },
  49769. {
  49770. frame: endFrame,
  49771. value: targetValue
  49772. }]);
  49773. if (!host.animations) {
  49774. host.animations = [];
  49775. }
  49776. host.animations.push(transition);
  49777. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49778. animation.onAnimationEnd = onAnimationEnd;
  49779. return animation;
  49780. };
  49781. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49782. /**
  49783. * Return the array of runtime animations currently using this animation
  49784. */
  49785. get: function () {
  49786. return this._runtimeAnimations;
  49787. },
  49788. enumerable: true,
  49789. configurable: true
  49790. });
  49791. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49792. /**
  49793. * Specifies if any of the runtime animations are currently running
  49794. */
  49795. get: function () {
  49796. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49797. var runtimeAnimation = _a[_i];
  49798. if (!runtimeAnimation.isStopped) {
  49799. return true;
  49800. }
  49801. }
  49802. return false;
  49803. },
  49804. enumerable: true,
  49805. configurable: true
  49806. });
  49807. // Methods
  49808. /**
  49809. * Converts the animation to a string
  49810. * @param fullDetails support for multiple levels of logging within scene loading
  49811. * @returns String form of the animation
  49812. */
  49813. Animation.prototype.toString = function (fullDetails) {
  49814. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49815. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49816. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49817. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49818. if (fullDetails) {
  49819. ret += ", Ranges: {";
  49820. var first = true;
  49821. for (var name in this._ranges) {
  49822. if (first) {
  49823. ret += ", ";
  49824. first = false;
  49825. }
  49826. ret += name;
  49827. }
  49828. ret += "}";
  49829. }
  49830. return ret;
  49831. };
  49832. /**
  49833. * Add an event to this animation
  49834. * @param event Event to add
  49835. */
  49836. Animation.prototype.addEvent = function (event) {
  49837. this._events.push(event);
  49838. };
  49839. /**
  49840. * Remove all events found at the given frame
  49841. * @param frame The frame to remove events from
  49842. */
  49843. Animation.prototype.removeEvents = function (frame) {
  49844. for (var index = 0; index < this._events.length; index++) {
  49845. if (this._events[index].frame === frame) {
  49846. this._events.splice(index, 1);
  49847. index--;
  49848. }
  49849. }
  49850. };
  49851. /**
  49852. * Retrieves all the events from the animation
  49853. * @returns Events from the animation
  49854. */
  49855. Animation.prototype.getEvents = function () {
  49856. return this._events;
  49857. };
  49858. /**
  49859. * Creates an animation range
  49860. * @param name Name of the animation range
  49861. * @param from Starting frame of the animation range
  49862. * @param to Ending frame of the animation
  49863. */
  49864. Animation.prototype.createRange = function (name, from, to) {
  49865. // check name not already in use; could happen for bones after serialized
  49866. if (!this._ranges[name]) {
  49867. this._ranges[name] = new AnimationRange(name, from, to);
  49868. }
  49869. };
  49870. /**
  49871. * Deletes an animation range by name
  49872. * @param name Name of the animation range to delete
  49873. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49874. */
  49875. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49876. if (deleteFrames === void 0) { deleteFrames = true; }
  49877. var range = this._ranges[name];
  49878. if (!range) {
  49879. return;
  49880. }
  49881. if (deleteFrames) {
  49882. var from = range.from;
  49883. var to = range.to;
  49884. // this loop MUST go high to low for multiple splices to work
  49885. for (var key = this._keys.length - 1; key >= 0; key--) {
  49886. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49887. this._keys.splice(key, 1);
  49888. }
  49889. }
  49890. }
  49891. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49892. };
  49893. /**
  49894. * Gets the animation range by name, or null if not defined
  49895. * @param name Name of the animation range
  49896. * @returns Nullable animation range
  49897. */
  49898. Animation.prototype.getRange = function (name) {
  49899. return this._ranges[name];
  49900. };
  49901. /**
  49902. * Gets the key frames from the animation
  49903. * @returns The key frames of the animation
  49904. */
  49905. Animation.prototype.getKeys = function () {
  49906. return this._keys;
  49907. };
  49908. /**
  49909. * Gets the highest frame rate of the animation
  49910. * @returns Highest frame rate of the animation
  49911. */
  49912. Animation.prototype.getHighestFrame = function () {
  49913. var ret = 0;
  49914. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49915. if (ret < this._keys[key].frame) {
  49916. ret = this._keys[key].frame;
  49917. }
  49918. }
  49919. return ret;
  49920. };
  49921. /**
  49922. * Gets the easing function of the animation
  49923. * @returns Easing function of the animation
  49924. */
  49925. Animation.prototype.getEasingFunction = function () {
  49926. return this._easingFunction;
  49927. };
  49928. /**
  49929. * Sets the easing function of the animation
  49930. * @param easingFunction A custom mathematical formula for animation
  49931. */
  49932. Animation.prototype.setEasingFunction = function (easingFunction) {
  49933. this._easingFunction = easingFunction;
  49934. };
  49935. /**
  49936. * Interpolates a scalar linearly
  49937. * @param startValue Start value of the animation curve
  49938. * @param endValue End value of the animation curve
  49939. * @param gradient Scalar amount to interpolate
  49940. * @returns Interpolated scalar value
  49941. */
  49942. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49943. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49944. };
  49945. /**
  49946. * Interpolates a scalar cubically
  49947. * @param startValue Start value of the animation curve
  49948. * @param outTangent End tangent of the animation
  49949. * @param endValue End value of the animation curve
  49950. * @param inTangent Start tangent of the animation curve
  49951. * @param gradient Scalar amount to interpolate
  49952. * @returns Interpolated scalar value
  49953. */
  49954. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49955. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49956. };
  49957. /**
  49958. * Interpolates a quaternion using a spherical linear interpolation
  49959. * @param startValue Start value of the animation curve
  49960. * @param endValue End value of the animation curve
  49961. * @param gradient Scalar amount to interpolate
  49962. * @returns Interpolated quaternion value
  49963. */
  49964. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49965. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49966. };
  49967. /**
  49968. * Interpolates a quaternion cubically
  49969. * @param startValue Start value of the animation curve
  49970. * @param outTangent End tangent of the animation curve
  49971. * @param endValue End value of the animation curve
  49972. * @param inTangent Start tangent of the animation curve
  49973. * @param gradient Scalar amount to interpolate
  49974. * @returns Interpolated quaternion value
  49975. */
  49976. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49977. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49978. };
  49979. /**
  49980. * Interpolates a Vector3 linearl
  49981. * @param startValue Start value of the animation curve
  49982. * @param endValue End value of the animation curve
  49983. * @param gradient Scalar amount to interpolate
  49984. * @returns Interpolated scalar value
  49985. */
  49986. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49987. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49988. };
  49989. /**
  49990. * Interpolates a Vector3 cubically
  49991. * @param startValue Start value of the animation curve
  49992. * @param outTangent End tangent of the animation
  49993. * @param endValue End value of the animation curve
  49994. * @param inTangent Start tangent of the animation curve
  49995. * @param gradient Scalar amount to interpolate
  49996. * @returns InterpolatedVector3 value
  49997. */
  49998. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49999. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50000. };
  50001. /**
  50002. * Interpolates a Vector2 linearly
  50003. * @param startValue Start value of the animation curve
  50004. * @param endValue End value of the animation curve
  50005. * @param gradient Scalar amount to interpolate
  50006. * @returns Interpolated Vector2 value
  50007. */
  50008. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50009. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50010. };
  50011. /**
  50012. * Interpolates a Vector2 cubically
  50013. * @param startValue Start value of the animation curve
  50014. * @param outTangent End tangent of the animation
  50015. * @param endValue End value of the animation curve
  50016. * @param inTangent Start tangent of the animation curve
  50017. * @param gradient Scalar amount to interpolate
  50018. * @returns Interpolated Vector2 value
  50019. */
  50020. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50021. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50022. };
  50023. /**
  50024. * Interpolates a size linearly
  50025. * @param startValue Start value of the animation curve
  50026. * @param endValue End value of the animation curve
  50027. * @param gradient Scalar amount to interpolate
  50028. * @returns Interpolated Size value
  50029. */
  50030. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50031. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50032. };
  50033. /**
  50034. * Interpolates a Color3 linearly
  50035. * @param startValue Start value of the animation curve
  50036. * @param endValue End value of the animation curve
  50037. * @param gradient Scalar amount to interpolate
  50038. * @returns Interpolated Color3 value
  50039. */
  50040. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50041. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50042. };
  50043. /**
  50044. * @hidden Internal use only
  50045. */
  50046. Animation.prototype._getKeyValue = function (value) {
  50047. if (typeof value === "function") {
  50048. return value();
  50049. }
  50050. return value;
  50051. };
  50052. /**
  50053. * @hidden Internal use only
  50054. */
  50055. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50056. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50057. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50058. }
  50059. var keys = this.getKeys();
  50060. // Try to get a hash to find the right key
  50061. 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));
  50062. if (keys[startKeyIndex].frame >= currentFrame) {
  50063. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50064. startKeyIndex--;
  50065. }
  50066. }
  50067. for (var key = startKeyIndex; key < keys.length; key++) {
  50068. var endKey = keys[key + 1];
  50069. if (endKey.frame >= currentFrame) {
  50070. var startKey = keys[key];
  50071. var startValue = this._getKeyValue(startKey.value);
  50072. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50073. return startValue;
  50074. }
  50075. var endValue = this._getKeyValue(endKey.value);
  50076. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50077. var frameDelta = endKey.frame - startKey.frame;
  50078. // gradient : percent of currentFrame between the frame inf and the frame sup
  50079. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50080. // check for easingFunction and correction of gradient
  50081. var easingFunction = this.getEasingFunction();
  50082. if (easingFunction != null) {
  50083. gradient = easingFunction.ease(gradient);
  50084. }
  50085. switch (this.dataType) {
  50086. // Float
  50087. case Animation.ANIMATIONTYPE_FLOAT:
  50088. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50089. switch (loopMode) {
  50090. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50091. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50092. return floatValue;
  50093. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50094. return offsetValue * repeatCount + floatValue;
  50095. }
  50096. break;
  50097. // Quaternion
  50098. case Animation.ANIMATIONTYPE_QUATERNION:
  50099. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50100. switch (loopMode) {
  50101. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50102. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50103. return quatValue;
  50104. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50105. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50106. }
  50107. return quatValue;
  50108. // Vector3
  50109. case Animation.ANIMATIONTYPE_VECTOR3:
  50110. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50111. switch (loopMode) {
  50112. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50113. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50114. return vec3Value;
  50115. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50116. return vec3Value.add(offsetValue.scale(repeatCount));
  50117. }
  50118. // Vector2
  50119. case Animation.ANIMATIONTYPE_VECTOR2:
  50120. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50121. switch (loopMode) {
  50122. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50123. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50124. return vec2Value;
  50125. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50126. return vec2Value.add(offsetValue.scale(repeatCount));
  50127. }
  50128. // Size
  50129. case Animation.ANIMATIONTYPE_SIZE:
  50130. switch (loopMode) {
  50131. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50132. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50133. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50134. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50135. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50136. }
  50137. // Color3
  50138. case Animation.ANIMATIONTYPE_COLOR3:
  50139. switch (loopMode) {
  50140. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50141. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50142. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50143. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50144. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50145. }
  50146. // Matrix
  50147. case Animation.ANIMATIONTYPE_MATRIX:
  50148. switch (loopMode) {
  50149. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50150. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50151. if (Animation.AllowMatricesInterpolation) {
  50152. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50153. }
  50154. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50155. return startValue;
  50156. }
  50157. default:
  50158. break;
  50159. }
  50160. break;
  50161. }
  50162. }
  50163. return this._getKeyValue(keys[keys.length - 1].value);
  50164. };
  50165. /**
  50166. * Defines the function to use to interpolate matrices
  50167. * @param startValue defines the start matrix
  50168. * @param endValue defines the end matrix
  50169. * @param gradient defines the gradient between both matrices
  50170. * @param result defines an optional target matrix where to store the interpolation
  50171. * @returns the interpolated matrix
  50172. */
  50173. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50174. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50175. if (result) {
  50176. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50177. return result;
  50178. }
  50179. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50180. }
  50181. if (result) {
  50182. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50183. return result;
  50184. }
  50185. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50186. };
  50187. /**
  50188. * Makes a copy of the animation
  50189. * @returns Cloned animation
  50190. */
  50191. Animation.prototype.clone = function () {
  50192. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50193. clone.enableBlending = this.enableBlending;
  50194. clone.blendingSpeed = this.blendingSpeed;
  50195. if (this._keys) {
  50196. clone.setKeys(this._keys);
  50197. }
  50198. if (this._ranges) {
  50199. clone._ranges = {};
  50200. for (var name in this._ranges) {
  50201. var range = this._ranges[name];
  50202. if (!range) {
  50203. continue;
  50204. }
  50205. clone._ranges[name] = range.clone();
  50206. }
  50207. }
  50208. return clone;
  50209. };
  50210. /**
  50211. * Sets the key frames of the animation
  50212. * @param values The animation key frames to set
  50213. */
  50214. Animation.prototype.setKeys = function (values) {
  50215. this._keys = values.slice(0);
  50216. };
  50217. /**
  50218. * Serializes the animation to an object
  50219. * @returns Serialized object
  50220. */
  50221. Animation.prototype.serialize = function () {
  50222. var serializationObject = {};
  50223. serializationObject.name = this.name;
  50224. serializationObject.property = this.targetProperty;
  50225. serializationObject.framePerSecond = this.framePerSecond;
  50226. serializationObject.dataType = this.dataType;
  50227. serializationObject.loopBehavior = this.loopMode;
  50228. serializationObject.enableBlending = this.enableBlending;
  50229. serializationObject.blendingSpeed = this.blendingSpeed;
  50230. var dataType = this.dataType;
  50231. serializationObject.keys = [];
  50232. var keys = this.getKeys();
  50233. for (var index = 0; index < keys.length; index++) {
  50234. var animationKey = keys[index];
  50235. var key = {};
  50236. key.frame = animationKey.frame;
  50237. switch (dataType) {
  50238. case Animation.ANIMATIONTYPE_FLOAT:
  50239. key.values = [animationKey.value];
  50240. break;
  50241. case Animation.ANIMATIONTYPE_QUATERNION:
  50242. case Animation.ANIMATIONTYPE_MATRIX:
  50243. case Animation.ANIMATIONTYPE_VECTOR3:
  50244. case Animation.ANIMATIONTYPE_COLOR3:
  50245. key.values = animationKey.value.asArray();
  50246. break;
  50247. }
  50248. serializationObject.keys.push(key);
  50249. }
  50250. serializationObject.ranges = [];
  50251. for (var name in this._ranges) {
  50252. var source = this._ranges[name];
  50253. if (!source) {
  50254. continue;
  50255. }
  50256. var range = {};
  50257. range.name = name;
  50258. range.from = source.from;
  50259. range.to = source.to;
  50260. serializationObject.ranges.push(range);
  50261. }
  50262. return serializationObject;
  50263. };
  50264. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50265. /**
  50266. * Get the float animation type
  50267. */
  50268. get: function () {
  50269. return Animation._ANIMATIONTYPE_FLOAT;
  50270. },
  50271. enumerable: true,
  50272. configurable: true
  50273. });
  50274. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50275. /**
  50276. * Get the Vector3 animation type
  50277. */
  50278. get: function () {
  50279. return Animation._ANIMATIONTYPE_VECTOR3;
  50280. },
  50281. enumerable: true,
  50282. configurable: true
  50283. });
  50284. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50285. /**
  50286. * Get the Vector2 animation type
  50287. */
  50288. get: function () {
  50289. return Animation._ANIMATIONTYPE_VECTOR2;
  50290. },
  50291. enumerable: true,
  50292. configurable: true
  50293. });
  50294. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50295. /**
  50296. * Get the Size animation type
  50297. */
  50298. get: function () {
  50299. return Animation._ANIMATIONTYPE_SIZE;
  50300. },
  50301. enumerable: true,
  50302. configurable: true
  50303. });
  50304. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50305. /**
  50306. * Get the Quaternion animation type
  50307. */
  50308. get: function () {
  50309. return Animation._ANIMATIONTYPE_QUATERNION;
  50310. },
  50311. enumerable: true,
  50312. configurable: true
  50313. });
  50314. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50315. /**
  50316. * Get the Matrix animation type
  50317. */
  50318. get: function () {
  50319. return Animation._ANIMATIONTYPE_MATRIX;
  50320. },
  50321. enumerable: true,
  50322. configurable: true
  50323. });
  50324. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50325. /**
  50326. * Get the Color3 animation type
  50327. */
  50328. get: function () {
  50329. return Animation._ANIMATIONTYPE_COLOR3;
  50330. },
  50331. enumerable: true,
  50332. configurable: true
  50333. });
  50334. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50335. /**
  50336. * Get the Relative Loop Mode
  50337. */
  50338. get: function () {
  50339. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50340. },
  50341. enumerable: true,
  50342. configurable: true
  50343. });
  50344. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50345. /**
  50346. * Get the Cycle Loop Mode
  50347. */
  50348. get: function () {
  50349. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50350. },
  50351. enumerable: true,
  50352. configurable: true
  50353. });
  50354. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50355. /**
  50356. * Get the Constant Loop Mode
  50357. */
  50358. get: function () {
  50359. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50360. },
  50361. enumerable: true,
  50362. configurable: true
  50363. });
  50364. /** @hidden */
  50365. Animation._UniversalLerp = function (left, right, amount) {
  50366. var constructor = left.constructor;
  50367. if (constructor.Lerp) { // Lerp supported
  50368. return constructor.Lerp(left, right, amount);
  50369. }
  50370. else if (constructor.Slerp) { // Slerp supported
  50371. return constructor.Slerp(left, right, amount);
  50372. }
  50373. else if (left.toFixed) { // Number
  50374. return left * (1.0 - amount) + amount * right;
  50375. }
  50376. else { // Blending not supported
  50377. return right;
  50378. }
  50379. };
  50380. /**
  50381. * Parses an animation object and creates an animation
  50382. * @param parsedAnimation Parsed animation object
  50383. * @returns Animation object
  50384. */
  50385. Animation.Parse = function (parsedAnimation) {
  50386. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50387. var dataType = parsedAnimation.dataType;
  50388. var keys = [];
  50389. var data;
  50390. var index;
  50391. if (parsedAnimation.enableBlending) {
  50392. animation.enableBlending = parsedAnimation.enableBlending;
  50393. }
  50394. if (parsedAnimation.blendingSpeed) {
  50395. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50396. }
  50397. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50398. var key = parsedAnimation.keys[index];
  50399. var inTangent;
  50400. var outTangent;
  50401. switch (dataType) {
  50402. case Animation.ANIMATIONTYPE_FLOAT:
  50403. data = key.values[0];
  50404. if (key.values.length >= 1) {
  50405. inTangent = key.values[1];
  50406. }
  50407. if (key.values.length >= 2) {
  50408. outTangent = key.values[2];
  50409. }
  50410. break;
  50411. case Animation.ANIMATIONTYPE_QUATERNION:
  50412. data = BABYLON.Quaternion.FromArray(key.values);
  50413. if (key.values.length >= 8) {
  50414. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50415. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50416. inTangent = _inTangent;
  50417. }
  50418. }
  50419. if (key.values.length >= 12) {
  50420. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50421. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50422. outTangent = _outTangent;
  50423. }
  50424. }
  50425. break;
  50426. case Animation.ANIMATIONTYPE_MATRIX:
  50427. data = BABYLON.Matrix.FromArray(key.values);
  50428. break;
  50429. case Animation.ANIMATIONTYPE_COLOR3:
  50430. data = BABYLON.Color3.FromArray(key.values);
  50431. break;
  50432. case Animation.ANIMATIONTYPE_VECTOR3:
  50433. default:
  50434. data = BABYLON.Vector3.FromArray(key.values);
  50435. break;
  50436. }
  50437. var keyData = {};
  50438. keyData.frame = key.frame;
  50439. keyData.value = data;
  50440. if (inTangent != undefined) {
  50441. keyData.inTangent = inTangent;
  50442. }
  50443. if (outTangent != undefined) {
  50444. keyData.outTangent = outTangent;
  50445. }
  50446. keys.push(keyData);
  50447. }
  50448. animation.setKeys(keys);
  50449. if (parsedAnimation.ranges) {
  50450. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50451. data = parsedAnimation.ranges[index];
  50452. animation.createRange(data.name, data.from, data.to);
  50453. }
  50454. }
  50455. return animation;
  50456. };
  50457. /**
  50458. * Appends the serialized animations from the source animations
  50459. * @param source Source containing the animations
  50460. * @param destination Target to store the animations
  50461. */
  50462. Animation.AppendSerializedAnimations = function (source, destination) {
  50463. if (source.animations) {
  50464. destination.animations = [];
  50465. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50466. var animation = source.animations[animationIndex];
  50467. destination.animations.push(animation.serialize());
  50468. }
  50469. }
  50470. };
  50471. /**
  50472. * Use matrix interpolation instead of using direct key value when animating matrices
  50473. */
  50474. Animation.AllowMatricesInterpolation = false;
  50475. /**
  50476. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50477. */
  50478. Animation.AllowMatrixDecomposeForInterpolation = true;
  50479. // Statics
  50480. /**
  50481. * Float animation type
  50482. */
  50483. Animation._ANIMATIONTYPE_FLOAT = 0;
  50484. /**
  50485. * Vector3 animation type
  50486. */
  50487. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50488. /**
  50489. * Quaternion animation type
  50490. */
  50491. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50492. /**
  50493. * Matrix animation type
  50494. */
  50495. Animation._ANIMATIONTYPE_MATRIX = 3;
  50496. /**
  50497. * Color3 animation type
  50498. */
  50499. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50500. /**
  50501. * Vector2 animation type
  50502. */
  50503. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50504. /**
  50505. * Size animation type
  50506. */
  50507. Animation._ANIMATIONTYPE_SIZE = 6;
  50508. /**
  50509. * Relative Loop Mode
  50510. */
  50511. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50512. /**
  50513. * Cycle Loop Mode
  50514. */
  50515. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50516. /**
  50517. * Constant Loop Mode
  50518. */
  50519. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50520. return Animation;
  50521. }());
  50522. BABYLON.Animation = Animation;
  50523. })(BABYLON || (BABYLON = {}));
  50524. //# sourceMappingURL=babylon.animation.js.map
  50525. var BABYLON;
  50526. (function (BABYLON) {
  50527. /**
  50528. * This class defines the direct association between an animation and a target
  50529. */
  50530. var TargetedAnimation = /** @class */ (function () {
  50531. function TargetedAnimation() {
  50532. }
  50533. return TargetedAnimation;
  50534. }());
  50535. BABYLON.TargetedAnimation = TargetedAnimation;
  50536. /**
  50537. * Use this class to create coordinated animations on multiple targets
  50538. */
  50539. var AnimationGroup = /** @class */ (function () {
  50540. function AnimationGroup(name, scene) {
  50541. if (scene === void 0) { scene = null; }
  50542. this.name = name;
  50543. this._targetedAnimations = new Array();
  50544. this._animatables = new Array();
  50545. this._from = Number.MAX_VALUE;
  50546. this._to = -Number.MAX_VALUE;
  50547. this._speedRatio = 1;
  50548. this.onAnimationEndObservable = new BABYLON.Observable();
  50549. /**
  50550. * This observable will notify when all animations have ended.
  50551. */
  50552. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50553. /**
  50554. * This observable will notify when all animations have paused.
  50555. */
  50556. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50557. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50558. this._scene.animationGroups.push(this);
  50559. }
  50560. Object.defineProperty(AnimationGroup.prototype, "from", {
  50561. /**
  50562. * Gets the first frame
  50563. */
  50564. get: function () {
  50565. return this._from;
  50566. },
  50567. enumerable: true,
  50568. configurable: true
  50569. });
  50570. Object.defineProperty(AnimationGroup.prototype, "to", {
  50571. /**
  50572. * Gets the last frame
  50573. */
  50574. get: function () {
  50575. return this._to;
  50576. },
  50577. enumerable: true,
  50578. configurable: true
  50579. });
  50580. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50581. /**
  50582. * Define if the animations are started
  50583. */
  50584. get: function () {
  50585. return this._isStarted;
  50586. },
  50587. enumerable: true,
  50588. configurable: true
  50589. });
  50590. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50591. /**
  50592. * Gets or sets the speed ratio to use for all animations
  50593. */
  50594. get: function () {
  50595. return this._speedRatio;
  50596. },
  50597. /**
  50598. * Gets or sets the speed ratio to use for all animations
  50599. */
  50600. set: function (value) {
  50601. if (this._speedRatio === value) {
  50602. return;
  50603. }
  50604. this._speedRatio = value;
  50605. for (var index = 0; index < this._animatables.length; index++) {
  50606. var animatable = this._animatables[index];
  50607. animatable.speedRatio = this._speedRatio;
  50608. }
  50609. },
  50610. enumerable: true,
  50611. configurable: true
  50612. });
  50613. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50614. /**
  50615. * Gets the targeted animations for this animation group
  50616. */
  50617. get: function () {
  50618. return this._targetedAnimations;
  50619. },
  50620. enumerable: true,
  50621. configurable: true
  50622. });
  50623. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50624. /**
  50625. * returning the list of animatables controlled by this animation group.
  50626. */
  50627. get: function () {
  50628. return this._animatables;
  50629. },
  50630. enumerable: true,
  50631. configurable: true
  50632. });
  50633. /**
  50634. * Add an animation (with its target) in the group
  50635. * @param animation defines the animation we want to add
  50636. * @param target defines the target of the animation
  50637. * @returns the {BABYLON.TargetedAnimation} object
  50638. */
  50639. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50640. var targetedAnimation = {
  50641. animation: animation,
  50642. target: target
  50643. };
  50644. var keys = animation.getKeys();
  50645. if (this._from > keys[0].frame) {
  50646. this._from = keys[0].frame;
  50647. }
  50648. if (this._to < keys[keys.length - 1].frame) {
  50649. this._to = keys[keys.length - 1].frame;
  50650. }
  50651. this._targetedAnimations.push(targetedAnimation);
  50652. return targetedAnimation;
  50653. };
  50654. /**
  50655. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50656. * It can add constant keys at begin or end
  50657. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50658. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50659. */
  50660. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50661. if (beginFrame === void 0) { beginFrame = null; }
  50662. if (endFrame === void 0) { endFrame = null; }
  50663. if (beginFrame == null)
  50664. beginFrame = this._from;
  50665. if (endFrame == null)
  50666. endFrame = this._to;
  50667. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50668. var targetedAnimation = this._targetedAnimations[index];
  50669. var keys = targetedAnimation.animation.getKeys();
  50670. var startKey = keys[0];
  50671. var endKey = keys[keys.length - 1];
  50672. if (startKey.frame > beginFrame) {
  50673. var newKey = {
  50674. frame: beginFrame,
  50675. value: startKey.value,
  50676. inTangent: startKey.inTangent,
  50677. outTangent: startKey.outTangent,
  50678. interpolation: startKey.interpolation
  50679. };
  50680. keys.splice(0, 0, newKey);
  50681. }
  50682. if (endKey.frame < endFrame) {
  50683. var newKey = {
  50684. frame: endFrame,
  50685. value: endKey.value,
  50686. inTangent: endKey.outTangent,
  50687. outTangent: endKey.outTangent,
  50688. interpolation: endKey.interpolation
  50689. };
  50690. keys.push(newKey);
  50691. }
  50692. }
  50693. this._from = beginFrame;
  50694. this._to = endFrame;
  50695. return this;
  50696. };
  50697. /**
  50698. * Start all animations on given targets
  50699. * @param loop defines if animations must loop
  50700. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50701. * @param from defines the from key (optional)
  50702. * @param to defines the to key (optional)
  50703. * @returns the current animation group
  50704. */
  50705. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50706. var _this = this;
  50707. if (loop === void 0) { loop = false; }
  50708. if (speedRatio === void 0) { speedRatio = 1; }
  50709. if (this._isStarted || this._targetedAnimations.length === 0) {
  50710. return this;
  50711. }
  50712. var _loop_1 = function (targetedAnimation) {
  50713. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50714. animatable.onAnimationEnd = function () {
  50715. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50716. _this._checkAnimationGroupEnded(animatable);
  50717. };
  50718. this_1._animatables.push(animatable);
  50719. };
  50720. var this_1 = this;
  50721. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50722. var targetedAnimation = _a[_i];
  50723. _loop_1(targetedAnimation);
  50724. }
  50725. this._speedRatio = speedRatio;
  50726. this._isStarted = true;
  50727. return this;
  50728. };
  50729. /**
  50730. * Pause all animations
  50731. */
  50732. AnimationGroup.prototype.pause = function () {
  50733. if (!this._isStarted) {
  50734. return this;
  50735. }
  50736. for (var index = 0; index < this._animatables.length; index++) {
  50737. var animatable = this._animatables[index];
  50738. animatable.pause();
  50739. }
  50740. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50741. return this;
  50742. };
  50743. /**
  50744. * Play all animations to initial state
  50745. * This function will start() the animations if they were not started or will restart() them if they were paused
  50746. * @param loop defines if animations must loop
  50747. */
  50748. AnimationGroup.prototype.play = function (loop) {
  50749. // only if all animatables are ready and exist
  50750. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50751. if (loop !== undefined) {
  50752. for (var index = 0; index < this._animatables.length; index++) {
  50753. var animatable = this._animatables[index];
  50754. animatable.loopAnimation = loop;
  50755. }
  50756. }
  50757. this.restart();
  50758. }
  50759. else {
  50760. this.stop();
  50761. this.start(loop, this._speedRatio);
  50762. }
  50763. return this;
  50764. };
  50765. /**
  50766. * Reset all animations to initial state
  50767. */
  50768. AnimationGroup.prototype.reset = function () {
  50769. if (!this._isStarted) {
  50770. return this;
  50771. }
  50772. for (var index = 0; index < this._animatables.length; index++) {
  50773. var animatable = this._animatables[index];
  50774. animatable.reset();
  50775. }
  50776. return this;
  50777. };
  50778. /**
  50779. * Restart animations from key 0
  50780. */
  50781. AnimationGroup.prototype.restart = function () {
  50782. if (!this._isStarted) {
  50783. return this;
  50784. }
  50785. for (var index = 0; index < this._animatables.length; index++) {
  50786. var animatable = this._animatables[index];
  50787. animatable.restart();
  50788. }
  50789. return this;
  50790. };
  50791. /**
  50792. * Stop all animations
  50793. */
  50794. AnimationGroup.prototype.stop = function () {
  50795. if (!this._isStarted) {
  50796. return this;
  50797. }
  50798. var list = this._animatables.slice();
  50799. for (var index = 0; index < list.length; index++) {
  50800. list[index].stop();
  50801. }
  50802. this._isStarted = false;
  50803. return this;
  50804. };
  50805. /**
  50806. * Set animation weight for all animatables
  50807. * @param weight defines the weight to use
  50808. * @return the animationGroup
  50809. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50810. */
  50811. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50812. for (var index = 0; index < this._animatables.length; index++) {
  50813. var animatable = this._animatables[index];
  50814. animatable.weight = weight;
  50815. }
  50816. return this;
  50817. };
  50818. /**
  50819. * Synchronize and normalize all animatables with a source animatable
  50820. * @param root defines the root animatable to synchronize with
  50821. * @return the animationGroup
  50822. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50823. */
  50824. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50825. for (var index = 0; index < this._animatables.length; index++) {
  50826. var animatable = this._animatables[index];
  50827. animatable.syncWith(root);
  50828. }
  50829. return this;
  50830. };
  50831. /**
  50832. * Goes to a specific frame in this animation group
  50833. * @param frame the frame number to go to
  50834. * @return the animationGroup
  50835. */
  50836. AnimationGroup.prototype.goToFrame = function (frame) {
  50837. if (!this._isStarted) {
  50838. return this;
  50839. }
  50840. for (var index = 0; index < this._animatables.length; index++) {
  50841. var animatable = this._animatables[index];
  50842. animatable.goToFrame(frame);
  50843. }
  50844. return this;
  50845. };
  50846. /**
  50847. * Dispose all associated resources
  50848. */
  50849. AnimationGroup.prototype.dispose = function () {
  50850. this._targetedAnimations = [];
  50851. this._animatables = [];
  50852. var index = this._scene.animationGroups.indexOf(this);
  50853. if (index > -1) {
  50854. this._scene.animationGroups.splice(index, 1);
  50855. }
  50856. };
  50857. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50858. // animatable should be taken out of the array
  50859. var idx = this._animatables.indexOf(animatable);
  50860. if (idx > -1) {
  50861. this._animatables.splice(idx, 1);
  50862. }
  50863. // all animatables were removed? animation group ended!
  50864. if (this._animatables.length === 0) {
  50865. this._isStarted = false;
  50866. this.onAnimationGroupEndObservable.notifyObservers(this);
  50867. }
  50868. };
  50869. return AnimationGroup;
  50870. }());
  50871. BABYLON.AnimationGroup = AnimationGroup;
  50872. })(BABYLON || (BABYLON = {}));
  50873. //# sourceMappingURL=babylon.animationGroup.js.map
  50874. var BABYLON;
  50875. (function (BABYLON) {
  50876. /**
  50877. * Defines a runtime animation
  50878. */
  50879. var RuntimeAnimation = /** @class */ (function () {
  50880. /**
  50881. * Create a new RuntimeAnimation object
  50882. * @param target defines the target of the animation
  50883. * @param animation defines the source animation object
  50884. * @param scene defines the hosting scene
  50885. * @param host defines the initiating Animatable
  50886. */
  50887. function RuntimeAnimation(target, animation, scene, host) {
  50888. var _this = this;
  50889. this._events = new Array();
  50890. /**
  50891. * The current frame of the runtime animation
  50892. */
  50893. this._currentFrame = 0;
  50894. /**
  50895. * The original value of the runtime animation
  50896. */
  50897. this._originalValue = new Array();
  50898. /**
  50899. * The offsets cache of the runtime animation
  50900. */
  50901. this._offsetsCache = {};
  50902. /**
  50903. * The high limits cache of the runtime animation
  50904. */
  50905. this._highLimitsCache = {};
  50906. /**
  50907. * Specifies if the runtime animation has been stopped
  50908. */
  50909. this._stopped = false;
  50910. /**
  50911. * The blending factor of the runtime animation
  50912. */
  50913. this._blendingFactor = 0;
  50914. /**
  50915. * The target path of the runtime animation
  50916. */
  50917. this._targetPath = "";
  50918. /**
  50919. * The weight of the runtime animation
  50920. */
  50921. this._weight = 1.0;
  50922. /**
  50923. * The ratio offset of the runtime animation
  50924. */
  50925. this._ratioOffset = 0;
  50926. /**
  50927. * The previous delay of the runtime animation
  50928. */
  50929. this._previousDelay = 0;
  50930. /**
  50931. * The previous ratio of the runtime animation
  50932. */
  50933. this._previousRatio = 0;
  50934. this._animation = animation;
  50935. this._target = target;
  50936. this._scene = scene;
  50937. this._host = host;
  50938. animation._runtimeAnimations.push(this);
  50939. // Cloning events locally
  50940. var events = animation.getEvents();
  50941. if (events && events.length > 0) {
  50942. events.forEach(function (e) {
  50943. _this._events.push(e._clone());
  50944. });
  50945. }
  50946. }
  50947. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50948. /**
  50949. * Gets the current frame of the runtime animation
  50950. */
  50951. get: function () {
  50952. return this._currentFrame;
  50953. },
  50954. enumerable: true,
  50955. configurable: true
  50956. });
  50957. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50958. /**
  50959. * Gets the weight of the runtime animation
  50960. */
  50961. get: function () {
  50962. return this._weight;
  50963. },
  50964. enumerable: true,
  50965. configurable: true
  50966. });
  50967. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50968. /**
  50969. * Gets the current value of the runtime animation
  50970. */
  50971. get: function () {
  50972. return this._currentValue;
  50973. },
  50974. enumerable: true,
  50975. configurable: true
  50976. });
  50977. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50978. /**
  50979. * Gets the target path of the runtime animation
  50980. */
  50981. get: function () {
  50982. return this._targetPath;
  50983. },
  50984. enumerable: true,
  50985. configurable: true
  50986. });
  50987. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50988. /**
  50989. * Gets the actual target of the runtime animation
  50990. */
  50991. get: function () {
  50992. return this._activeTarget;
  50993. },
  50994. enumerable: true,
  50995. configurable: true
  50996. });
  50997. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50998. /**
  50999. * Gets the animation from the runtime animation
  51000. */
  51001. get: function () {
  51002. return this._animation;
  51003. },
  51004. enumerable: true,
  51005. configurable: true
  51006. });
  51007. /**
  51008. * Resets the runtime animation to the beginning
  51009. * @param restoreOriginal defines whether to restore the target property to the original value
  51010. */
  51011. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51012. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51013. if (restoreOriginal) {
  51014. if (this._target instanceof Array) {
  51015. var index = 0;
  51016. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51017. var target = _a[_i];
  51018. if (this._originalValue[index] !== undefined) {
  51019. this._setValue(target, this._originalValue[index], -1);
  51020. }
  51021. index++;
  51022. }
  51023. }
  51024. else {
  51025. if (this._originalValue[0] !== undefined) {
  51026. this._setValue(this._target, this._originalValue[0], -1);
  51027. }
  51028. }
  51029. }
  51030. this._offsetsCache = {};
  51031. this._highLimitsCache = {};
  51032. this._currentFrame = 0;
  51033. this._blendingFactor = 0;
  51034. this._originalValue = new Array();
  51035. // Events
  51036. for (var index = 0; index < this._events.length; index++) {
  51037. this._events[index].isDone = false;
  51038. }
  51039. };
  51040. /**
  51041. * Specifies if the runtime animation is stopped
  51042. * @returns Boolean specifying if the runtime animation is stopped
  51043. */
  51044. RuntimeAnimation.prototype.isStopped = function () {
  51045. return this._stopped;
  51046. };
  51047. /**
  51048. * Disposes of the runtime animation
  51049. */
  51050. RuntimeAnimation.prototype.dispose = function () {
  51051. var index = this._animation.runtimeAnimations.indexOf(this);
  51052. if (index > -1) {
  51053. this._animation.runtimeAnimations.splice(index, 1);
  51054. }
  51055. };
  51056. /**
  51057. * Interpolates the animation from the current frame
  51058. * @param currentFrame The frame to interpolate the animation to
  51059. * @param repeatCount The number of times that the animation should loop
  51060. * @param loopMode The type of looping mode to use
  51061. * @param offsetValue Animation offset value
  51062. * @param highLimitValue The high limit value
  51063. * @returns The interpolated value
  51064. */
  51065. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51066. this._currentFrame = currentFrame;
  51067. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51068. this._workValue = BABYLON.Matrix.Zero();
  51069. }
  51070. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51071. };
  51072. /**
  51073. * Apply the interpolated value to the target
  51074. * @param currentValue defines the value computed by the animation
  51075. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51076. */
  51077. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51078. if (weight === void 0) { weight = 1.0; }
  51079. if (this._target instanceof Array) {
  51080. var index = 0;
  51081. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51082. var target = _a[_i];
  51083. this._setValue(target, currentValue, weight, index);
  51084. index++;
  51085. }
  51086. }
  51087. else {
  51088. this._setValue(this._target, currentValue, weight);
  51089. }
  51090. };
  51091. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51092. if (targetIndex === void 0) { targetIndex = 0; }
  51093. // Set value
  51094. var path;
  51095. var destination;
  51096. var targetPropertyPath = this._animation.targetPropertyPath;
  51097. if (targetPropertyPath.length > 1) {
  51098. var property = target[targetPropertyPath[0]];
  51099. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51100. property = property[targetPropertyPath[index]];
  51101. }
  51102. path = targetPropertyPath[targetPropertyPath.length - 1];
  51103. destination = property;
  51104. }
  51105. else {
  51106. path = targetPropertyPath[0];
  51107. destination = target;
  51108. }
  51109. this._targetPath = path;
  51110. this._activeTarget = destination;
  51111. this._weight = weight;
  51112. if (this._originalValue[targetIndex] === undefined) {
  51113. var originalValue = void 0;
  51114. if (destination.getRestPose && path === "_matrix") { // For bones
  51115. originalValue = destination.getRestPose();
  51116. }
  51117. else {
  51118. originalValue = destination[path];
  51119. }
  51120. if (originalValue && originalValue.clone) {
  51121. this._originalValue[targetIndex] = originalValue.clone();
  51122. }
  51123. else {
  51124. this._originalValue[targetIndex] = originalValue;
  51125. }
  51126. }
  51127. // Blending
  51128. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51129. if (enableBlending && this._blendingFactor <= 1.0) {
  51130. if (!this._originalBlendValue) {
  51131. var originalValue = destination[path];
  51132. if (originalValue.clone) {
  51133. this._originalBlendValue = originalValue.clone();
  51134. }
  51135. else {
  51136. this._originalBlendValue = originalValue;
  51137. }
  51138. }
  51139. if (this._originalBlendValue.m) { // Matrix
  51140. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51141. if (this._currentValue) {
  51142. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51143. }
  51144. else {
  51145. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51146. }
  51147. }
  51148. else {
  51149. if (this._currentValue) {
  51150. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51151. }
  51152. else {
  51153. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51154. }
  51155. }
  51156. }
  51157. else {
  51158. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51159. }
  51160. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51161. this._blendingFactor += blendingSpeed;
  51162. }
  51163. else {
  51164. this._currentValue = currentValue;
  51165. }
  51166. if (weight !== -1.0) {
  51167. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51168. }
  51169. else {
  51170. destination[path] = this._currentValue;
  51171. }
  51172. if (target.markAsDirty) {
  51173. target.markAsDirty(this._animation.targetProperty);
  51174. }
  51175. };
  51176. /**
  51177. * Gets the loop pmode of the runtime animation
  51178. * @returns Loop Mode
  51179. */
  51180. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51181. if (this._target && this._target.animationPropertiesOverride) {
  51182. return this._target.animationPropertiesOverride.loopMode;
  51183. }
  51184. return this._animation.loopMode;
  51185. };
  51186. /**
  51187. * Move the current animation to a given frame
  51188. * @param frame defines the frame to move to
  51189. */
  51190. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51191. var keys = this._animation.getKeys();
  51192. if (frame < keys[0].frame) {
  51193. frame = keys[0].frame;
  51194. }
  51195. else if (frame > keys[keys.length - 1].frame) {
  51196. frame = keys[keys.length - 1].frame;
  51197. }
  51198. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51199. this.setValue(currentValue, -1);
  51200. };
  51201. /**
  51202. * @hidden Internal use only
  51203. */
  51204. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51205. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51206. this._ratioOffset = this._previousRatio - newRatio;
  51207. };
  51208. /**
  51209. * Execute the current animation
  51210. * @param delay defines the delay to add to the current frame
  51211. * @param from defines the lower bound of the animation range
  51212. * @param to defines the upper bound of the animation range
  51213. * @param loop defines if the current animation must loop
  51214. * @param speedRatio defines the current speed ratio
  51215. * @param weight defines the weight of the animation (default is -1 so no weight)
  51216. * @returns a boolean indicating if the animation is running
  51217. */
  51218. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51219. if (weight === void 0) { weight = -1.0; }
  51220. var targetPropertyPath = this._animation.targetPropertyPath;
  51221. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51222. this._stopped = true;
  51223. return false;
  51224. }
  51225. var returnValue = true;
  51226. var keys = this._animation.getKeys();
  51227. // Adding a start key at frame 0 if missing
  51228. if (keys[0].frame !== 0) {
  51229. var newKey = { frame: 0, value: keys[0].value };
  51230. keys.splice(0, 0, newKey);
  51231. }
  51232. // Adding a duplicate key when there is only one key at frame zero
  51233. else if (keys.length === 1) {
  51234. var newKey = { frame: 0.001, value: keys[0].value };
  51235. keys.push(newKey);
  51236. }
  51237. // Check limits
  51238. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51239. from = keys[0].frame;
  51240. }
  51241. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51242. to = keys[keys.length - 1].frame;
  51243. }
  51244. //to and from cannot be the same key
  51245. if (from === to) {
  51246. if (from > keys[0].frame) {
  51247. from--;
  51248. }
  51249. else if (to < keys[keys.length - 1].frame) {
  51250. to++;
  51251. }
  51252. }
  51253. // Compute ratio
  51254. var range = to - from;
  51255. var offsetValue;
  51256. // ratio represents the frame delta between from and to
  51257. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51258. var highLimitValue = 0;
  51259. this._previousDelay = delay;
  51260. this._previousRatio = ratio;
  51261. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51262. returnValue = false;
  51263. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51264. }
  51265. else {
  51266. // Get max value if required
  51267. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51268. var keyOffset = to.toString() + from.toString();
  51269. if (!this._offsetsCache[keyOffset]) {
  51270. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51271. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51272. switch (this._animation.dataType) {
  51273. // Float
  51274. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51275. this._offsetsCache[keyOffset] = toValue - fromValue;
  51276. break;
  51277. // Quaternion
  51278. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51279. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51280. break;
  51281. // Vector3
  51282. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51283. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51284. // Vector2
  51285. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51286. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51287. // Size
  51288. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51289. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51290. // Color3
  51291. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51292. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51293. default:
  51294. break;
  51295. }
  51296. this._highLimitsCache[keyOffset] = toValue;
  51297. }
  51298. highLimitValue = this._highLimitsCache[keyOffset];
  51299. offsetValue = this._offsetsCache[keyOffset];
  51300. }
  51301. }
  51302. if (offsetValue === undefined) {
  51303. switch (this._animation.dataType) {
  51304. // Float
  51305. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51306. offsetValue = 0;
  51307. break;
  51308. // Quaternion
  51309. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51310. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51311. break;
  51312. // Vector3
  51313. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51314. offsetValue = BABYLON.Vector3.Zero();
  51315. break;
  51316. // Vector2
  51317. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51318. offsetValue = BABYLON.Vector2.Zero();
  51319. break;
  51320. // Size
  51321. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51322. offsetValue = BABYLON.Size.Zero();
  51323. break;
  51324. // Color3
  51325. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51326. offsetValue = BABYLON.Color3.Black();
  51327. }
  51328. }
  51329. // Compute value
  51330. var repeatCount = (ratio / range) >> 0;
  51331. var currentFrame = returnValue ? from + ratio % range : to;
  51332. // Need to normalize?
  51333. if (this._host && this._host.syncRoot) {
  51334. var syncRoot = this._host.syncRoot;
  51335. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51336. currentFrame = from + (to - from) * hostNormalizedFrame;
  51337. }
  51338. // Reset events if looping
  51339. var events = this._events;
  51340. if (range > 0 && this.currentFrame > currentFrame ||
  51341. range < 0 && this.currentFrame < currentFrame) {
  51342. // Need to reset animation events
  51343. for (var index = 0; index < events.length; index++) {
  51344. if (!events[index].onlyOnce) {
  51345. // reset event, the animation is looping
  51346. events[index].isDone = false;
  51347. }
  51348. }
  51349. }
  51350. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51351. // Set value
  51352. this.setValue(currentValue, weight);
  51353. // Check events
  51354. for (var index = 0; index < events.length; index++) {
  51355. // Make sure current frame has passed event frame and that event frame is within the current range
  51356. // Also, handle both forward and reverse animations
  51357. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51358. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51359. var event = events[index];
  51360. if (!event.isDone) {
  51361. // If event should be done only once, remove it.
  51362. if (event.onlyOnce) {
  51363. events.splice(index, 1);
  51364. index--;
  51365. }
  51366. event.isDone = true;
  51367. event.action(currentFrame);
  51368. } // Don't do anything if the event has already be done.
  51369. }
  51370. }
  51371. if (!returnValue) {
  51372. this._stopped = true;
  51373. }
  51374. return returnValue;
  51375. };
  51376. return RuntimeAnimation;
  51377. }());
  51378. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51379. })(BABYLON || (BABYLON = {}));
  51380. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51381. var BABYLON;
  51382. (function (BABYLON) {
  51383. /**
  51384. * Class used to store an actual running animation
  51385. */
  51386. var Animatable = /** @class */ (function () {
  51387. /**
  51388. * Creates a new Animatable
  51389. * @param scene defines the hosting scene
  51390. * @param target defines the target object
  51391. * @param fromFrame defines the starting frame number (default is 0)
  51392. * @param toFrame defines the ending frame number (default is 100)
  51393. * @param loopAnimation defines if the animation must loop (default is false)
  51394. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51395. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51396. * @param animations defines a group of animation to add to the new Animatable
  51397. */
  51398. function Animatable(scene,
  51399. /** defines the target object */
  51400. target,
  51401. /** defines the starting frame number (default is 0) */
  51402. fromFrame,
  51403. /** defines the ending frame number (default is 100) */
  51404. toFrame,
  51405. /** defines if the animation must loop (default is false) */
  51406. loopAnimation, speedRatio,
  51407. /** defines a callback to call when animation ends if it is not looping */
  51408. onAnimationEnd, animations) {
  51409. if (fromFrame === void 0) { fromFrame = 0; }
  51410. if (toFrame === void 0) { toFrame = 100; }
  51411. if (loopAnimation === void 0) { loopAnimation = false; }
  51412. if (speedRatio === void 0) { speedRatio = 1.0; }
  51413. this.target = target;
  51414. this.fromFrame = fromFrame;
  51415. this.toFrame = toFrame;
  51416. this.loopAnimation = loopAnimation;
  51417. this.onAnimationEnd = onAnimationEnd;
  51418. this._localDelayOffset = null;
  51419. this._pausedDelay = null;
  51420. this._runtimeAnimations = new Array();
  51421. this._paused = false;
  51422. this._speedRatio = 1;
  51423. this._weight = -1.0;
  51424. /**
  51425. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51426. * This will only apply for non looping animation (default is true)
  51427. */
  51428. this.disposeOnEnd = true;
  51429. /**
  51430. * Gets a boolean indicating if the animation has started
  51431. */
  51432. this.animationStarted = false;
  51433. /**
  51434. * Observer raised when the animation ends
  51435. */
  51436. this.onAnimationEndObservable = new BABYLON.Observable();
  51437. this._scene = scene;
  51438. if (animations) {
  51439. this.appendAnimations(target, animations);
  51440. }
  51441. this._speedRatio = speedRatio;
  51442. scene._activeAnimatables.push(this);
  51443. }
  51444. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51445. /**
  51446. * Gets the root Animatable used to synchronize and normalize animations
  51447. */
  51448. get: function () {
  51449. return this._syncRoot;
  51450. },
  51451. enumerable: true,
  51452. configurable: true
  51453. });
  51454. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51455. /**
  51456. * Gets the current frame of the first RuntimeAnimation
  51457. * Used to synchronize Animatables
  51458. */
  51459. get: function () {
  51460. if (this._runtimeAnimations.length === 0) {
  51461. return 0;
  51462. }
  51463. return this._runtimeAnimations[0].currentFrame;
  51464. },
  51465. enumerable: true,
  51466. configurable: true
  51467. });
  51468. Object.defineProperty(Animatable.prototype, "weight", {
  51469. /**
  51470. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51471. */
  51472. get: function () {
  51473. return this._weight;
  51474. },
  51475. set: function (value) {
  51476. if (value === -1) { // -1 is ok and means no weight
  51477. this._weight = -1;
  51478. return;
  51479. }
  51480. // Else weight must be in [0, 1] range
  51481. this._weight = Math.min(Math.max(value, 0), 1.0);
  51482. },
  51483. enumerable: true,
  51484. configurable: true
  51485. });
  51486. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51487. /**
  51488. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51489. */
  51490. get: function () {
  51491. return this._speedRatio;
  51492. },
  51493. set: function (value) {
  51494. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51495. var animation = this._runtimeAnimations[index];
  51496. animation._prepareForSpeedRatioChange(value);
  51497. }
  51498. this._speedRatio = value;
  51499. },
  51500. enumerable: true,
  51501. configurable: true
  51502. });
  51503. // Methods
  51504. /**
  51505. * Synchronize and normalize current Animatable with a source Animatable
  51506. * This is useful when using animation weights and when animations are not of the same length
  51507. * @param root defines the root Animatable to synchronize with
  51508. * @returns the current Animatable
  51509. */
  51510. Animatable.prototype.syncWith = function (root) {
  51511. this._syncRoot = root;
  51512. if (root) {
  51513. // Make sure this animatable will animate after the root
  51514. var index = this._scene._activeAnimatables.indexOf(this);
  51515. if (index > -1) {
  51516. this._scene._activeAnimatables.splice(index, 1);
  51517. this._scene._activeAnimatables.push(this);
  51518. }
  51519. }
  51520. return this;
  51521. };
  51522. /**
  51523. * Gets the list of runtime animations
  51524. * @returns an array of RuntimeAnimation
  51525. */
  51526. Animatable.prototype.getAnimations = function () {
  51527. return this._runtimeAnimations;
  51528. };
  51529. /**
  51530. * Adds more animations to the current animatable
  51531. * @param target defines the target of the animations
  51532. * @param animations defines the new animations to add
  51533. */
  51534. Animatable.prototype.appendAnimations = function (target, animations) {
  51535. for (var index = 0; index < animations.length; index++) {
  51536. var animation = animations[index];
  51537. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51538. }
  51539. };
  51540. /**
  51541. * Gets the source animation for a specific property
  51542. * @param property defines the propertyu to look for
  51543. * @returns null or the source animation for the given property
  51544. */
  51545. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51546. var runtimeAnimations = this._runtimeAnimations;
  51547. for (var index = 0; index < runtimeAnimations.length; index++) {
  51548. if (runtimeAnimations[index].animation.targetProperty === property) {
  51549. return runtimeAnimations[index].animation;
  51550. }
  51551. }
  51552. return null;
  51553. };
  51554. /**
  51555. * Gets the runtime animation for a specific property
  51556. * @param property defines the propertyu to look for
  51557. * @returns null or the runtime animation for the given property
  51558. */
  51559. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51560. var runtimeAnimations = this._runtimeAnimations;
  51561. for (var index = 0; index < runtimeAnimations.length; index++) {
  51562. if (runtimeAnimations[index].animation.targetProperty === property) {
  51563. return runtimeAnimations[index];
  51564. }
  51565. }
  51566. return null;
  51567. };
  51568. /**
  51569. * Resets the animatable to its original state
  51570. */
  51571. Animatable.prototype.reset = function () {
  51572. var runtimeAnimations = this._runtimeAnimations;
  51573. for (var index = 0; index < runtimeAnimations.length; index++) {
  51574. runtimeAnimations[index].reset(true);
  51575. }
  51576. this._localDelayOffset = null;
  51577. this._pausedDelay = null;
  51578. };
  51579. /**
  51580. * Allows the animatable to blend with current running animations
  51581. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51582. * @param blendingSpeed defines the blending speed to use
  51583. */
  51584. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51585. var runtimeAnimations = this._runtimeAnimations;
  51586. for (var index = 0; index < runtimeAnimations.length; index++) {
  51587. runtimeAnimations[index].animation.enableBlending = true;
  51588. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51589. }
  51590. };
  51591. /**
  51592. * Disable animation blending
  51593. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51594. */
  51595. Animatable.prototype.disableBlending = function () {
  51596. var runtimeAnimations = this._runtimeAnimations;
  51597. for (var index = 0; index < runtimeAnimations.length; index++) {
  51598. runtimeAnimations[index].animation.enableBlending = false;
  51599. }
  51600. };
  51601. /**
  51602. * Jump directly to a given frame
  51603. * @param frame defines the frame to jump to
  51604. */
  51605. Animatable.prototype.goToFrame = function (frame) {
  51606. var runtimeAnimations = this._runtimeAnimations;
  51607. if (runtimeAnimations[0]) {
  51608. var fps = runtimeAnimations[0].animation.framePerSecond;
  51609. var currentFrame = runtimeAnimations[0].currentFrame;
  51610. var adjustTime = frame - currentFrame;
  51611. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51612. if (this._localDelayOffset === null) {
  51613. this._localDelayOffset = 0;
  51614. }
  51615. this._localDelayOffset -= delay;
  51616. }
  51617. for (var index = 0; index < runtimeAnimations.length; index++) {
  51618. runtimeAnimations[index].goToFrame(frame);
  51619. }
  51620. };
  51621. /**
  51622. * Pause the animation
  51623. */
  51624. Animatable.prototype.pause = function () {
  51625. if (this._paused) {
  51626. return;
  51627. }
  51628. this._paused = true;
  51629. };
  51630. /**
  51631. * Restart the animation
  51632. */
  51633. Animatable.prototype.restart = function () {
  51634. this._paused = false;
  51635. };
  51636. Animatable.prototype._raiseOnAnimationEnd = function () {
  51637. if (this.onAnimationEnd) {
  51638. this.onAnimationEnd();
  51639. }
  51640. this.onAnimationEndObservable.notifyObservers(this);
  51641. };
  51642. /**
  51643. * Stop and delete the current animation
  51644. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51645. * @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)
  51646. */
  51647. Animatable.prototype.stop = function (animationName, targetMask) {
  51648. if (animationName || targetMask) {
  51649. var idx = this._scene._activeAnimatables.indexOf(this);
  51650. if (idx > -1) {
  51651. var runtimeAnimations = this._runtimeAnimations;
  51652. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51653. var runtimeAnimation = runtimeAnimations[index];
  51654. if (animationName && runtimeAnimation.animation.name != animationName) {
  51655. continue;
  51656. }
  51657. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51658. continue;
  51659. }
  51660. runtimeAnimation.dispose();
  51661. runtimeAnimations.splice(index, 1);
  51662. }
  51663. if (runtimeAnimations.length == 0) {
  51664. this._scene._activeAnimatables.splice(idx, 1);
  51665. this._raiseOnAnimationEnd();
  51666. }
  51667. }
  51668. }
  51669. else {
  51670. var index = this._scene._activeAnimatables.indexOf(this);
  51671. if (index > -1) {
  51672. this._scene._activeAnimatables.splice(index, 1);
  51673. var runtimeAnimations = this._runtimeAnimations;
  51674. for (var index = 0; index < runtimeAnimations.length; index++) {
  51675. runtimeAnimations[index].dispose();
  51676. }
  51677. this._raiseOnAnimationEnd();
  51678. }
  51679. }
  51680. };
  51681. /**
  51682. * Wait asynchronously for the animation to end
  51683. * @returns a promise which will be fullfilled when the animation ends
  51684. */
  51685. Animatable.prototype.waitAsync = function () {
  51686. var _this = this;
  51687. return new Promise(function (resolve, reject) {
  51688. _this.onAnimationEndObservable.add(function () {
  51689. resolve(_this);
  51690. }, undefined, undefined, _this, true);
  51691. });
  51692. };
  51693. /** @hidden */
  51694. Animatable.prototype._animate = function (delay) {
  51695. if (this._paused) {
  51696. this.animationStarted = false;
  51697. if (this._pausedDelay === null) {
  51698. this._pausedDelay = delay;
  51699. }
  51700. return true;
  51701. }
  51702. if (this._localDelayOffset === null) {
  51703. this._localDelayOffset = delay;
  51704. this._pausedDelay = null;
  51705. }
  51706. else if (this._pausedDelay !== null) {
  51707. this._localDelayOffset += delay - this._pausedDelay;
  51708. this._pausedDelay = null;
  51709. }
  51710. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51711. return true;
  51712. }
  51713. // Animating
  51714. var running = false;
  51715. var runtimeAnimations = this._runtimeAnimations;
  51716. var index;
  51717. for (index = 0; index < runtimeAnimations.length; index++) {
  51718. var animation = runtimeAnimations[index];
  51719. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51720. running = running || isRunning;
  51721. }
  51722. this.animationStarted = running;
  51723. if (!running) {
  51724. if (this.disposeOnEnd) {
  51725. // Remove from active animatables
  51726. index = this._scene._activeAnimatables.indexOf(this);
  51727. this._scene._activeAnimatables.splice(index, 1);
  51728. // Dispose all runtime animations
  51729. for (index = 0; index < runtimeAnimations.length; index++) {
  51730. runtimeAnimations[index].dispose();
  51731. }
  51732. }
  51733. this._raiseOnAnimationEnd();
  51734. if (this.disposeOnEnd) {
  51735. this.onAnimationEnd = null;
  51736. this.onAnimationEndObservable.clear();
  51737. }
  51738. }
  51739. return running;
  51740. };
  51741. return Animatable;
  51742. }());
  51743. BABYLON.Animatable = Animatable;
  51744. })(BABYLON || (BABYLON = {}));
  51745. //# sourceMappingURL=babylon.animatable.js.map
  51746. var BABYLON;
  51747. (function (BABYLON) {
  51748. var EasingFunction = /** @class */ (function () {
  51749. function EasingFunction() {
  51750. // Properties
  51751. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51752. }
  51753. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51754. get: function () {
  51755. return EasingFunction._EASINGMODE_EASEIN;
  51756. },
  51757. enumerable: true,
  51758. configurable: true
  51759. });
  51760. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51761. get: function () {
  51762. return EasingFunction._EASINGMODE_EASEOUT;
  51763. },
  51764. enumerable: true,
  51765. configurable: true
  51766. });
  51767. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51768. get: function () {
  51769. return EasingFunction._EASINGMODE_EASEINOUT;
  51770. },
  51771. enumerable: true,
  51772. configurable: true
  51773. });
  51774. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51775. var n = Math.min(Math.max(easingMode, 0), 2);
  51776. this._easingMode = n;
  51777. };
  51778. EasingFunction.prototype.getEasingMode = function () {
  51779. return this._easingMode;
  51780. };
  51781. EasingFunction.prototype.easeInCore = function (gradient) {
  51782. throw new Error('You must implement this method');
  51783. };
  51784. EasingFunction.prototype.ease = function (gradient) {
  51785. switch (this._easingMode) {
  51786. case EasingFunction.EASINGMODE_EASEIN:
  51787. return this.easeInCore(gradient);
  51788. case EasingFunction.EASINGMODE_EASEOUT:
  51789. return (1 - this.easeInCore(1 - gradient));
  51790. }
  51791. if (gradient >= 0.5) {
  51792. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51793. }
  51794. return (this.easeInCore(gradient * 2) * 0.5);
  51795. };
  51796. //Statics
  51797. EasingFunction._EASINGMODE_EASEIN = 0;
  51798. EasingFunction._EASINGMODE_EASEOUT = 1;
  51799. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51800. return EasingFunction;
  51801. }());
  51802. BABYLON.EasingFunction = EasingFunction;
  51803. var CircleEase = /** @class */ (function (_super) {
  51804. __extends(CircleEase, _super);
  51805. function CircleEase() {
  51806. return _super !== null && _super.apply(this, arguments) || this;
  51807. }
  51808. CircleEase.prototype.easeInCore = function (gradient) {
  51809. gradient = Math.max(0, Math.min(1, gradient));
  51810. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51811. };
  51812. return CircleEase;
  51813. }(EasingFunction));
  51814. BABYLON.CircleEase = CircleEase;
  51815. var BackEase = /** @class */ (function (_super) {
  51816. __extends(BackEase, _super);
  51817. function BackEase(amplitude) {
  51818. if (amplitude === void 0) { amplitude = 1; }
  51819. var _this = _super.call(this) || this;
  51820. _this.amplitude = amplitude;
  51821. return _this;
  51822. }
  51823. BackEase.prototype.easeInCore = function (gradient) {
  51824. var num = Math.max(0, this.amplitude);
  51825. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51826. };
  51827. return BackEase;
  51828. }(EasingFunction));
  51829. BABYLON.BackEase = BackEase;
  51830. var BounceEase = /** @class */ (function (_super) {
  51831. __extends(BounceEase, _super);
  51832. function BounceEase(bounces, bounciness) {
  51833. if (bounces === void 0) { bounces = 3; }
  51834. if (bounciness === void 0) { bounciness = 2; }
  51835. var _this = _super.call(this) || this;
  51836. _this.bounces = bounces;
  51837. _this.bounciness = bounciness;
  51838. return _this;
  51839. }
  51840. BounceEase.prototype.easeInCore = function (gradient) {
  51841. var y = Math.max(0.0, this.bounces);
  51842. var bounciness = this.bounciness;
  51843. if (bounciness <= 1.0) {
  51844. bounciness = 1.001;
  51845. }
  51846. var num9 = Math.pow(bounciness, y);
  51847. var num5 = 1.0 - bounciness;
  51848. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51849. var num15 = gradient * num4;
  51850. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51851. var num3 = Math.floor(num65);
  51852. var num13 = num3 + 1.0;
  51853. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51854. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51855. var num7 = (num8 + num12) * 0.5;
  51856. var num6 = gradient - num7;
  51857. var num2 = num7 - num8;
  51858. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51859. };
  51860. return BounceEase;
  51861. }(EasingFunction));
  51862. BABYLON.BounceEase = BounceEase;
  51863. var CubicEase = /** @class */ (function (_super) {
  51864. __extends(CubicEase, _super);
  51865. function CubicEase() {
  51866. return _super !== null && _super.apply(this, arguments) || this;
  51867. }
  51868. CubicEase.prototype.easeInCore = function (gradient) {
  51869. return (gradient * gradient * gradient);
  51870. };
  51871. return CubicEase;
  51872. }(EasingFunction));
  51873. BABYLON.CubicEase = CubicEase;
  51874. var ElasticEase = /** @class */ (function (_super) {
  51875. __extends(ElasticEase, _super);
  51876. function ElasticEase(oscillations, springiness) {
  51877. if (oscillations === void 0) { oscillations = 3; }
  51878. if (springiness === void 0) { springiness = 3; }
  51879. var _this = _super.call(this) || this;
  51880. _this.oscillations = oscillations;
  51881. _this.springiness = springiness;
  51882. return _this;
  51883. }
  51884. ElasticEase.prototype.easeInCore = function (gradient) {
  51885. var num2;
  51886. var num3 = Math.max(0.0, this.oscillations);
  51887. var num = Math.max(0.0, this.springiness);
  51888. if (num == 0) {
  51889. num2 = gradient;
  51890. }
  51891. else {
  51892. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51893. }
  51894. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51895. };
  51896. return ElasticEase;
  51897. }(EasingFunction));
  51898. BABYLON.ElasticEase = ElasticEase;
  51899. var ExponentialEase = /** @class */ (function (_super) {
  51900. __extends(ExponentialEase, _super);
  51901. function ExponentialEase(exponent) {
  51902. if (exponent === void 0) { exponent = 2; }
  51903. var _this = _super.call(this) || this;
  51904. _this.exponent = exponent;
  51905. return _this;
  51906. }
  51907. ExponentialEase.prototype.easeInCore = function (gradient) {
  51908. if (this.exponent <= 0) {
  51909. return gradient;
  51910. }
  51911. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51912. };
  51913. return ExponentialEase;
  51914. }(EasingFunction));
  51915. BABYLON.ExponentialEase = ExponentialEase;
  51916. var PowerEase = /** @class */ (function (_super) {
  51917. __extends(PowerEase, _super);
  51918. function PowerEase(power) {
  51919. if (power === void 0) { power = 2; }
  51920. var _this = _super.call(this) || this;
  51921. _this.power = power;
  51922. return _this;
  51923. }
  51924. PowerEase.prototype.easeInCore = function (gradient) {
  51925. var y = Math.max(0.0, this.power);
  51926. return Math.pow(gradient, y);
  51927. };
  51928. return PowerEase;
  51929. }(EasingFunction));
  51930. BABYLON.PowerEase = PowerEase;
  51931. var QuadraticEase = /** @class */ (function (_super) {
  51932. __extends(QuadraticEase, _super);
  51933. function QuadraticEase() {
  51934. return _super !== null && _super.apply(this, arguments) || this;
  51935. }
  51936. QuadraticEase.prototype.easeInCore = function (gradient) {
  51937. return (gradient * gradient);
  51938. };
  51939. return QuadraticEase;
  51940. }(EasingFunction));
  51941. BABYLON.QuadraticEase = QuadraticEase;
  51942. var QuarticEase = /** @class */ (function (_super) {
  51943. __extends(QuarticEase, _super);
  51944. function QuarticEase() {
  51945. return _super !== null && _super.apply(this, arguments) || this;
  51946. }
  51947. QuarticEase.prototype.easeInCore = function (gradient) {
  51948. return (gradient * gradient * gradient * gradient);
  51949. };
  51950. return QuarticEase;
  51951. }(EasingFunction));
  51952. BABYLON.QuarticEase = QuarticEase;
  51953. var QuinticEase = /** @class */ (function (_super) {
  51954. __extends(QuinticEase, _super);
  51955. function QuinticEase() {
  51956. return _super !== null && _super.apply(this, arguments) || this;
  51957. }
  51958. QuinticEase.prototype.easeInCore = function (gradient) {
  51959. return (gradient * gradient * gradient * gradient * gradient);
  51960. };
  51961. return QuinticEase;
  51962. }(EasingFunction));
  51963. BABYLON.QuinticEase = QuinticEase;
  51964. var SineEase = /** @class */ (function (_super) {
  51965. __extends(SineEase, _super);
  51966. function SineEase() {
  51967. return _super !== null && _super.apply(this, arguments) || this;
  51968. }
  51969. SineEase.prototype.easeInCore = function (gradient) {
  51970. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51971. };
  51972. return SineEase;
  51973. }(EasingFunction));
  51974. BABYLON.SineEase = SineEase;
  51975. var BezierCurveEase = /** @class */ (function (_super) {
  51976. __extends(BezierCurveEase, _super);
  51977. function BezierCurveEase(x1, y1, x2, y2) {
  51978. if (x1 === void 0) { x1 = 0; }
  51979. if (y1 === void 0) { y1 = 0; }
  51980. if (x2 === void 0) { x2 = 1; }
  51981. if (y2 === void 0) { y2 = 1; }
  51982. var _this = _super.call(this) || this;
  51983. _this.x1 = x1;
  51984. _this.y1 = y1;
  51985. _this.x2 = x2;
  51986. _this.y2 = y2;
  51987. return _this;
  51988. }
  51989. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51990. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51991. };
  51992. return BezierCurveEase;
  51993. }(EasingFunction));
  51994. BABYLON.BezierCurveEase = BezierCurveEase;
  51995. })(BABYLON || (BABYLON = {}));
  51996. //# sourceMappingURL=babylon.easing.js.map
  51997. var BABYLON;
  51998. (function (BABYLON) {
  51999. /**
  52000. * A Condition applied to an Action
  52001. */
  52002. var Condition = /** @class */ (function () {
  52003. /**
  52004. * Creates a new Condition
  52005. * @param actionManager the manager of the action the condition is applied to
  52006. */
  52007. function Condition(actionManager) {
  52008. this._actionManager = actionManager;
  52009. }
  52010. /**
  52011. * Check if the current condition is valid
  52012. * @returns a boolean
  52013. */
  52014. Condition.prototype.isValid = function () {
  52015. return true;
  52016. };
  52017. /**
  52018. * Internal only
  52019. * @hidden
  52020. */
  52021. Condition.prototype._getProperty = function (propertyPath) {
  52022. return this._actionManager._getProperty(propertyPath);
  52023. };
  52024. /**
  52025. * Internal only
  52026. * @hidden
  52027. */
  52028. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52029. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52030. };
  52031. /**
  52032. * Serialize placeholder for child classes
  52033. * @returns the serialized object
  52034. */
  52035. Condition.prototype.serialize = function () {
  52036. };
  52037. /**
  52038. * Internal only
  52039. * @hidden
  52040. */
  52041. Condition.prototype._serialize = function (serializedCondition) {
  52042. return {
  52043. type: 2,
  52044. children: [],
  52045. name: serializedCondition.name,
  52046. properties: serializedCondition.properties
  52047. };
  52048. };
  52049. return Condition;
  52050. }());
  52051. BABYLON.Condition = Condition;
  52052. /**
  52053. * Defines specific conditional operators as extensions of Condition
  52054. */
  52055. var ValueCondition = /** @class */ (function (_super) {
  52056. __extends(ValueCondition, _super);
  52057. /**
  52058. * Creates a new ValueCondition
  52059. * @param actionManager manager for the action the condition applies to
  52060. * @param target for the action
  52061. * @param propertyPath path to specify the property of the target the conditional operator uses
  52062. * @param value the value compared by the conditional operator against the current value of the property
  52063. * @param operator the conditional operator, default ValueCondition.IsEqual
  52064. */
  52065. function ValueCondition(actionManager, target,
  52066. /** path to specify the property of the target the conditional operator uses */
  52067. propertyPath,
  52068. /** the value compared by the conditional operator against the current value of the property */
  52069. value,
  52070. /** the conditional operator, default ValueCondition.IsEqual */
  52071. operator) {
  52072. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52073. var _this = _super.call(this, actionManager) || this;
  52074. _this.propertyPath = propertyPath;
  52075. _this.value = value;
  52076. _this.operator = operator;
  52077. _this._target = target;
  52078. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52079. _this._property = _this._getProperty(_this.propertyPath);
  52080. return _this;
  52081. }
  52082. Object.defineProperty(ValueCondition, "IsEqual", {
  52083. /**
  52084. * returns the number for IsEqual
  52085. */
  52086. get: function () {
  52087. return ValueCondition._IsEqual;
  52088. },
  52089. enumerable: true,
  52090. configurable: true
  52091. });
  52092. Object.defineProperty(ValueCondition, "IsDifferent", {
  52093. /**
  52094. * Returns the number for IsDifferent
  52095. */
  52096. get: function () {
  52097. return ValueCondition._IsDifferent;
  52098. },
  52099. enumerable: true,
  52100. configurable: true
  52101. });
  52102. Object.defineProperty(ValueCondition, "IsGreater", {
  52103. /**
  52104. * Returns the number for IsGreater
  52105. */
  52106. get: function () {
  52107. return ValueCondition._IsGreater;
  52108. },
  52109. enumerable: true,
  52110. configurable: true
  52111. });
  52112. Object.defineProperty(ValueCondition, "IsLesser", {
  52113. /**
  52114. * Returns the number for IsLesser
  52115. */
  52116. get: function () {
  52117. return ValueCondition._IsLesser;
  52118. },
  52119. enumerable: true,
  52120. configurable: true
  52121. });
  52122. /**
  52123. * Compares the given value with the property value for the specified conditional operator
  52124. * @returns the result of the comparison
  52125. */
  52126. ValueCondition.prototype.isValid = function () {
  52127. switch (this.operator) {
  52128. case ValueCondition.IsGreater:
  52129. return this._effectiveTarget[this._property] > this.value;
  52130. case ValueCondition.IsLesser:
  52131. return this._effectiveTarget[this._property] < this.value;
  52132. case ValueCondition.IsEqual:
  52133. case ValueCondition.IsDifferent:
  52134. var check;
  52135. if (this.value.equals) {
  52136. check = this.value.equals(this._effectiveTarget[this._property]);
  52137. }
  52138. else {
  52139. check = this.value === this._effectiveTarget[this._property];
  52140. }
  52141. return this.operator === ValueCondition.IsEqual ? check : !check;
  52142. }
  52143. return false;
  52144. };
  52145. /**
  52146. * Serialize the ValueCondition into a JSON compatible object
  52147. * @returns serialization object
  52148. */
  52149. ValueCondition.prototype.serialize = function () {
  52150. return this._serialize({
  52151. name: "ValueCondition",
  52152. properties: [
  52153. BABYLON.Action._GetTargetProperty(this._target),
  52154. { name: "propertyPath", value: this.propertyPath },
  52155. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52156. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52157. ]
  52158. });
  52159. };
  52160. /**
  52161. * Gets the name of the conditional operator for the ValueCondition
  52162. * @param operator the conditional operator
  52163. * @returns the name
  52164. */
  52165. ValueCondition.GetOperatorName = function (operator) {
  52166. switch (operator) {
  52167. case ValueCondition._IsEqual: return "IsEqual";
  52168. case ValueCondition._IsDifferent: return "IsDifferent";
  52169. case ValueCondition._IsGreater: return "IsGreater";
  52170. case ValueCondition._IsLesser: return "IsLesser";
  52171. default: return "";
  52172. }
  52173. };
  52174. /**
  52175. * Internal only
  52176. * @hidden
  52177. */
  52178. ValueCondition._IsEqual = 0;
  52179. /**
  52180. * Internal only
  52181. * @hidden
  52182. */
  52183. ValueCondition._IsDifferent = 1;
  52184. /**
  52185. * Internal only
  52186. * @hidden
  52187. */
  52188. ValueCondition._IsGreater = 2;
  52189. /**
  52190. * Internal only
  52191. * @hidden
  52192. */
  52193. ValueCondition._IsLesser = 3;
  52194. return ValueCondition;
  52195. }(Condition));
  52196. BABYLON.ValueCondition = ValueCondition;
  52197. /**
  52198. * Defines a predicate condition as an extension of Condition
  52199. */
  52200. var PredicateCondition = /** @class */ (function (_super) {
  52201. __extends(PredicateCondition, _super);
  52202. /**
  52203. * Creates a new PredicateCondition
  52204. * @param actionManager manager for the action the condition applies to
  52205. * @param predicate defines the predicate function used to validate the condition
  52206. */
  52207. function PredicateCondition(actionManager,
  52208. /** defines the predicate function used to validate the condition */
  52209. predicate) {
  52210. var _this = _super.call(this, actionManager) || this;
  52211. _this.predicate = predicate;
  52212. return _this;
  52213. }
  52214. /**
  52215. * @returns the validity of the predicate condition
  52216. */
  52217. PredicateCondition.prototype.isValid = function () {
  52218. return this.predicate();
  52219. };
  52220. return PredicateCondition;
  52221. }(Condition));
  52222. BABYLON.PredicateCondition = PredicateCondition;
  52223. /**
  52224. * Defines a state condition as an extension of Condition
  52225. */
  52226. var StateCondition = /** @class */ (function (_super) {
  52227. __extends(StateCondition, _super);
  52228. /**
  52229. * Creates a new StateCondition
  52230. * @param actionManager manager for the action the condition applies to
  52231. * @param target of the condition
  52232. * @param value to compare with target state
  52233. */
  52234. function StateCondition(actionManager, target, value) {
  52235. var _this = _super.call(this, actionManager) || this;
  52236. _this.value = value;
  52237. _this._target = target;
  52238. return _this;
  52239. }
  52240. /**
  52241. * @returns the validity of the state
  52242. */
  52243. StateCondition.prototype.isValid = function () {
  52244. return this._target.state === this.value;
  52245. };
  52246. /**
  52247. * Serialize the StateCondition into a JSON compatible object
  52248. * @returns serialization object
  52249. */
  52250. StateCondition.prototype.serialize = function () {
  52251. return this._serialize({
  52252. name: "StateCondition",
  52253. properties: [
  52254. BABYLON.Action._GetTargetProperty(this._target),
  52255. { name: "value", value: this.value }
  52256. ]
  52257. });
  52258. };
  52259. return StateCondition;
  52260. }(Condition));
  52261. BABYLON.StateCondition = StateCondition;
  52262. })(BABYLON || (BABYLON = {}));
  52263. //# sourceMappingURL=babylon.condition.js.map
  52264. var BABYLON;
  52265. (function (BABYLON) {
  52266. /**
  52267. * The action to be carried out following a trigger
  52268. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52269. */
  52270. var Action = /** @class */ (function () {
  52271. /**
  52272. * Creates a new Action
  52273. * @param triggerOptions the trigger, with or without parameters, for the action
  52274. * @param condition an optional determinant of action
  52275. */
  52276. function Action(
  52277. /** the trigger, with or without parameters, for the action */
  52278. triggerOptions, condition) {
  52279. this.triggerOptions = triggerOptions;
  52280. /**
  52281. * An event triggered prior to action being executed.
  52282. */
  52283. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52284. if (triggerOptions.parameter) {
  52285. this.trigger = triggerOptions.trigger;
  52286. this._triggerParameter = triggerOptions.parameter;
  52287. }
  52288. else {
  52289. this.trigger = triggerOptions;
  52290. }
  52291. this._nextActiveAction = this;
  52292. this._condition = condition;
  52293. }
  52294. /**
  52295. * Internal only
  52296. * @hidden
  52297. */
  52298. Action.prototype._prepare = function () {
  52299. };
  52300. /**
  52301. * Gets the trigger parameters
  52302. * @returns the trigger parameters
  52303. */
  52304. Action.prototype.getTriggerParameter = function () {
  52305. return this._triggerParameter;
  52306. };
  52307. /**
  52308. * Internal only - executes current action event
  52309. * @hidden
  52310. */
  52311. Action.prototype._executeCurrent = function (evt) {
  52312. if (this._nextActiveAction._condition) {
  52313. var condition = this._nextActiveAction._condition;
  52314. var currentRenderId = this._actionManager.getScene().getRenderId();
  52315. // We cache the current evaluation for the current frame
  52316. if (condition._evaluationId === currentRenderId) {
  52317. if (!condition._currentResult) {
  52318. return;
  52319. }
  52320. }
  52321. else {
  52322. condition._evaluationId = currentRenderId;
  52323. if (!condition.isValid()) {
  52324. condition._currentResult = false;
  52325. return;
  52326. }
  52327. condition._currentResult = true;
  52328. }
  52329. }
  52330. this.onBeforeExecuteObservable.notifyObservers(this);
  52331. this._nextActiveAction.execute(evt);
  52332. this.skipToNextActiveAction();
  52333. };
  52334. /**
  52335. * Execute placeholder for child classes
  52336. * @param evt optional action event
  52337. */
  52338. Action.prototype.execute = function (evt) {
  52339. };
  52340. /**
  52341. * Skips to next active action
  52342. */
  52343. Action.prototype.skipToNextActiveAction = function () {
  52344. if (this._nextActiveAction._child) {
  52345. if (!this._nextActiveAction._child._actionManager) {
  52346. this._nextActiveAction._child._actionManager = this._actionManager;
  52347. }
  52348. this._nextActiveAction = this._nextActiveAction._child;
  52349. }
  52350. else {
  52351. this._nextActiveAction = this;
  52352. }
  52353. };
  52354. /**
  52355. * Adds action to chain of actions, may be a DoNothingAction
  52356. * @param action defines the next action to execute
  52357. * @returns The action passed in
  52358. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52359. */
  52360. Action.prototype.then = function (action) {
  52361. this._child = action;
  52362. action._actionManager = this._actionManager;
  52363. action._prepare();
  52364. return action;
  52365. };
  52366. /**
  52367. * Internal only
  52368. * @hidden
  52369. */
  52370. Action.prototype._getProperty = function (propertyPath) {
  52371. return this._actionManager._getProperty(propertyPath);
  52372. };
  52373. /**
  52374. * Internal only
  52375. * @hidden
  52376. */
  52377. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52378. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52379. };
  52380. /**
  52381. * Serialize placeholder for child classes
  52382. * @param parent of child
  52383. * @returns the serialized object
  52384. */
  52385. Action.prototype.serialize = function (parent) {
  52386. };
  52387. /**
  52388. * Internal only called by serialize
  52389. * @hidden
  52390. */
  52391. Action.prototype._serialize = function (serializedAction, parent) {
  52392. var serializationObject = {
  52393. type: 1,
  52394. children: [],
  52395. name: serializedAction.name,
  52396. properties: serializedAction.properties || []
  52397. };
  52398. // Serialize child
  52399. if (this._child) {
  52400. this._child.serialize(serializationObject);
  52401. }
  52402. // Check if "this" has a condition
  52403. if (this._condition) {
  52404. var serializedCondition = this._condition.serialize();
  52405. serializedCondition.children.push(serializationObject);
  52406. if (parent) {
  52407. parent.children.push(serializedCondition);
  52408. }
  52409. return serializedCondition;
  52410. }
  52411. if (parent) {
  52412. parent.children.push(serializationObject);
  52413. }
  52414. return serializationObject;
  52415. };
  52416. /**
  52417. * Internal only
  52418. * @hidden
  52419. */
  52420. Action._SerializeValueAsString = function (value) {
  52421. if (typeof value === "number") {
  52422. return value.toString();
  52423. }
  52424. if (typeof value === "boolean") {
  52425. return value ? "true" : "false";
  52426. }
  52427. if (value instanceof BABYLON.Vector2) {
  52428. return value.x + ", " + value.y;
  52429. }
  52430. if (value instanceof BABYLON.Vector3) {
  52431. return value.x + ", " + value.y + ", " + value.z;
  52432. }
  52433. if (value instanceof BABYLON.Color3) {
  52434. return value.r + ", " + value.g + ", " + value.b;
  52435. }
  52436. if (value instanceof BABYLON.Color4) {
  52437. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52438. }
  52439. return value; // string
  52440. };
  52441. /**
  52442. * Internal only
  52443. * @hidden
  52444. */
  52445. Action._GetTargetProperty = function (target) {
  52446. return {
  52447. name: "target",
  52448. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52449. : target instanceof BABYLON.Light ? "LightProperties"
  52450. : target instanceof BABYLON.Camera ? "CameraProperties"
  52451. : "SceneProperties",
  52452. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52453. };
  52454. };
  52455. return Action;
  52456. }());
  52457. BABYLON.Action = Action;
  52458. })(BABYLON || (BABYLON = {}));
  52459. //# sourceMappingURL=babylon.action.js.map
  52460. var BABYLON;
  52461. (function (BABYLON) {
  52462. /**
  52463. * ActionEvent is the event being sent when an action is triggered.
  52464. */
  52465. var ActionEvent = /** @class */ (function () {
  52466. /**
  52467. * Creates a new ActionEvent
  52468. * @param source The mesh or sprite that triggered the action
  52469. * @param pointerX The X mouse cursor position at the time of the event
  52470. * @param pointerY The Y mouse cursor position at the time of the event
  52471. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52472. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52473. * @param additionalData additional data for the event
  52474. */
  52475. function ActionEvent(
  52476. /** The mesh or sprite that triggered the action */
  52477. source,
  52478. /** The X mouse cursor position at the time of the event */
  52479. pointerX,
  52480. /** The Y mouse cursor position at the time of the event */
  52481. pointerY,
  52482. /** The mesh that is currently pointed at (can be null) */
  52483. meshUnderPointer,
  52484. /** the original (browser) event that triggered the ActionEvent */
  52485. sourceEvent,
  52486. /** additional data for the event */
  52487. additionalData) {
  52488. this.source = source;
  52489. this.pointerX = pointerX;
  52490. this.pointerY = pointerY;
  52491. this.meshUnderPointer = meshUnderPointer;
  52492. this.sourceEvent = sourceEvent;
  52493. this.additionalData = additionalData;
  52494. }
  52495. /**
  52496. * Helper function to auto-create an ActionEvent from a source mesh.
  52497. * @param source The source mesh that triggered the event
  52498. * @param evt The original (browser) event
  52499. * @param additionalData additional data for the event
  52500. * @returns the new ActionEvent
  52501. */
  52502. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52503. var scene = source.getScene();
  52504. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52505. };
  52506. /**
  52507. * Helper function to auto-create an ActionEvent from a source sprite
  52508. * @param source The source sprite that triggered the event
  52509. * @param scene Scene associated with the sprite
  52510. * @param evt The original (browser) event
  52511. * @param additionalData additional data for the event
  52512. * @returns the new ActionEvent
  52513. */
  52514. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52515. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52516. };
  52517. /**
  52518. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52519. * @param scene the scene where the event occurred
  52520. * @param evt The original (browser) event
  52521. * @returns the new ActionEvent
  52522. */
  52523. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52524. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52525. };
  52526. /**
  52527. * Helper function to auto-create an ActionEvent from a primitive
  52528. * @param prim defines the target primitive
  52529. * @param pointerPos defines the pointer position
  52530. * @param evt The original (browser) event
  52531. * @param additionalData additional data for the event
  52532. * @returns the new ActionEvent
  52533. */
  52534. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52535. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52536. };
  52537. return ActionEvent;
  52538. }());
  52539. BABYLON.ActionEvent = ActionEvent;
  52540. /**
  52541. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52542. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52543. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52544. */
  52545. var ActionManager = /** @class */ (function () {
  52546. /**
  52547. * Creates a new action manager
  52548. * @param scene defines the hosting scene
  52549. */
  52550. function ActionManager(scene) {
  52551. // Members
  52552. /** Gets the list of actions */
  52553. this.actions = new Array();
  52554. /** Gets the cursor to use when hovering items */
  52555. this.hoverCursor = '';
  52556. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52557. scene.actionManagers.push(this);
  52558. }
  52559. Object.defineProperty(ActionManager, "NothingTrigger", {
  52560. /**
  52561. * Nothing
  52562. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52563. */
  52564. get: function () {
  52565. return ActionManager._NothingTrigger;
  52566. },
  52567. enumerable: true,
  52568. configurable: true
  52569. });
  52570. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52571. /**
  52572. * On pick
  52573. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52574. */
  52575. get: function () {
  52576. return ActionManager._OnPickTrigger;
  52577. },
  52578. enumerable: true,
  52579. configurable: true
  52580. });
  52581. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52582. /**
  52583. * On left pick
  52584. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52585. */
  52586. get: function () {
  52587. return ActionManager._OnLeftPickTrigger;
  52588. },
  52589. enumerable: true,
  52590. configurable: true
  52591. });
  52592. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52593. /**
  52594. * On right pick
  52595. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52596. */
  52597. get: function () {
  52598. return ActionManager._OnRightPickTrigger;
  52599. },
  52600. enumerable: true,
  52601. configurable: true
  52602. });
  52603. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52604. /**
  52605. * On center pick
  52606. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52607. */
  52608. get: function () {
  52609. return ActionManager._OnCenterPickTrigger;
  52610. },
  52611. enumerable: true,
  52612. configurable: true
  52613. });
  52614. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52615. /**
  52616. * On pick down
  52617. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52618. */
  52619. get: function () {
  52620. return ActionManager._OnPickDownTrigger;
  52621. },
  52622. enumerable: true,
  52623. configurable: true
  52624. });
  52625. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52626. /**
  52627. * On double pick
  52628. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52629. */
  52630. get: function () {
  52631. return ActionManager._OnDoublePickTrigger;
  52632. },
  52633. enumerable: true,
  52634. configurable: true
  52635. });
  52636. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52637. /**
  52638. * On pick up
  52639. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52640. */
  52641. get: function () {
  52642. return ActionManager._OnPickUpTrigger;
  52643. },
  52644. enumerable: true,
  52645. configurable: true
  52646. });
  52647. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52648. /**
  52649. * On pick out.
  52650. * This trigger will only be raised if you also declared a OnPickDown
  52651. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52652. */
  52653. get: function () {
  52654. return ActionManager._OnPickOutTrigger;
  52655. },
  52656. enumerable: true,
  52657. configurable: true
  52658. });
  52659. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52660. /**
  52661. * On long press
  52662. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52663. */
  52664. get: function () {
  52665. return ActionManager._OnLongPressTrigger;
  52666. },
  52667. enumerable: true,
  52668. configurable: true
  52669. });
  52670. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52671. /**
  52672. * On pointer over
  52673. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52674. */
  52675. get: function () {
  52676. return ActionManager._OnPointerOverTrigger;
  52677. },
  52678. enumerable: true,
  52679. configurable: true
  52680. });
  52681. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52682. /**
  52683. * On pointer out
  52684. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52685. */
  52686. get: function () {
  52687. return ActionManager._OnPointerOutTrigger;
  52688. },
  52689. enumerable: true,
  52690. configurable: true
  52691. });
  52692. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52693. /**
  52694. * On every frame
  52695. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52696. */
  52697. get: function () {
  52698. return ActionManager._OnEveryFrameTrigger;
  52699. },
  52700. enumerable: true,
  52701. configurable: true
  52702. });
  52703. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52704. /**
  52705. * On intersection enter
  52706. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52707. */
  52708. get: function () {
  52709. return ActionManager._OnIntersectionEnterTrigger;
  52710. },
  52711. enumerable: true,
  52712. configurable: true
  52713. });
  52714. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52715. /**
  52716. * On intersection exit
  52717. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52718. */
  52719. get: function () {
  52720. return ActionManager._OnIntersectionExitTrigger;
  52721. },
  52722. enumerable: true,
  52723. configurable: true
  52724. });
  52725. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52726. /**
  52727. * On key down
  52728. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52729. */
  52730. get: function () {
  52731. return ActionManager._OnKeyDownTrigger;
  52732. },
  52733. enumerable: true,
  52734. configurable: true
  52735. });
  52736. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52737. /**
  52738. * On key up
  52739. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52740. */
  52741. get: function () {
  52742. return ActionManager._OnKeyUpTrigger;
  52743. },
  52744. enumerable: true,
  52745. configurable: true
  52746. });
  52747. // Methods
  52748. /**
  52749. * Releases all associated resources
  52750. */
  52751. ActionManager.prototype.dispose = function () {
  52752. var index = this._scene.actionManagers.indexOf(this);
  52753. for (var i = 0; i < this.actions.length; i++) {
  52754. var action = this.actions[i];
  52755. ActionManager.Triggers[action.trigger]--;
  52756. if (ActionManager.Triggers[action.trigger] === 0) {
  52757. delete ActionManager.Triggers[action.trigger];
  52758. }
  52759. }
  52760. if (index > -1) {
  52761. this._scene.actionManagers.splice(index, 1);
  52762. }
  52763. };
  52764. /**
  52765. * Gets hosting scene
  52766. * @returns the hosting scene
  52767. */
  52768. ActionManager.prototype.getScene = function () {
  52769. return this._scene;
  52770. };
  52771. /**
  52772. * Does this action manager handles actions of any of the given triggers
  52773. * @param triggers defines the triggers to be tested
  52774. * @return a boolean indicating whether one (or more) of the triggers is handled
  52775. */
  52776. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52777. for (var index = 0; index < this.actions.length; index++) {
  52778. var action = this.actions[index];
  52779. if (triggers.indexOf(action.trigger) > -1) {
  52780. return true;
  52781. }
  52782. }
  52783. return false;
  52784. };
  52785. /**
  52786. * Does this action manager handles actions of a given trigger
  52787. * @param trigger defines the trigger to be tested
  52788. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52789. * @return whether the trigger is handled
  52790. */
  52791. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52792. for (var index = 0; index < this.actions.length; index++) {
  52793. var action = this.actions[index];
  52794. if (action.trigger === trigger) {
  52795. if (parameterPredicate) {
  52796. if (parameterPredicate(action.getTriggerParameter())) {
  52797. return true;
  52798. }
  52799. }
  52800. else {
  52801. return true;
  52802. }
  52803. }
  52804. }
  52805. return false;
  52806. };
  52807. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52808. /**
  52809. * Does this action manager has pointer triggers
  52810. */
  52811. get: function () {
  52812. for (var index = 0; index < this.actions.length; index++) {
  52813. var action = this.actions[index];
  52814. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52815. return true;
  52816. }
  52817. }
  52818. return false;
  52819. },
  52820. enumerable: true,
  52821. configurable: true
  52822. });
  52823. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52824. /**
  52825. * Does this action manager has pick triggers
  52826. */
  52827. get: function () {
  52828. for (var index = 0; index < this.actions.length; index++) {
  52829. var action = this.actions[index];
  52830. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52831. return true;
  52832. }
  52833. }
  52834. return false;
  52835. },
  52836. enumerable: true,
  52837. configurable: true
  52838. });
  52839. Object.defineProperty(ActionManager, "HasTriggers", {
  52840. /**
  52841. * Does exist one action manager with at least one trigger
  52842. **/
  52843. get: function () {
  52844. for (var t in ActionManager.Triggers) {
  52845. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52846. return true;
  52847. }
  52848. }
  52849. return false;
  52850. },
  52851. enumerable: true,
  52852. configurable: true
  52853. });
  52854. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52855. /**
  52856. * Does exist one action manager with at least one pick trigger
  52857. **/
  52858. get: function () {
  52859. for (var t in ActionManager.Triggers) {
  52860. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52861. var t_int = parseInt(t);
  52862. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52863. return true;
  52864. }
  52865. }
  52866. }
  52867. return false;
  52868. },
  52869. enumerable: true,
  52870. configurable: true
  52871. });
  52872. /**
  52873. * Does exist one action manager that handles actions of a given trigger
  52874. * @param trigger defines the trigger to be tested
  52875. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52876. **/
  52877. ActionManager.HasSpecificTrigger = function (trigger) {
  52878. for (var t in ActionManager.Triggers) {
  52879. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52880. var t_int = parseInt(t);
  52881. if (t_int === trigger) {
  52882. return true;
  52883. }
  52884. }
  52885. }
  52886. return false;
  52887. };
  52888. /**
  52889. * Registers an action to this action manager
  52890. * @param action defines the action to be registered
  52891. * @return the action amended (prepared) after registration
  52892. */
  52893. ActionManager.prototype.registerAction = function (action) {
  52894. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52895. if (this.getScene().actionManager !== this) {
  52896. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52897. return null;
  52898. }
  52899. }
  52900. this.actions.push(action);
  52901. if (ActionManager.Triggers[action.trigger]) {
  52902. ActionManager.Triggers[action.trigger]++;
  52903. }
  52904. else {
  52905. ActionManager.Triggers[action.trigger] = 1;
  52906. }
  52907. action._actionManager = this;
  52908. action._prepare();
  52909. return action;
  52910. };
  52911. /**
  52912. * Unregisters an action to this action manager
  52913. * @param action defines the action to be unregistered
  52914. * @return a boolean indicating whether the action has been unregistered
  52915. */
  52916. ActionManager.prototype.unregisterAction = function (action) {
  52917. var index = this.actions.indexOf(action);
  52918. if (index !== -1) {
  52919. this.actions.splice(index, 1);
  52920. ActionManager.Triggers[action.trigger] -= 1;
  52921. if (ActionManager.Triggers[action.trigger] === 0) {
  52922. delete ActionManager.Triggers[action.trigger];
  52923. }
  52924. delete action._actionManager;
  52925. return true;
  52926. }
  52927. return false;
  52928. };
  52929. /**
  52930. * Process a specific trigger
  52931. * @param trigger defines the trigger to process
  52932. * @param evt defines the event details to be processed
  52933. */
  52934. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52935. for (var index = 0; index < this.actions.length; index++) {
  52936. var action = this.actions[index];
  52937. if (action.trigger === trigger) {
  52938. if (evt) {
  52939. if (trigger === ActionManager.OnKeyUpTrigger
  52940. || trigger === ActionManager.OnKeyDownTrigger) {
  52941. var parameter = action.getTriggerParameter();
  52942. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52943. if (!parameter.toLowerCase) {
  52944. continue;
  52945. }
  52946. var lowerCase = parameter.toLowerCase();
  52947. if (lowerCase !== evt.sourceEvent.key) {
  52948. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52949. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52950. if (actualkey !== lowerCase) {
  52951. continue;
  52952. }
  52953. }
  52954. }
  52955. }
  52956. }
  52957. action._executeCurrent(evt);
  52958. }
  52959. }
  52960. };
  52961. /** @hidden */
  52962. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52963. var properties = propertyPath.split(".");
  52964. for (var index = 0; index < properties.length - 1; index++) {
  52965. target = target[properties[index]];
  52966. }
  52967. return target;
  52968. };
  52969. /** @hidden */
  52970. ActionManager.prototype._getProperty = function (propertyPath) {
  52971. var properties = propertyPath.split(".");
  52972. return properties[properties.length - 1];
  52973. };
  52974. /**
  52975. * Serialize this manager to a JSON object
  52976. * @param name defines the property name to store this manager
  52977. * @returns a JSON representation of this manager
  52978. */
  52979. ActionManager.prototype.serialize = function (name) {
  52980. var root = {
  52981. children: new Array(),
  52982. name: name,
  52983. type: 3,
  52984. properties: new Array() // Empty for root but required
  52985. };
  52986. for (var i = 0; i < this.actions.length; i++) {
  52987. var triggerObject = {
  52988. type: 0,
  52989. children: new Array(),
  52990. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52991. properties: new Array()
  52992. };
  52993. var triggerOptions = this.actions[i].triggerOptions;
  52994. if (triggerOptions && typeof triggerOptions !== "number") {
  52995. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52996. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52997. }
  52998. else {
  52999. var parameter = {};
  53000. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53001. if (triggerOptions.parameter.mesh) {
  53002. parameter._meshId = triggerOptions.parameter.mesh.id;
  53003. }
  53004. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53005. }
  53006. }
  53007. // Serialize child action, recursively
  53008. this.actions[i].serialize(triggerObject);
  53009. // Add serialized trigger
  53010. root.children.push(triggerObject);
  53011. }
  53012. return root;
  53013. };
  53014. /**
  53015. * Creates a new ActionManager from a JSON data
  53016. * @param parsedActions defines the JSON data to read from
  53017. * @param object defines the hosting mesh
  53018. * @param scene defines the hosting scene
  53019. */
  53020. ActionManager.Parse = function (parsedActions, object, scene) {
  53021. var actionManager = new ActionManager(scene);
  53022. if (object === null)
  53023. scene.actionManager = actionManager;
  53024. else
  53025. object.actionManager = actionManager;
  53026. // instanciate a new object
  53027. var instanciate = function (name, params) {
  53028. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53029. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53030. newInstance.constructor.apply(newInstance, params);
  53031. return newInstance;
  53032. };
  53033. var parseParameter = function (name, value, target, propertyPath) {
  53034. if (propertyPath === null) {
  53035. // String, boolean or float
  53036. var floatValue = parseFloat(value);
  53037. if (value === "true" || value === "false")
  53038. return value === "true";
  53039. else
  53040. return isNaN(floatValue) ? value : floatValue;
  53041. }
  53042. var effectiveTarget = propertyPath.split(".");
  53043. var values = value.split(",");
  53044. // Get effective Target
  53045. for (var i = 0; i < effectiveTarget.length; i++) {
  53046. target = target[effectiveTarget[i]];
  53047. }
  53048. // Return appropriate value with its type
  53049. if (typeof (target) === "boolean")
  53050. return values[0] === "true";
  53051. if (typeof (target) === "string")
  53052. return values[0];
  53053. // Parameters with multiple values such as Vector3 etc.
  53054. var split = new Array();
  53055. for (var i = 0; i < values.length; i++)
  53056. split.push(parseFloat(values[i]));
  53057. if (target instanceof BABYLON.Vector3)
  53058. return BABYLON.Vector3.FromArray(split);
  53059. if (target instanceof BABYLON.Vector4)
  53060. return BABYLON.Vector4.FromArray(split);
  53061. if (target instanceof BABYLON.Color3)
  53062. return BABYLON.Color3.FromArray(split);
  53063. if (target instanceof BABYLON.Color4)
  53064. return BABYLON.Color4.FromArray(split);
  53065. return parseFloat(values[0]);
  53066. };
  53067. // traverse graph per trigger
  53068. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53069. if (combineArray === void 0) { combineArray = null; }
  53070. if (parsedAction.detached)
  53071. return;
  53072. var parameters = new Array();
  53073. var target = null;
  53074. var propertyPath = null;
  53075. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53076. // Parameters
  53077. if (parsedAction.type === 2)
  53078. parameters.push(actionManager);
  53079. else
  53080. parameters.push(trigger);
  53081. if (combine) {
  53082. var actions = new Array();
  53083. for (var j = 0; j < parsedAction.combine.length; j++) {
  53084. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53085. }
  53086. parameters.push(actions);
  53087. }
  53088. else {
  53089. for (var i = 0; i < parsedAction.properties.length; i++) {
  53090. var value = parsedAction.properties[i].value;
  53091. var name = parsedAction.properties[i].name;
  53092. var targetType = parsedAction.properties[i].targetType;
  53093. if (name === "target")
  53094. if (targetType !== null && targetType === "SceneProperties")
  53095. value = target = scene;
  53096. else
  53097. value = target = scene.getNodeByName(value);
  53098. else if (name === "parent")
  53099. value = scene.getNodeByName(value);
  53100. else if (name === "sound")
  53101. value = scene.getSoundByName(value);
  53102. else if (name !== "propertyPath") {
  53103. if (parsedAction.type === 2 && name === "operator")
  53104. value = BABYLON.ValueCondition[value];
  53105. else
  53106. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53107. }
  53108. else {
  53109. propertyPath = value;
  53110. }
  53111. parameters.push(value);
  53112. }
  53113. }
  53114. if (combineArray === null) {
  53115. parameters.push(condition);
  53116. }
  53117. else {
  53118. parameters.push(null);
  53119. }
  53120. // If interpolate value action
  53121. if (parsedAction.name === "InterpolateValueAction") {
  53122. var param = parameters[parameters.length - 2];
  53123. parameters[parameters.length - 1] = param;
  53124. parameters[parameters.length - 2] = condition;
  53125. }
  53126. // Action or condition(s) and not CombineAction
  53127. var newAction = instanciate(parsedAction.name, parameters);
  53128. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53129. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53130. if (action)
  53131. action.then(nothing);
  53132. else
  53133. actionManager.registerAction(nothing);
  53134. action = nothing;
  53135. }
  53136. if (combineArray === null) {
  53137. if (newAction instanceof BABYLON.Condition) {
  53138. condition = newAction;
  53139. newAction = action;
  53140. }
  53141. else {
  53142. condition = null;
  53143. if (action)
  53144. action.then(newAction);
  53145. else
  53146. actionManager.registerAction(newAction);
  53147. }
  53148. }
  53149. else {
  53150. combineArray.push(newAction);
  53151. }
  53152. for (var i = 0; i < parsedAction.children.length; i++)
  53153. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53154. };
  53155. // triggers
  53156. for (var i = 0; i < parsedActions.children.length; i++) {
  53157. var triggerParams;
  53158. var trigger = parsedActions.children[i];
  53159. if (trigger.properties.length > 0) {
  53160. var param = trigger.properties[0].value;
  53161. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53162. if (value._meshId) {
  53163. value.mesh = scene.getMeshByID(value._meshId);
  53164. }
  53165. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53166. }
  53167. else
  53168. triggerParams = ActionManager[trigger.name];
  53169. for (var j = 0; j < trigger.children.length; j++) {
  53170. if (!trigger.detached)
  53171. traverse(trigger.children[j], triggerParams, null, null);
  53172. }
  53173. }
  53174. };
  53175. /**
  53176. * Get a trigger name by index
  53177. * @param trigger defines the trigger index
  53178. * @returns a trigger name
  53179. */
  53180. ActionManager.GetTriggerName = function (trigger) {
  53181. switch (trigger) {
  53182. case 0: return "NothingTrigger";
  53183. case 1: return "OnPickTrigger";
  53184. case 2: return "OnLeftPickTrigger";
  53185. case 3: return "OnRightPickTrigger";
  53186. case 4: return "OnCenterPickTrigger";
  53187. case 5: return "OnPickDownTrigger";
  53188. case 6: return "OnPickUpTrigger";
  53189. case 7: return "OnLongPressTrigger";
  53190. case 8: return "OnPointerOverTrigger";
  53191. case 9: return "OnPointerOutTrigger";
  53192. case 10: return "OnEveryFrameTrigger";
  53193. case 11: return "OnIntersectionEnterTrigger";
  53194. case 12: return "OnIntersectionExitTrigger";
  53195. case 13: return "OnKeyDownTrigger";
  53196. case 14: return "OnKeyUpTrigger";
  53197. case 15: return "OnPickOutTrigger";
  53198. default: return "";
  53199. }
  53200. };
  53201. // Statics
  53202. ActionManager._NothingTrigger = 0;
  53203. ActionManager._OnPickTrigger = 1;
  53204. ActionManager._OnLeftPickTrigger = 2;
  53205. ActionManager._OnRightPickTrigger = 3;
  53206. ActionManager._OnCenterPickTrigger = 4;
  53207. ActionManager._OnPickDownTrigger = 5;
  53208. ActionManager._OnDoublePickTrigger = 6;
  53209. ActionManager._OnPickUpTrigger = 7;
  53210. ActionManager._OnLongPressTrigger = 8;
  53211. ActionManager._OnPointerOverTrigger = 9;
  53212. ActionManager._OnPointerOutTrigger = 10;
  53213. ActionManager._OnEveryFrameTrigger = 11;
  53214. ActionManager._OnIntersectionEnterTrigger = 12;
  53215. ActionManager._OnIntersectionExitTrigger = 13;
  53216. ActionManager._OnKeyDownTrigger = 14;
  53217. ActionManager._OnKeyUpTrigger = 15;
  53218. ActionManager._OnPickOutTrigger = 16;
  53219. /** Gets the list of active triggers */
  53220. ActionManager.Triggers = {};
  53221. return ActionManager;
  53222. }());
  53223. BABYLON.ActionManager = ActionManager;
  53224. })(BABYLON || (BABYLON = {}));
  53225. //# sourceMappingURL=babylon.actionManager.js.map
  53226. var BABYLON;
  53227. (function (BABYLON) {
  53228. var InterpolateValueAction = /** @class */ (function (_super) {
  53229. __extends(InterpolateValueAction, _super);
  53230. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53231. if (duration === void 0) { duration = 1000; }
  53232. var _this = _super.call(this, triggerOptions, condition) || this;
  53233. _this.propertyPath = propertyPath;
  53234. _this.value = value;
  53235. _this.duration = duration;
  53236. _this.stopOtherAnimations = stopOtherAnimations;
  53237. _this.onInterpolationDone = onInterpolationDone;
  53238. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53239. _this._target = _this._effectiveTarget = target;
  53240. return _this;
  53241. }
  53242. InterpolateValueAction.prototype._prepare = function () {
  53243. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53244. this._property = this._getProperty(this.propertyPath);
  53245. };
  53246. InterpolateValueAction.prototype.execute = function () {
  53247. var _this = this;
  53248. var scene = this._actionManager.getScene();
  53249. var keys = [
  53250. {
  53251. frame: 0,
  53252. value: this._effectiveTarget[this._property]
  53253. }, {
  53254. frame: 100,
  53255. value: this.value
  53256. }
  53257. ];
  53258. var dataType;
  53259. if (typeof this.value === "number") {
  53260. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53261. }
  53262. else if (this.value instanceof BABYLON.Color3) {
  53263. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53264. }
  53265. else if (this.value instanceof BABYLON.Vector3) {
  53266. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53267. }
  53268. else if (this.value instanceof BABYLON.Matrix) {
  53269. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53270. }
  53271. else if (this.value instanceof BABYLON.Quaternion) {
  53272. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53273. }
  53274. else {
  53275. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53276. return;
  53277. }
  53278. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53279. animation.setKeys(keys);
  53280. if (this.stopOtherAnimations) {
  53281. scene.stopAnimation(this._effectiveTarget);
  53282. }
  53283. var wrapper = function () {
  53284. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53285. if (_this.onInterpolationDone) {
  53286. _this.onInterpolationDone();
  53287. }
  53288. };
  53289. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53290. };
  53291. InterpolateValueAction.prototype.serialize = function (parent) {
  53292. return _super.prototype._serialize.call(this, {
  53293. name: "InterpolateValueAction",
  53294. properties: [
  53295. BABYLON.Action._GetTargetProperty(this._target),
  53296. { name: "propertyPath", value: this.propertyPath },
  53297. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53298. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53299. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53300. ]
  53301. }, parent);
  53302. };
  53303. return InterpolateValueAction;
  53304. }(BABYLON.Action));
  53305. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53306. })(BABYLON || (BABYLON = {}));
  53307. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53308. var BABYLON;
  53309. (function (BABYLON) {
  53310. var SwitchBooleanAction = /** @class */ (function (_super) {
  53311. __extends(SwitchBooleanAction, _super);
  53312. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53313. var _this = _super.call(this, triggerOptions, condition) || this;
  53314. _this.propertyPath = propertyPath;
  53315. _this._target = _this._effectiveTarget = target;
  53316. return _this;
  53317. }
  53318. SwitchBooleanAction.prototype._prepare = function () {
  53319. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53320. this._property = this._getProperty(this.propertyPath);
  53321. };
  53322. SwitchBooleanAction.prototype.execute = function () {
  53323. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53324. };
  53325. SwitchBooleanAction.prototype.serialize = function (parent) {
  53326. return _super.prototype._serialize.call(this, {
  53327. name: "SwitchBooleanAction",
  53328. properties: [
  53329. BABYLON.Action._GetTargetProperty(this._target),
  53330. { name: "propertyPath", value: this.propertyPath }
  53331. ]
  53332. }, parent);
  53333. };
  53334. return SwitchBooleanAction;
  53335. }(BABYLON.Action));
  53336. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53337. var SetStateAction = /** @class */ (function (_super) {
  53338. __extends(SetStateAction, _super);
  53339. function SetStateAction(triggerOptions, target, value, condition) {
  53340. var _this = _super.call(this, triggerOptions, condition) || this;
  53341. _this.value = value;
  53342. _this._target = target;
  53343. return _this;
  53344. }
  53345. SetStateAction.prototype.execute = function () {
  53346. this._target.state = this.value;
  53347. };
  53348. SetStateAction.prototype.serialize = function (parent) {
  53349. return _super.prototype._serialize.call(this, {
  53350. name: "SetStateAction",
  53351. properties: [
  53352. BABYLON.Action._GetTargetProperty(this._target),
  53353. { name: "value", value: this.value }
  53354. ]
  53355. }, parent);
  53356. };
  53357. return SetStateAction;
  53358. }(BABYLON.Action));
  53359. BABYLON.SetStateAction = SetStateAction;
  53360. var SetValueAction = /** @class */ (function (_super) {
  53361. __extends(SetValueAction, _super);
  53362. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53363. var _this = _super.call(this, triggerOptions, condition) || this;
  53364. _this.propertyPath = propertyPath;
  53365. _this.value = value;
  53366. _this._target = _this._effectiveTarget = target;
  53367. return _this;
  53368. }
  53369. SetValueAction.prototype._prepare = function () {
  53370. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53371. this._property = this._getProperty(this.propertyPath);
  53372. };
  53373. SetValueAction.prototype.execute = function () {
  53374. this._effectiveTarget[this._property] = this.value;
  53375. if (this._target.markAsDirty) {
  53376. this._target.markAsDirty(this._property);
  53377. }
  53378. };
  53379. SetValueAction.prototype.serialize = function (parent) {
  53380. return _super.prototype._serialize.call(this, {
  53381. name: "SetValueAction",
  53382. properties: [
  53383. BABYLON.Action._GetTargetProperty(this._target),
  53384. { name: "propertyPath", value: this.propertyPath },
  53385. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53386. ]
  53387. }, parent);
  53388. };
  53389. return SetValueAction;
  53390. }(BABYLON.Action));
  53391. BABYLON.SetValueAction = SetValueAction;
  53392. var IncrementValueAction = /** @class */ (function (_super) {
  53393. __extends(IncrementValueAction, _super);
  53394. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53395. var _this = _super.call(this, triggerOptions, condition) || this;
  53396. _this.propertyPath = propertyPath;
  53397. _this.value = value;
  53398. _this._target = _this._effectiveTarget = target;
  53399. return _this;
  53400. }
  53401. IncrementValueAction.prototype._prepare = function () {
  53402. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53403. this._property = this._getProperty(this.propertyPath);
  53404. if (typeof this._effectiveTarget[this._property] !== "number") {
  53405. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53406. }
  53407. };
  53408. IncrementValueAction.prototype.execute = function () {
  53409. this._effectiveTarget[this._property] += this.value;
  53410. if (this._target.markAsDirty) {
  53411. this._target.markAsDirty(this._property);
  53412. }
  53413. };
  53414. IncrementValueAction.prototype.serialize = function (parent) {
  53415. return _super.prototype._serialize.call(this, {
  53416. name: "IncrementValueAction",
  53417. properties: [
  53418. BABYLON.Action._GetTargetProperty(this._target),
  53419. { name: "propertyPath", value: this.propertyPath },
  53420. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53421. ]
  53422. }, parent);
  53423. };
  53424. return IncrementValueAction;
  53425. }(BABYLON.Action));
  53426. BABYLON.IncrementValueAction = IncrementValueAction;
  53427. var PlayAnimationAction = /** @class */ (function (_super) {
  53428. __extends(PlayAnimationAction, _super);
  53429. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53430. var _this = _super.call(this, triggerOptions, condition) || this;
  53431. _this.from = from;
  53432. _this.to = to;
  53433. _this.loop = loop;
  53434. _this._target = target;
  53435. return _this;
  53436. }
  53437. PlayAnimationAction.prototype._prepare = function () {
  53438. };
  53439. PlayAnimationAction.prototype.execute = function () {
  53440. var scene = this._actionManager.getScene();
  53441. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53442. };
  53443. PlayAnimationAction.prototype.serialize = function (parent) {
  53444. return _super.prototype._serialize.call(this, {
  53445. name: "PlayAnimationAction",
  53446. properties: [
  53447. BABYLON.Action._GetTargetProperty(this._target),
  53448. { name: "from", value: String(this.from) },
  53449. { name: "to", value: String(this.to) },
  53450. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53451. ]
  53452. }, parent);
  53453. };
  53454. return PlayAnimationAction;
  53455. }(BABYLON.Action));
  53456. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53457. var StopAnimationAction = /** @class */ (function (_super) {
  53458. __extends(StopAnimationAction, _super);
  53459. function StopAnimationAction(triggerOptions, target, condition) {
  53460. var _this = _super.call(this, triggerOptions, condition) || this;
  53461. _this._target = target;
  53462. return _this;
  53463. }
  53464. StopAnimationAction.prototype._prepare = function () {
  53465. };
  53466. StopAnimationAction.prototype.execute = function () {
  53467. var scene = this._actionManager.getScene();
  53468. scene.stopAnimation(this._target);
  53469. };
  53470. StopAnimationAction.prototype.serialize = function (parent) {
  53471. return _super.prototype._serialize.call(this, {
  53472. name: "StopAnimationAction",
  53473. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53474. }, parent);
  53475. };
  53476. return StopAnimationAction;
  53477. }(BABYLON.Action));
  53478. BABYLON.StopAnimationAction = StopAnimationAction;
  53479. var DoNothingAction = /** @class */ (function (_super) {
  53480. __extends(DoNothingAction, _super);
  53481. function DoNothingAction(triggerOptions, condition) {
  53482. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53483. return _super.call(this, triggerOptions, condition) || this;
  53484. }
  53485. DoNothingAction.prototype.execute = function () {
  53486. };
  53487. DoNothingAction.prototype.serialize = function (parent) {
  53488. return _super.prototype._serialize.call(this, {
  53489. name: "DoNothingAction",
  53490. properties: []
  53491. }, parent);
  53492. };
  53493. return DoNothingAction;
  53494. }(BABYLON.Action));
  53495. BABYLON.DoNothingAction = DoNothingAction;
  53496. var CombineAction = /** @class */ (function (_super) {
  53497. __extends(CombineAction, _super);
  53498. function CombineAction(triggerOptions, children, condition) {
  53499. var _this = _super.call(this, triggerOptions, condition) || this;
  53500. _this.children = children;
  53501. return _this;
  53502. }
  53503. CombineAction.prototype._prepare = function () {
  53504. for (var index = 0; index < this.children.length; index++) {
  53505. this.children[index]._actionManager = this._actionManager;
  53506. this.children[index]._prepare();
  53507. }
  53508. };
  53509. CombineAction.prototype.execute = function (evt) {
  53510. for (var index = 0; index < this.children.length; index++) {
  53511. this.children[index].execute(evt);
  53512. }
  53513. };
  53514. CombineAction.prototype.serialize = function (parent) {
  53515. var serializationObject = _super.prototype._serialize.call(this, {
  53516. name: "CombineAction",
  53517. properties: [],
  53518. combine: []
  53519. }, parent);
  53520. for (var i = 0; i < this.children.length; i++) {
  53521. serializationObject.combine.push(this.children[i].serialize(null));
  53522. }
  53523. return serializationObject;
  53524. };
  53525. return CombineAction;
  53526. }(BABYLON.Action));
  53527. BABYLON.CombineAction = CombineAction;
  53528. var ExecuteCodeAction = /** @class */ (function (_super) {
  53529. __extends(ExecuteCodeAction, _super);
  53530. function ExecuteCodeAction(triggerOptions, func, condition) {
  53531. var _this = _super.call(this, triggerOptions, condition) || this;
  53532. _this.func = func;
  53533. return _this;
  53534. }
  53535. ExecuteCodeAction.prototype.execute = function (evt) {
  53536. this.func(evt);
  53537. };
  53538. return ExecuteCodeAction;
  53539. }(BABYLON.Action));
  53540. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53541. var SetParentAction = /** @class */ (function (_super) {
  53542. __extends(SetParentAction, _super);
  53543. function SetParentAction(triggerOptions, target, parent, condition) {
  53544. var _this = _super.call(this, triggerOptions, condition) || this;
  53545. _this._target = target;
  53546. _this._parent = parent;
  53547. return _this;
  53548. }
  53549. SetParentAction.prototype._prepare = function () {
  53550. };
  53551. SetParentAction.prototype.execute = function () {
  53552. if (this._target.parent === this._parent) {
  53553. return;
  53554. }
  53555. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53556. invertParentWorldMatrix.invert();
  53557. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53558. this._target.parent = this._parent;
  53559. };
  53560. SetParentAction.prototype.serialize = function (parent) {
  53561. return _super.prototype._serialize.call(this, {
  53562. name: "SetParentAction",
  53563. properties: [
  53564. BABYLON.Action._GetTargetProperty(this._target),
  53565. BABYLON.Action._GetTargetProperty(this._parent),
  53566. ]
  53567. }, parent);
  53568. };
  53569. return SetParentAction;
  53570. }(BABYLON.Action));
  53571. BABYLON.SetParentAction = SetParentAction;
  53572. var PlaySoundAction = /** @class */ (function (_super) {
  53573. __extends(PlaySoundAction, _super);
  53574. function PlaySoundAction(triggerOptions, sound, condition) {
  53575. var _this = _super.call(this, triggerOptions, condition) || this;
  53576. _this._sound = sound;
  53577. return _this;
  53578. }
  53579. PlaySoundAction.prototype._prepare = function () {
  53580. };
  53581. PlaySoundAction.prototype.execute = function () {
  53582. if (this._sound !== undefined)
  53583. this._sound.play();
  53584. };
  53585. PlaySoundAction.prototype.serialize = function (parent) {
  53586. return _super.prototype._serialize.call(this, {
  53587. name: "PlaySoundAction",
  53588. properties: [{ name: "sound", value: this._sound.name }]
  53589. }, parent);
  53590. };
  53591. return PlaySoundAction;
  53592. }(BABYLON.Action));
  53593. BABYLON.PlaySoundAction = PlaySoundAction;
  53594. var StopSoundAction = /** @class */ (function (_super) {
  53595. __extends(StopSoundAction, _super);
  53596. function StopSoundAction(triggerOptions, sound, condition) {
  53597. var _this = _super.call(this, triggerOptions, condition) || this;
  53598. _this._sound = sound;
  53599. return _this;
  53600. }
  53601. StopSoundAction.prototype._prepare = function () {
  53602. };
  53603. StopSoundAction.prototype.execute = function () {
  53604. if (this._sound !== undefined)
  53605. this._sound.stop();
  53606. };
  53607. StopSoundAction.prototype.serialize = function (parent) {
  53608. return _super.prototype._serialize.call(this, {
  53609. name: "StopSoundAction",
  53610. properties: [{ name: "sound", value: this._sound.name }]
  53611. }, parent);
  53612. };
  53613. return StopSoundAction;
  53614. }(BABYLON.Action));
  53615. BABYLON.StopSoundAction = StopSoundAction;
  53616. })(BABYLON || (BABYLON = {}));
  53617. //# sourceMappingURL=babylon.directActions.js.map
  53618. var BABYLON;
  53619. (function (BABYLON) {
  53620. var SpriteManager = /** @class */ (function () {
  53621. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53622. if (epsilon === void 0) { epsilon = 0.01; }
  53623. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53624. this.name = name;
  53625. this.sprites = new Array();
  53626. this.renderingGroupId = 0;
  53627. this.layerMask = 0x0FFFFFFF;
  53628. this.fogEnabled = true;
  53629. this.isPickable = false;
  53630. /**
  53631. * An event triggered when the manager is disposed.
  53632. */
  53633. this.onDisposeObservable = new BABYLON.Observable();
  53634. this._vertexBuffers = {};
  53635. this._capacity = capacity;
  53636. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53637. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53638. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53639. if (cellSize.width && cellSize.height) {
  53640. this.cellWidth = cellSize.width;
  53641. this.cellHeight = cellSize.height;
  53642. }
  53643. else if (cellSize !== undefined) {
  53644. this.cellWidth = cellSize;
  53645. this.cellHeight = cellSize;
  53646. }
  53647. else {
  53648. return;
  53649. }
  53650. this._epsilon = epsilon;
  53651. this._scene = scene;
  53652. this._scene.spriteManagers.push(this);
  53653. var indices = [];
  53654. var index = 0;
  53655. for (var count = 0; count < capacity; count++) {
  53656. indices.push(index);
  53657. indices.push(index + 1);
  53658. indices.push(index + 2);
  53659. indices.push(index);
  53660. indices.push(index + 2);
  53661. indices.push(index + 3);
  53662. index += 4;
  53663. }
  53664. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53665. // VBO
  53666. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53667. this._vertexData = new Float32Array(capacity * 16 * 4);
  53668. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53669. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53670. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53671. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53672. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53673. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53674. this._vertexBuffers["options"] = options;
  53675. this._vertexBuffers["cellInfo"] = cellInfo;
  53676. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53677. // Effects
  53678. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53679. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53680. }
  53681. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53682. set: function (callback) {
  53683. if (this._onDisposeObserver) {
  53684. this.onDisposeObservable.remove(this._onDisposeObserver);
  53685. }
  53686. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53687. },
  53688. enumerable: true,
  53689. configurable: true
  53690. });
  53691. Object.defineProperty(SpriteManager.prototype, "texture", {
  53692. get: function () {
  53693. return this._spriteTexture;
  53694. },
  53695. set: function (value) {
  53696. this._spriteTexture = value;
  53697. },
  53698. enumerable: true,
  53699. configurable: true
  53700. });
  53701. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53702. var arrayOffset = index * 16;
  53703. if (offsetX === 0)
  53704. offsetX = this._epsilon;
  53705. else if (offsetX === 1)
  53706. offsetX = 1 - this._epsilon;
  53707. if (offsetY === 0)
  53708. offsetY = this._epsilon;
  53709. else if (offsetY === 1)
  53710. offsetY = 1 - this._epsilon;
  53711. this._vertexData[arrayOffset] = sprite.position.x;
  53712. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53713. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53714. this._vertexData[arrayOffset + 3] = sprite.angle;
  53715. this._vertexData[arrayOffset + 4] = sprite.width;
  53716. this._vertexData[arrayOffset + 5] = sprite.height;
  53717. this._vertexData[arrayOffset + 6] = offsetX;
  53718. this._vertexData[arrayOffset + 7] = offsetY;
  53719. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53720. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53721. var offset = (sprite.cellIndex / rowSize) >> 0;
  53722. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53723. this._vertexData[arrayOffset + 11] = offset;
  53724. // Color
  53725. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53726. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53727. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53728. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53729. };
  53730. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53731. var count = Math.min(this._capacity, this.sprites.length);
  53732. var min = BABYLON.Vector3.Zero();
  53733. var max = BABYLON.Vector3.Zero();
  53734. var distance = Number.MAX_VALUE;
  53735. var currentSprite = null;
  53736. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53737. var cameraView = camera.getViewMatrix();
  53738. for (var index = 0; index < count; index++) {
  53739. var sprite = this.sprites[index];
  53740. if (!sprite) {
  53741. continue;
  53742. }
  53743. if (predicate) {
  53744. if (!predicate(sprite)) {
  53745. continue;
  53746. }
  53747. }
  53748. else if (!sprite.isPickable) {
  53749. continue;
  53750. }
  53751. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53752. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53753. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53754. if (ray.intersectsBoxMinMax(min, max)) {
  53755. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53756. if (distance > currentDistance) {
  53757. distance = currentDistance;
  53758. currentSprite = sprite;
  53759. if (fastCheck) {
  53760. break;
  53761. }
  53762. }
  53763. }
  53764. }
  53765. if (currentSprite) {
  53766. var result = new BABYLON.PickingInfo();
  53767. result.hit = true;
  53768. result.pickedSprite = currentSprite;
  53769. result.distance = distance;
  53770. return result;
  53771. }
  53772. return null;
  53773. };
  53774. SpriteManager.prototype.render = function () {
  53775. // Check
  53776. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53777. return;
  53778. var engine = this._scene.getEngine();
  53779. var baseSize = this._spriteTexture.getBaseSize();
  53780. // Sprites
  53781. var deltaTime = engine.getDeltaTime();
  53782. var max = Math.min(this._capacity, this.sprites.length);
  53783. var rowSize = baseSize.width / this.cellWidth;
  53784. var offset = 0;
  53785. for (var index = 0; index < max; index++) {
  53786. var sprite = this.sprites[index];
  53787. if (!sprite || !sprite.isVisible) {
  53788. continue;
  53789. }
  53790. sprite._animate(deltaTime);
  53791. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53792. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53793. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53794. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53795. }
  53796. this._buffer.update(this._vertexData);
  53797. // Render
  53798. var effect = this._effectBase;
  53799. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53800. effect = this._effectFog;
  53801. }
  53802. engine.enableEffect(effect);
  53803. var viewMatrix = this._scene.getViewMatrix();
  53804. effect.setTexture("diffuseSampler", this._spriteTexture);
  53805. effect.setMatrix("view", viewMatrix);
  53806. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53807. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53808. // Fog
  53809. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53810. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53811. effect.setColor3("vFogColor", this._scene.fogColor);
  53812. }
  53813. // VBOs
  53814. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53815. // Draw order
  53816. engine.setDepthFunctionToLessOrEqual();
  53817. effect.setBool("alphaTest", true);
  53818. engine.setColorWrite(false);
  53819. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53820. engine.setColorWrite(true);
  53821. effect.setBool("alphaTest", false);
  53822. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53823. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53824. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53825. };
  53826. SpriteManager.prototype.dispose = function () {
  53827. if (this._buffer) {
  53828. this._buffer.dispose();
  53829. this._buffer = null;
  53830. }
  53831. if (this._indexBuffer) {
  53832. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53833. this._indexBuffer = null;
  53834. }
  53835. if (this._spriteTexture) {
  53836. this._spriteTexture.dispose();
  53837. this._spriteTexture = null;
  53838. }
  53839. // Remove from scene
  53840. var index = this._scene.spriteManagers.indexOf(this);
  53841. this._scene.spriteManagers.splice(index, 1);
  53842. // Callback
  53843. this.onDisposeObservable.notifyObservers(this);
  53844. this.onDisposeObservable.clear();
  53845. };
  53846. return SpriteManager;
  53847. }());
  53848. BABYLON.SpriteManager = SpriteManager;
  53849. })(BABYLON || (BABYLON = {}));
  53850. //# sourceMappingURL=babylon.spriteManager.js.map
  53851. var BABYLON;
  53852. (function (BABYLON) {
  53853. var Sprite = /** @class */ (function () {
  53854. function Sprite(name, manager) {
  53855. this.name = name;
  53856. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53857. this.width = 1.0;
  53858. this.height = 1.0;
  53859. this.angle = 0;
  53860. this.cellIndex = 0;
  53861. this.invertU = 0;
  53862. this.invertV = 0;
  53863. this.animations = new Array();
  53864. this.isPickable = false;
  53865. this._animationStarted = false;
  53866. this._loopAnimation = false;
  53867. this._fromIndex = 0;
  53868. this._toIndex = 0;
  53869. this._delay = 0;
  53870. this._direction = 1;
  53871. this._time = 0;
  53872. /**
  53873. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53874. */
  53875. this.isVisible = true;
  53876. this._manager = manager;
  53877. this._manager.sprites.push(this);
  53878. this.position = BABYLON.Vector3.Zero();
  53879. }
  53880. Object.defineProperty(Sprite.prototype, "size", {
  53881. get: function () {
  53882. return this.width;
  53883. },
  53884. set: function (value) {
  53885. this.width = value;
  53886. this.height = value;
  53887. },
  53888. enumerable: true,
  53889. configurable: true
  53890. });
  53891. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53892. this._fromIndex = from;
  53893. this._toIndex = to;
  53894. this._loopAnimation = loop;
  53895. this._delay = delay;
  53896. this._animationStarted = true;
  53897. this._direction = from < to ? 1 : -1;
  53898. this.cellIndex = from;
  53899. this._time = 0;
  53900. this._onAnimationEnd = onAnimationEnd;
  53901. };
  53902. Sprite.prototype.stopAnimation = function () {
  53903. this._animationStarted = false;
  53904. };
  53905. Sprite.prototype._animate = function (deltaTime) {
  53906. if (!this._animationStarted)
  53907. return;
  53908. this._time += deltaTime;
  53909. if (this._time > this._delay) {
  53910. this._time = this._time % this._delay;
  53911. this.cellIndex += this._direction;
  53912. if (this.cellIndex > this._toIndex) {
  53913. if (this._loopAnimation) {
  53914. this.cellIndex = this._fromIndex;
  53915. }
  53916. else {
  53917. this.cellIndex = this._toIndex;
  53918. this._animationStarted = false;
  53919. if (this._onAnimationEnd) {
  53920. this._onAnimationEnd();
  53921. }
  53922. if (this.disposeWhenFinishedAnimating) {
  53923. this.dispose();
  53924. }
  53925. }
  53926. }
  53927. }
  53928. };
  53929. Sprite.prototype.dispose = function () {
  53930. for (var i = 0; i < this._manager.sprites.length; i++) {
  53931. if (this._manager.sprites[i] == this) {
  53932. this._manager.sprites.splice(i, 1);
  53933. }
  53934. }
  53935. };
  53936. return Sprite;
  53937. }());
  53938. BABYLON.Sprite = Sprite;
  53939. })(BABYLON || (BABYLON = {}));
  53940. //# sourceMappingURL=babylon.sprite.js.map
  53941. var BABYLON;
  53942. (function (BABYLON) {
  53943. var IntersectionInfo = /** @class */ (function () {
  53944. function IntersectionInfo(bu, bv, distance) {
  53945. this.bu = bu;
  53946. this.bv = bv;
  53947. this.distance = distance;
  53948. this.faceId = 0;
  53949. this.subMeshId = 0;
  53950. }
  53951. return IntersectionInfo;
  53952. }());
  53953. BABYLON.IntersectionInfo = IntersectionInfo;
  53954. /**
  53955. * Information about the result of picking within a scene
  53956. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53957. */
  53958. var PickingInfo = /** @class */ (function () {
  53959. function PickingInfo() {
  53960. /**
  53961. * If the pick collided with an object
  53962. */
  53963. this.hit = false;
  53964. /**
  53965. * Distance away where the pick collided
  53966. */
  53967. this.distance = 0;
  53968. /**
  53969. * The location of pick collision
  53970. */
  53971. this.pickedPoint = null;
  53972. /**
  53973. * The mesh corrisponding the the pick collision
  53974. */
  53975. this.pickedMesh = null;
  53976. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53977. this.bu = 0;
  53978. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53979. this.bv = 0;
  53980. /** The id of the face on the mesh that was picked */
  53981. this.faceId = -1;
  53982. /** Id of the the submesh that was picked */
  53983. this.subMeshId = 0;
  53984. /** If a sprite was picked, this will be the sprite the pick collided with */
  53985. this.pickedSprite = null;
  53986. /**
  53987. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53988. */
  53989. this.originMesh = null;
  53990. /**
  53991. * The ray that was used to perform the picking.
  53992. */
  53993. this.ray = null;
  53994. }
  53995. /**
  53996. * Gets the normal corrispodning to the face the pick collided with
  53997. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53998. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53999. * @returns The normal corrispodning to the face the pick collided with
  54000. */
  54001. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54002. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54003. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54004. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54005. return null;
  54006. }
  54007. var indices = this.pickedMesh.getIndices();
  54008. if (!indices) {
  54009. return null;
  54010. }
  54011. var result;
  54012. if (useVerticesNormals) {
  54013. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54014. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54015. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54016. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54017. normal0 = normal0.scale(this.bu);
  54018. normal1 = normal1.scale(this.bv);
  54019. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54020. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54021. }
  54022. else {
  54023. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54024. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54025. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54026. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54027. var p1p2 = vertex1.subtract(vertex2);
  54028. var p3p2 = vertex3.subtract(vertex2);
  54029. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54030. }
  54031. if (useWorldCoordinates) {
  54032. var wm = this.pickedMesh.getWorldMatrix();
  54033. if (this.pickedMesh.nonUniformScaling) {
  54034. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54035. wm = BABYLON.Tmp.Matrix[0];
  54036. wm.setTranslationFromFloats(0, 0, 0);
  54037. wm.invert();
  54038. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54039. wm = BABYLON.Tmp.Matrix[1];
  54040. }
  54041. result = BABYLON.Vector3.TransformNormal(result, wm);
  54042. }
  54043. result.normalize();
  54044. return result;
  54045. };
  54046. /**
  54047. * Gets the texture coordinates of where the pick occured
  54048. * @returns the vector containing the coordnates of the texture
  54049. */
  54050. PickingInfo.prototype.getTextureCoordinates = function () {
  54051. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54052. return null;
  54053. }
  54054. var indices = this.pickedMesh.getIndices();
  54055. if (!indices) {
  54056. return null;
  54057. }
  54058. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54059. if (!uvs) {
  54060. return null;
  54061. }
  54062. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54063. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54064. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54065. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54066. uv1 = uv1.scale(this.bu);
  54067. uv2 = uv2.scale(this.bv);
  54068. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54069. };
  54070. return PickingInfo;
  54071. }());
  54072. BABYLON.PickingInfo = PickingInfo;
  54073. })(BABYLON || (BABYLON = {}));
  54074. //# sourceMappingURL=babylon.pickingInfo.js.map
  54075. var BABYLON;
  54076. (function (BABYLON) {
  54077. var Ray = /** @class */ (function () {
  54078. function Ray(origin, direction, length) {
  54079. if (length === void 0) { length = Number.MAX_VALUE; }
  54080. this.origin = origin;
  54081. this.direction = direction;
  54082. this.length = length;
  54083. }
  54084. // Methods
  54085. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54086. var d = 0.0;
  54087. var maxValue = Number.MAX_VALUE;
  54088. var inv;
  54089. var min;
  54090. var max;
  54091. var temp;
  54092. if (Math.abs(this.direction.x) < 0.0000001) {
  54093. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54094. return false;
  54095. }
  54096. }
  54097. else {
  54098. inv = 1.0 / this.direction.x;
  54099. min = (minimum.x - this.origin.x) * inv;
  54100. max = (maximum.x - this.origin.x) * inv;
  54101. if (max === -Infinity) {
  54102. max = Infinity;
  54103. }
  54104. if (min > max) {
  54105. temp = min;
  54106. min = max;
  54107. max = temp;
  54108. }
  54109. d = Math.max(min, d);
  54110. maxValue = Math.min(max, maxValue);
  54111. if (d > maxValue) {
  54112. return false;
  54113. }
  54114. }
  54115. if (Math.abs(this.direction.y) < 0.0000001) {
  54116. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54117. return false;
  54118. }
  54119. }
  54120. else {
  54121. inv = 1.0 / this.direction.y;
  54122. min = (minimum.y - this.origin.y) * inv;
  54123. max = (maximum.y - this.origin.y) * inv;
  54124. if (max === -Infinity) {
  54125. max = Infinity;
  54126. }
  54127. if (min > max) {
  54128. temp = min;
  54129. min = max;
  54130. max = temp;
  54131. }
  54132. d = Math.max(min, d);
  54133. maxValue = Math.min(max, maxValue);
  54134. if (d > maxValue) {
  54135. return false;
  54136. }
  54137. }
  54138. if (Math.abs(this.direction.z) < 0.0000001) {
  54139. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54140. return false;
  54141. }
  54142. }
  54143. else {
  54144. inv = 1.0 / this.direction.z;
  54145. min = (minimum.z - this.origin.z) * inv;
  54146. max = (maximum.z - this.origin.z) * inv;
  54147. if (max === -Infinity) {
  54148. max = Infinity;
  54149. }
  54150. if (min > max) {
  54151. temp = min;
  54152. min = max;
  54153. max = temp;
  54154. }
  54155. d = Math.max(min, d);
  54156. maxValue = Math.min(max, maxValue);
  54157. if (d > maxValue) {
  54158. return false;
  54159. }
  54160. }
  54161. return true;
  54162. };
  54163. Ray.prototype.intersectsBox = function (box) {
  54164. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54165. };
  54166. Ray.prototype.intersectsSphere = function (sphere) {
  54167. var x = sphere.center.x - this.origin.x;
  54168. var y = sphere.center.y - this.origin.y;
  54169. var z = sphere.center.z - this.origin.z;
  54170. var pyth = (x * x) + (y * y) + (z * z);
  54171. var rr = sphere.radius * sphere.radius;
  54172. if (pyth <= rr) {
  54173. return true;
  54174. }
  54175. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54176. if (dot < 0.0) {
  54177. return false;
  54178. }
  54179. var temp = pyth - (dot * dot);
  54180. return temp <= rr;
  54181. };
  54182. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54183. if (!this._edge1) {
  54184. this._edge1 = BABYLON.Vector3.Zero();
  54185. this._edge2 = BABYLON.Vector3.Zero();
  54186. this._pvec = BABYLON.Vector3.Zero();
  54187. this._tvec = BABYLON.Vector3.Zero();
  54188. this._qvec = BABYLON.Vector3.Zero();
  54189. }
  54190. vertex1.subtractToRef(vertex0, this._edge1);
  54191. vertex2.subtractToRef(vertex0, this._edge2);
  54192. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54193. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54194. if (det === 0) {
  54195. return null;
  54196. }
  54197. var invdet = 1 / det;
  54198. this.origin.subtractToRef(vertex0, this._tvec);
  54199. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54200. if (bu < 0 || bu > 1.0) {
  54201. return null;
  54202. }
  54203. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54204. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54205. if (bv < 0 || bu + bv > 1.0) {
  54206. return null;
  54207. }
  54208. //check if the distance is longer than the predefined length.
  54209. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54210. if (distance > this.length) {
  54211. return null;
  54212. }
  54213. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54214. };
  54215. Ray.prototype.intersectsPlane = function (plane) {
  54216. var distance;
  54217. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54218. if (Math.abs(result1) < 9.99999997475243E-07) {
  54219. return null;
  54220. }
  54221. else {
  54222. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54223. distance = (-plane.d - result2) / result1;
  54224. if (distance < 0.0) {
  54225. if (distance < -9.99999997475243E-07) {
  54226. return null;
  54227. }
  54228. else {
  54229. return 0;
  54230. }
  54231. }
  54232. return distance;
  54233. }
  54234. };
  54235. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54236. var tm = BABYLON.Tmp.Matrix[0];
  54237. mesh.getWorldMatrix().invertToRef(tm);
  54238. if (this._tmpRay) {
  54239. Ray.TransformToRef(this, tm, this._tmpRay);
  54240. }
  54241. else {
  54242. this._tmpRay = Ray.Transform(this, tm);
  54243. }
  54244. return mesh.intersects(this._tmpRay, fastCheck);
  54245. };
  54246. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54247. if (results) {
  54248. results.length = 0;
  54249. }
  54250. else {
  54251. results = [];
  54252. }
  54253. for (var i = 0; i < meshes.length; i++) {
  54254. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54255. if (pickInfo.hit) {
  54256. results.push(pickInfo);
  54257. }
  54258. }
  54259. results.sort(this._comparePickingInfo);
  54260. return results;
  54261. };
  54262. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54263. if (pickingInfoA.distance < pickingInfoB.distance) {
  54264. return -1;
  54265. }
  54266. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54267. return 1;
  54268. }
  54269. else {
  54270. return 0;
  54271. }
  54272. };
  54273. /**
  54274. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54275. * @param sega the first point of the segment to test the intersection against
  54276. * @param segb the second point of the segment to test the intersection against
  54277. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54278. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54279. */
  54280. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54281. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54282. var u = segb.subtract(sega);
  54283. var v = rsegb.subtract(this.origin);
  54284. var w = sega.subtract(this.origin);
  54285. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54286. var b = BABYLON.Vector3.Dot(u, v);
  54287. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54288. var d = BABYLON.Vector3.Dot(u, w);
  54289. var e = BABYLON.Vector3.Dot(v, w);
  54290. var D = a * c - b * b; // always >= 0
  54291. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54292. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54293. // compute the line parameters of the two closest points
  54294. if (D < Ray.smallnum) { // the lines are almost parallel
  54295. sN = 0.0; // force using point P0 on segment S1
  54296. sD = 1.0; // to prevent possible division by 0.0 later
  54297. tN = e;
  54298. tD = c;
  54299. }
  54300. else { // get the closest points on the infinite lines
  54301. sN = (b * e - c * d);
  54302. tN = (a * e - b * d);
  54303. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54304. sN = 0.0;
  54305. tN = e;
  54306. tD = c;
  54307. }
  54308. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54309. sN = sD;
  54310. tN = e + b;
  54311. tD = c;
  54312. }
  54313. }
  54314. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54315. tN = 0.0;
  54316. // recompute sc for this edge
  54317. if (-d < 0.0) {
  54318. sN = 0.0;
  54319. }
  54320. else if (-d > a)
  54321. sN = sD;
  54322. else {
  54323. sN = -d;
  54324. sD = a;
  54325. }
  54326. }
  54327. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54328. tN = tD;
  54329. // recompute sc for this edge
  54330. if ((-d + b) < 0.0) {
  54331. sN = 0;
  54332. }
  54333. else if ((-d + b) > a) {
  54334. sN = sD;
  54335. }
  54336. else {
  54337. sN = (-d + b);
  54338. sD = a;
  54339. }
  54340. }
  54341. // finally do the division to get sc and tc
  54342. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54343. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54344. // get the difference of the two closest points
  54345. var qtc = v.multiplyByFloats(tc, tc, tc);
  54346. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54347. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54348. if (isIntersected) {
  54349. return qtc.length();
  54350. }
  54351. return -1;
  54352. };
  54353. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54354. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54355. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54356. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54357. this.direction.normalize();
  54358. return this;
  54359. };
  54360. // Statics
  54361. Ray.Zero = function () {
  54362. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54363. };
  54364. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54365. var result = Ray.Zero();
  54366. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54367. };
  54368. /**
  54369. * 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
  54370. * transformed to the given world matrix.
  54371. * @param origin The origin point
  54372. * @param end The end point
  54373. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54374. */
  54375. Ray.CreateNewFromTo = function (origin, end, world) {
  54376. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54377. var direction = end.subtract(origin);
  54378. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54379. direction.normalize();
  54380. return Ray.Transform(new Ray(origin, direction, length), world);
  54381. };
  54382. Ray.Transform = function (ray, matrix) {
  54383. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54384. Ray.TransformToRef(ray, matrix, result);
  54385. return result;
  54386. };
  54387. Ray.TransformToRef = function (ray, matrix, result) {
  54388. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54389. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54390. result.length = ray.length;
  54391. var dir = result.direction;
  54392. var len = dir.length();
  54393. if (!(len === 0 || len === 1)) {
  54394. var num = 1.0 / len;
  54395. dir.x *= num;
  54396. dir.y *= num;
  54397. dir.z *= num;
  54398. result.length *= len;
  54399. }
  54400. };
  54401. Ray.smallnum = 0.00000001;
  54402. Ray.rayl = 10e8;
  54403. return Ray;
  54404. }());
  54405. BABYLON.Ray = Ray;
  54406. })(BABYLON || (BABYLON = {}));
  54407. //# sourceMappingURL=babylon.ray.js.map
  54408. var BABYLON;
  54409. (function (BABYLON) {
  54410. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54411. if (boxMin.x > sphereCenter.x + sphereRadius)
  54412. return false;
  54413. if (sphereCenter.x - sphereRadius > boxMax.x)
  54414. return false;
  54415. if (boxMin.y > sphereCenter.y + sphereRadius)
  54416. return false;
  54417. if (sphereCenter.y - sphereRadius > boxMax.y)
  54418. return false;
  54419. if (boxMin.z > sphereCenter.z + sphereRadius)
  54420. return false;
  54421. if (sphereCenter.z - sphereRadius > boxMax.z)
  54422. return false;
  54423. return true;
  54424. };
  54425. var getLowestRoot = (function () {
  54426. var result = { root: 0, found: false };
  54427. return function (a, b, c, maxR) {
  54428. result.root = 0;
  54429. result.found = false;
  54430. var determinant = b * b - 4.0 * a * c;
  54431. if (determinant < 0)
  54432. return result;
  54433. var sqrtD = Math.sqrt(determinant);
  54434. var r1 = (-b - sqrtD) / (2.0 * a);
  54435. var r2 = (-b + sqrtD) / (2.0 * a);
  54436. if (r1 > r2) {
  54437. var temp = r2;
  54438. r2 = r1;
  54439. r1 = temp;
  54440. }
  54441. if (r1 > 0 && r1 < maxR) {
  54442. result.root = r1;
  54443. result.found = true;
  54444. return result;
  54445. }
  54446. if (r2 > 0 && r2 < maxR) {
  54447. result.root = r2;
  54448. result.found = true;
  54449. return result;
  54450. }
  54451. return result;
  54452. };
  54453. })();
  54454. var Collider = /** @class */ (function () {
  54455. function Collider() {
  54456. this._collisionPoint = BABYLON.Vector3.Zero();
  54457. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54458. this._tempVector = BABYLON.Vector3.Zero();
  54459. this._tempVector2 = BABYLON.Vector3.Zero();
  54460. this._tempVector3 = BABYLON.Vector3.Zero();
  54461. this._tempVector4 = BABYLON.Vector3.Zero();
  54462. this._edge = BABYLON.Vector3.Zero();
  54463. this._baseToVertex = BABYLON.Vector3.Zero();
  54464. this._destinationPoint = BABYLON.Vector3.Zero();
  54465. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54466. this._displacementVector = BABYLON.Vector3.Zero();
  54467. this._radius = BABYLON.Vector3.One();
  54468. this._retry = 0;
  54469. this._basePointWorld = BABYLON.Vector3.Zero();
  54470. this._velocityWorld = BABYLON.Vector3.Zero();
  54471. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54472. this._collisionMask = -1;
  54473. }
  54474. Object.defineProperty(Collider.prototype, "collisionMask", {
  54475. get: function () {
  54476. return this._collisionMask;
  54477. },
  54478. set: function (mask) {
  54479. this._collisionMask = !isNaN(mask) ? mask : -1;
  54480. },
  54481. enumerable: true,
  54482. configurable: true
  54483. });
  54484. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54485. /**
  54486. * Gets the plane normal used to compute the sliding response (in local space)
  54487. */
  54488. get: function () {
  54489. return this._slidePlaneNormal;
  54490. },
  54491. enumerable: true,
  54492. configurable: true
  54493. });
  54494. // Methods
  54495. Collider.prototype._initialize = function (source, dir, e) {
  54496. this._velocity = dir;
  54497. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54498. this._basePoint = source;
  54499. source.multiplyToRef(this._radius, this._basePointWorld);
  54500. dir.multiplyToRef(this._radius, this._velocityWorld);
  54501. this._velocityWorldLength = this._velocityWorld.length();
  54502. this._epsilon = e;
  54503. this.collisionFound = false;
  54504. };
  54505. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54506. pa.subtractToRef(point, this._tempVector);
  54507. pb.subtractToRef(point, this._tempVector2);
  54508. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54509. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54510. if (d < 0)
  54511. return false;
  54512. pc.subtractToRef(point, this._tempVector3);
  54513. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54514. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54515. if (d < 0)
  54516. return false;
  54517. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54518. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54519. return d >= 0;
  54520. };
  54521. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54522. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54523. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54524. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54525. return false;
  54526. }
  54527. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54528. return false;
  54529. return true;
  54530. };
  54531. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54532. var t0;
  54533. var embeddedInPlane = false;
  54534. //defensive programming, actually not needed.
  54535. if (!trianglePlaneArray) {
  54536. trianglePlaneArray = [];
  54537. }
  54538. if (!trianglePlaneArray[faceIndex]) {
  54539. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54540. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54541. }
  54542. var trianglePlane = trianglePlaneArray[faceIndex];
  54543. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54544. return;
  54545. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54546. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54547. if (normalDotVelocity == 0) {
  54548. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54549. return;
  54550. embeddedInPlane = true;
  54551. t0 = 0;
  54552. }
  54553. else {
  54554. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54555. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54556. if (t0 > t1) {
  54557. var temp = t1;
  54558. t1 = t0;
  54559. t0 = temp;
  54560. }
  54561. if (t0 > 1.0 || t1 < 0.0)
  54562. return;
  54563. if (t0 < 0)
  54564. t0 = 0;
  54565. if (t0 > 1.0)
  54566. t0 = 1.0;
  54567. }
  54568. this._collisionPoint.copyFromFloats(0, 0, 0);
  54569. var found = false;
  54570. var t = 1.0;
  54571. if (!embeddedInPlane) {
  54572. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54573. this._velocity.scaleToRef(t0, this._tempVector);
  54574. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54575. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54576. found = true;
  54577. t = t0;
  54578. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54579. }
  54580. }
  54581. if (!found) {
  54582. var velocitySquaredLength = this._velocity.lengthSquared();
  54583. var a = velocitySquaredLength;
  54584. this._basePoint.subtractToRef(p1, this._tempVector);
  54585. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54586. var c = this._tempVector.lengthSquared() - 1.0;
  54587. var lowestRoot = getLowestRoot(a, b, c, t);
  54588. if (lowestRoot.found) {
  54589. t = lowestRoot.root;
  54590. found = true;
  54591. this._collisionPoint.copyFrom(p1);
  54592. }
  54593. this._basePoint.subtractToRef(p2, this._tempVector);
  54594. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54595. c = this._tempVector.lengthSquared() - 1.0;
  54596. lowestRoot = getLowestRoot(a, b, c, t);
  54597. if (lowestRoot.found) {
  54598. t = lowestRoot.root;
  54599. found = true;
  54600. this._collisionPoint.copyFrom(p2);
  54601. }
  54602. this._basePoint.subtractToRef(p3, this._tempVector);
  54603. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54604. c = this._tempVector.lengthSquared() - 1.0;
  54605. lowestRoot = getLowestRoot(a, b, c, t);
  54606. if (lowestRoot.found) {
  54607. t = lowestRoot.root;
  54608. found = true;
  54609. this._collisionPoint.copyFrom(p3);
  54610. }
  54611. p2.subtractToRef(p1, this._edge);
  54612. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54613. var edgeSquaredLength = this._edge.lengthSquared();
  54614. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54615. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54616. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54617. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54618. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54619. lowestRoot = getLowestRoot(a, b, c, t);
  54620. if (lowestRoot.found) {
  54621. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54622. if (f >= 0.0 && f <= 1.0) {
  54623. t = lowestRoot.root;
  54624. found = true;
  54625. this._edge.scaleInPlace(f);
  54626. p1.addToRef(this._edge, this._collisionPoint);
  54627. }
  54628. }
  54629. p3.subtractToRef(p2, this._edge);
  54630. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54631. edgeSquaredLength = this._edge.lengthSquared();
  54632. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54633. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54634. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54635. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54636. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54637. lowestRoot = getLowestRoot(a, b, c, t);
  54638. if (lowestRoot.found) {
  54639. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54640. if (f >= 0.0 && f <= 1.0) {
  54641. t = lowestRoot.root;
  54642. found = true;
  54643. this._edge.scaleInPlace(f);
  54644. p2.addToRef(this._edge, this._collisionPoint);
  54645. }
  54646. }
  54647. p1.subtractToRef(p3, this._edge);
  54648. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54649. edgeSquaredLength = this._edge.lengthSquared();
  54650. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54651. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54652. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54653. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54654. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54655. lowestRoot = getLowestRoot(a, b, c, t);
  54656. if (lowestRoot.found) {
  54657. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54658. if (f >= 0.0 && f <= 1.0) {
  54659. t = lowestRoot.root;
  54660. found = true;
  54661. this._edge.scaleInPlace(f);
  54662. p3.addToRef(this._edge, this._collisionPoint);
  54663. }
  54664. }
  54665. }
  54666. if (found) {
  54667. var distToCollision = t * this._velocity.length();
  54668. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54669. if (!this.intersectionPoint) {
  54670. this.intersectionPoint = this._collisionPoint.clone();
  54671. }
  54672. else {
  54673. this.intersectionPoint.copyFrom(this._collisionPoint);
  54674. }
  54675. this._nearestDistance = distToCollision;
  54676. this.collisionFound = true;
  54677. }
  54678. }
  54679. };
  54680. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54681. for (var i = indexStart; i < indexEnd; i += 3) {
  54682. var p1 = pts[indices[i] - decal];
  54683. var p2 = pts[indices[i + 1] - decal];
  54684. var p3 = pts[indices[i + 2] - decal];
  54685. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54686. }
  54687. };
  54688. Collider.prototype._getResponse = function (pos, vel) {
  54689. pos.addToRef(vel, this._destinationPoint);
  54690. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54691. this._basePoint.addToRef(vel, pos);
  54692. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54693. this._slidePlaneNormal.normalize();
  54694. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54695. pos.addInPlace(this._displacementVector);
  54696. this.intersectionPoint.addInPlace(this._displacementVector);
  54697. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54698. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54699. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54700. };
  54701. return Collider;
  54702. }());
  54703. BABYLON.Collider = Collider;
  54704. })(BABYLON || (BABYLON = {}));
  54705. //# sourceMappingURL=babylon.collider.js.map
  54706. var BABYLON;
  54707. (function (BABYLON) {
  54708. //WebWorker code will be inserted to this variable.
  54709. BABYLON.CollisionWorker = "";
  54710. /** Defines supported task for worker process */
  54711. var WorkerTaskType;
  54712. (function (WorkerTaskType) {
  54713. /** Initialization */
  54714. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54715. /** Update of geometry */
  54716. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54717. /** Evaluate collision */
  54718. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54719. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54720. /** Defines kind of replies returned by worker */
  54721. var WorkerReplyType;
  54722. (function (WorkerReplyType) {
  54723. /** Success */
  54724. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54725. /** Unkown error */
  54726. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54727. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54728. var CollisionCoordinatorWorker = /** @class */ (function () {
  54729. function CollisionCoordinatorWorker() {
  54730. var _this = this;
  54731. this._scaledPosition = BABYLON.Vector3.Zero();
  54732. this._scaledVelocity = BABYLON.Vector3.Zero();
  54733. this.onMeshUpdated = function (transformNode) {
  54734. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54735. };
  54736. this.onGeometryUpdated = function (geometry) {
  54737. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54738. };
  54739. this._afterRender = function () {
  54740. if (!_this._init)
  54741. return;
  54742. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54743. return;
  54744. }
  54745. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54746. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54747. if (_this._runningUpdated > 4) {
  54748. return;
  54749. }
  54750. ++_this._runningUpdated;
  54751. var payload = {
  54752. updatedMeshes: _this._addUpdateMeshesList,
  54753. updatedGeometries: _this._addUpdateGeometriesList,
  54754. removedGeometries: _this._toRemoveGeometryArray,
  54755. removedMeshes: _this._toRemoveMeshesArray
  54756. };
  54757. var message = {
  54758. payload: payload,
  54759. taskType: WorkerTaskType.UPDATE
  54760. };
  54761. var serializable = [];
  54762. for (var id in payload.updatedGeometries) {
  54763. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54764. //prepare transferables
  54765. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54766. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54767. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54768. }
  54769. }
  54770. _this._worker.postMessage(message, serializable);
  54771. _this._addUpdateMeshesList = {};
  54772. _this._addUpdateGeometriesList = {};
  54773. _this._toRemoveGeometryArray = [];
  54774. _this._toRemoveMeshesArray = [];
  54775. };
  54776. this._onMessageFromWorker = function (e) {
  54777. var returnData = e.data;
  54778. if (returnData.error != WorkerReplyType.SUCCESS) {
  54779. //TODO what errors can be returned from the worker?
  54780. BABYLON.Tools.Warn("error returned from worker!");
  54781. return;
  54782. }
  54783. switch (returnData.taskType) {
  54784. case WorkerTaskType.INIT:
  54785. _this._init = true;
  54786. //Update the worked with ALL of the scene's current state
  54787. _this._scene.meshes.forEach(function (mesh) {
  54788. _this.onMeshAdded(mesh);
  54789. });
  54790. _this._scene.getGeometries().forEach(function (geometry) {
  54791. _this.onGeometryAdded(geometry);
  54792. });
  54793. break;
  54794. case WorkerTaskType.UPDATE:
  54795. _this._runningUpdated--;
  54796. break;
  54797. case WorkerTaskType.COLLIDE:
  54798. var returnPayload = returnData.payload;
  54799. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54800. return;
  54801. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54802. if (callback) {
  54803. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54804. if (mesh) {
  54805. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54806. }
  54807. }
  54808. //cleanup
  54809. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54810. break;
  54811. }
  54812. };
  54813. this._collisionsCallbackArray = [];
  54814. this._init = false;
  54815. this._runningUpdated = 0;
  54816. this._addUpdateMeshesList = {};
  54817. this._addUpdateGeometriesList = {};
  54818. this._toRemoveGeometryArray = [];
  54819. this._toRemoveMeshesArray = [];
  54820. }
  54821. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54822. if (!this._init)
  54823. return;
  54824. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54825. return;
  54826. position.divideToRef(collider._radius, this._scaledPosition);
  54827. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54828. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54829. var payload = {
  54830. collider: {
  54831. position: this._scaledPosition.asArray(),
  54832. velocity: this._scaledVelocity.asArray(),
  54833. radius: collider._radius.asArray()
  54834. },
  54835. collisionId: collisionIndex,
  54836. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54837. maximumRetry: maximumRetry
  54838. };
  54839. var message = {
  54840. payload: payload,
  54841. taskType: WorkerTaskType.COLLIDE
  54842. };
  54843. this._worker.postMessage(message);
  54844. };
  54845. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54846. this._scene = scene;
  54847. this._scene.registerAfterRender(this._afterRender);
  54848. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54849. this._worker = new Worker(workerUrl);
  54850. this._worker.onmessage = this._onMessageFromWorker;
  54851. var message = {
  54852. payload: {},
  54853. taskType: WorkerTaskType.INIT
  54854. };
  54855. this._worker.postMessage(message);
  54856. };
  54857. CollisionCoordinatorWorker.prototype.destroy = function () {
  54858. this._scene.unregisterAfterRender(this._afterRender);
  54859. this._worker.terminate();
  54860. };
  54861. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54862. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54863. this.onMeshUpdated(mesh);
  54864. };
  54865. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54866. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54867. };
  54868. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54869. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54870. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54871. this.onGeometryUpdated(geometry);
  54872. };
  54873. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54874. this._toRemoveGeometryArray.push(geometry.id);
  54875. };
  54876. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54877. var submeshes = [];
  54878. if (mesh.subMeshes) {
  54879. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54880. var boundingInfo = sm.getBoundingInfo();
  54881. return {
  54882. position: idx,
  54883. verticesStart: sm.verticesStart,
  54884. verticesCount: sm.verticesCount,
  54885. indexStart: sm.indexStart,
  54886. indexCount: sm.indexCount,
  54887. hasMaterial: !!sm.getMaterial(),
  54888. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54889. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54890. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54891. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54892. };
  54893. });
  54894. }
  54895. var geometryId = null;
  54896. if (mesh instanceof BABYLON.Mesh) {
  54897. var geometry = mesh.geometry;
  54898. geometryId = geometry ? geometry.id : null;
  54899. }
  54900. else if (mesh instanceof BABYLON.InstancedMesh) {
  54901. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54902. geometryId = geometry ? geometry.id : null;
  54903. }
  54904. var boundingInfo = mesh.getBoundingInfo();
  54905. return {
  54906. uniqueId: mesh.uniqueId,
  54907. id: mesh.id,
  54908. name: mesh.name,
  54909. geometryId: geometryId,
  54910. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54911. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54912. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54913. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54914. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54915. subMeshes: submeshes,
  54916. checkCollisions: mesh.checkCollisions
  54917. };
  54918. };
  54919. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54920. return {
  54921. id: geometry.id,
  54922. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54923. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54924. indices: new Uint32Array(geometry.getIndices() || []),
  54925. };
  54926. };
  54927. return CollisionCoordinatorWorker;
  54928. }());
  54929. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54930. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54931. function CollisionCoordinatorLegacy() {
  54932. this._scaledPosition = BABYLON.Vector3.Zero();
  54933. this._scaledVelocity = BABYLON.Vector3.Zero();
  54934. this._finalPosition = BABYLON.Vector3.Zero();
  54935. }
  54936. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54937. position.divideToRef(collider._radius, this._scaledPosition);
  54938. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54939. collider.collidedMesh = null;
  54940. collider._retry = 0;
  54941. collider._initialVelocity = this._scaledVelocity;
  54942. collider._initialPosition = this._scaledPosition;
  54943. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54944. this._finalPosition.multiplyInPlace(collider._radius);
  54945. //run the callback
  54946. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54947. };
  54948. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54949. this._scene = scene;
  54950. };
  54951. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54952. //Legacy need no destruction method.
  54953. };
  54954. //No update in legacy mode
  54955. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54956. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54957. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54958. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54959. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54960. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54961. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54962. if (excludedMesh === void 0) { excludedMesh = null; }
  54963. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54964. if (collider._retry >= maximumRetry) {
  54965. finalPosition.copyFrom(position);
  54966. return;
  54967. }
  54968. // Check if this is a mesh else camera or -1
  54969. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54970. collider._initialize(position, velocity, closeDistance);
  54971. // Check all meshes
  54972. for (var index = 0; index < this._scene.meshes.length; index++) {
  54973. var mesh = this._scene.meshes[index];
  54974. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54975. mesh._checkCollision(collider);
  54976. }
  54977. }
  54978. if (!collider.collisionFound) {
  54979. position.addToRef(velocity, finalPosition);
  54980. return;
  54981. }
  54982. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54983. collider._getResponse(position, velocity);
  54984. }
  54985. if (velocity.length() <= closeDistance) {
  54986. finalPosition.copyFrom(position);
  54987. return;
  54988. }
  54989. collider._retry++;
  54990. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54991. };
  54992. return CollisionCoordinatorLegacy;
  54993. }());
  54994. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54995. })(BABYLON || (BABYLON = {}));
  54996. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54997. var BABYLON;
  54998. (function (BABYLON) {
  54999. /**
  55000. * A particle represents one of the element emitted by a particle system.
  55001. * This is mainly define by its coordinates, direction, velocity and age.
  55002. */
  55003. var Particle = /** @class */ (function () {
  55004. /**
  55005. * Creates a new instance Particle
  55006. * @param particleSystem the particle system the particle belongs to
  55007. */
  55008. function Particle(
  55009. /**
  55010. * particleSystem the particle system the particle belongs to.
  55011. */
  55012. particleSystem) {
  55013. this.particleSystem = particleSystem;
  55014. /**
  55015. * The world position of the particle in the scene.
  55016. */
  55017. this.position = BABYLON.Vector3.Zero();
  55018. /**
  55019. * The world direction of the particle in the scene.
  55020. */
  55021. this.direction = BABYLON.Vector3.Zero();
  55022. /**
  55023. * The color of the particle.
  55024. */
  55025. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55026. /**
  55027. * The color change of the particle per step.
  55028. */
  55029. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55030. /**
  55031. * Defines how long will the life of the particle be.
  55032. */
  55033. this.lifeTime = 1.0;
  55034. /**
  55035. * The current age of the particle.
  55036. */
  55037. this.age = 0;
  55038. /**
  55039. * The current size of the particle.
  55040. */
  55041. this.size = 0;
  55042. /**
  55043. * The current scale of the particle.
  55044. */
  55045. this.scale = new BABYLON.Vector2(1, 1);
  55046. /**
  55047. * The current angle of the particle.
  55048. */
  55049. this.angle = 0;
  55050. /**
  55051. * Defines how fast is the angle changing.
  55052. */
  55053. this.angularSpeed = 0;
  55054. /**
  55055. * Defines the cell index used by the particle to be rendered from a sprite.
  55056. */
  55057. this.cellIndex = 0;
  55058. /** @hidden */
  55059. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55060. /** @hidden */
  55061. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55062. /** @hidden */
  55063. this._currentSize1 = 0;
  55064. /** @hidden */
  55065. this._currentSize2 = 0;
  55066. /** @hidden */
  55067. this._currentAngularSpeed1 = 0;
  55068. /** @hidden */
  55069. this._currentAngularSpeed2 = 0;
  55070. /** @hidden */
  55071. this._currentVelocity1 = 0;
  55072. /** @hidden */
  55073. this._currentVelocity2 = 0;
  55074. /** @hidden */
  55075. this._currentLimitVelocity1 = 0;
  55076. /** @hidden */
  55077. this._currentLimitVelocity2 = 0;
  55078. if (!this.particleSystem.isAnimationSheetEnabled) {
  55079. return;
  55080. }
  55081. this.updateCellInfoFromSystem();
  55082. }
  55083. Particle.prototype.updateCellInfoFromSystem = function () {
  55084. this.cellIndex = this.particleSystem.startSpriteCellID;
  55085. };
  55086. /**
  55087. * Defines how the sprite cell index is updated for the particle
  55088. */
  55089. Particle.prototype.updateCellIndex = function () {
  55090. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55091. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55092. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55093. };
  55094. /**
  55095. * Copy the properties of particle to another one.
  55096. * @param other the particle to copy the information to.
  55097. */
  55098. Particle.prototype.copyTo = function (other) {
  55099. other.position.copyFrom(this.position);
  55100. if (this._initialDirection) {
  55101. if (other._initialDirection) {
  55102. other._initialDirection.copyFrom(this._initialDirection);
  55103. }
  55104. else {
  55105. other._initialDirection = this._initialDirection.clone();
  55106. }
  55107. }
  55108. else {
  55109. other._initialDirection = null;
  55110. }
  55111. other.direction.copyFrom(this.direction);
  55112. other.color.copyFrom(this.color);
  55113. other.colorStep.copyFrom(this.colorStep);
  55114. other.lifeTime = this.lifeTime;
  55115. other.age = this.age;
  55116. other.size = this.size;
  55117. other.scale.copyFrom(this.scale);
  55118. other.angle = this.angle;
  55119. other.angularSpeed = this.angularSpeed;
  55120. other.particleSystem = this.particleSystem;
  55121. other.cellIndex = this.cellIndex;
  55122. if (this._currentColorGradient) {
  55123. other._currentColorGradient = this._currentColorGradient;
  55124. other._currentColor1.copyFrom(this._currentColor1);
  55125. other._currentColor2.copyFrom(this._currentColor2);
  55126. }
  55127. if (this._currentSizeGradient) {
  55128. other._currentSizeGradient = this._currentSizeGradient;
  55129. other._currentSize1 = this._currentSize1;
  55130. other._currentSize2 = this._currentSize2;
  55131. }
  55132. if (this._currentAngularSpeedGradient) {
  55133. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55134. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55135. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55136. }
  55137. if (this._currentVelocityGradient) {
  55138. other._currentVelocityGradient = this._currentVelocityGradient;
  55139. other._currentVelocity1 = this._currentVelocity1;
  55140. other._currentVelocity2 = this._currentVelocity2;
  55141. }
  55142. if (this._currentLimitVelocityGradient) {
  55143. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55144. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55145. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55146. }
  55147. if (this.particleSystem.isAnimationSheetEnabled) {
  55148. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55149. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55150. }
  55151. };
  55152. return Particle;
  55153. }());
  55154. BABYLON.Particle = Particle;
  55155. })(BABYLON || (BABYLON = {}));
  55156. //# sourceMappingURL=babylon.particle.js.map
  55157. var BABYLON;
  55158. (function (BABYLON) {
  55159. /**
  55160. * This represents the base class for particle system in Babylon.
  55161. * 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.
  55162. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55163. * @example https://doc.babylonjs.com/babylon101/particles
  55164. */
  55165. var BaseParticleSystem = /** @class */ (function () {
  55166. /**
  55167. * Instantiates a particle system.
  55168. * 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.
  55169. * @param name The name of the particle system
  55170. */
  55171. function BaseParticleSystem(name) {
  55172. /**
  55173. * List of animations used by the particle system.
  55174. */
  55175. this.animations = [];
  55176. /**
  55177. * The rendering group used by the Particle system to chose when to render.
  55178. */
  55179. this.renderingGroupId = 0;
  55180. /**
  55181. * The emitter represents the Mesh or position we are attaching the particle system to.
  55182. */
  55183. this.emitter = null;
  55184. /**
  55185. * The maximum number of particles to emit per frame
  55186. */
  55187. this.emitRate = 10;
  55188. /**
  55189. * If you want to launch only a few particles at once, that can be done, as well.
  55190. */
  55191. this.manualEmitCount = -1;
  55192. /**
  55193. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55194. */
  55195. this.updateSpeed = 0.01;
  55196. /**
  55197. * The amount of time the particle system is running (depends of the overall update speed).
  55198. */
  55199. this.targetStopDuration = 0;
  55200. /**
  55201. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55202. */
  55203. this.disposeOnStop = false;
  55204. /**
  55205. * Minimum power of emitting particles.
  55206. */
  55207. this.minEmitPower = 1;
  55208. /**
  55209. * Maximum power of emitting particles.
  55210. */
  55211. this.maxEmitPower = 1;
  55212. /**
  55213. * Minimum life time of emitting particles.
  55214. */
  55215. this.minLifeTime = 1;
  55216. /**
  55217. * Maximum life time of emitting particles.
  55218. */
  55219. this.maxLifeTime = 1;
  55220. /**
  55221. * Minimum Size of emitting particles.
  55222. */
  55223. this.minSize = 1;
  55224. /**
  55225. * Maximum Size of emitting particles.
  55226. */
  55227. this.maxSize = 1;
  55228. /**
  55229. * Minimum scale of emitting particles on X axis.
  55230. */
  55231. this.minScaleX = 1;
  55232. /**
  55233. * Maximum scale of emitting particles on X axis.
  55234. */
  55235. this.maxScaleX = 1;
  55236. /**
  55237. * Minimum scale of emitting particles on Y axis.
  55238. */
  55239. this.minScaleY = 1;
  55240. /**
  55241. * Maximum scale of emitting particles on Y axis.
  55242. */
  55243. this.maxScaleY = 1;
  55244. /**
  55245. * Gets or sets the minimal initial rotation in radians.
  55246. */
  55247. this.minInitialRotation = 0;
  55248. /**
  55249. * Gets or sets the maximal initial rotation in radians.
  55250. */
  55251. this.maxInitialRotation = 0;
  55252. /**
  55253. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55254. */
  55255. this.minAngularSpeed = 0;
  55256. /**
  55257. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55258. */
  55259. this.maxAngularSpeed = 0;
  55260. /**
  55261. * The layer mask we are rendering the particles through.
  55262. */
  55263. this.layerMask = 0x0FFFFFFF;
  55264. /**
  55265. * This can help using your own shader to render the particle system.
  55266. * The according effect will be created
  55267. */
  55268. this.customShader = null;
  55269. /**
  55270. * By default particle system starts as soon as they are created. This prevents the
  55271. * automatic start to happen and let you decide when to start emitting particles.
  55272. */
  55273. this.preventAutoStart = false;
  55274. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55275. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55276. /**
  55277. * Callback triggered when the particle animation is ending.
  55278. */
  55279. this.onAnimationEnd = null;
  55280. /**
  55281. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55282. */
  55283. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55284. /**
  55285. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55286. * to override the particles.
  55287. */
  55288. this.forceDepthWrite = false;
  55289. /** 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 */
  55290. this.preWarmCycles = 0;
  55291. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55292. this.preWarmStepOffset = 1;
  55293. /**
  55294. * 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)
  55295. */
  55296. this.spriteCellChangeSpeed = 1;
  55297. /**
  55298. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55299. */
  55300. this.startSpriteCellID = 0;
  55301. /**
  55302. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55303. */
  55304. this.endSpriteCellID = 0;
  55305. /**
  55306. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55307. */
  55308. this.spriteCellWidth = 0;
  55309. /**
  55310. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55311. */
  55312. this.spriteCellHeight = 0;
  55313. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55314. this.translationPivot = new BABYLON.Vector2(0, 0);
  55315. /**
  55316. * You can use gravity if you want to give an orientation to your particles.
  55317. */
  55318. this.gravity = BABYLON.Vector3.Zero();
  55319. this._colorGradients = null;
  55320. this._sizeGradients = null;
  55321. this._lifeTimeGradients = null;
  55322. this._angularSpeedGradients = null;
  55323. this._velocityGradients = null;
  55324. this._limitVelocityGradients = null;
  55325. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55326. this.limitVelocityDamping = 0.4;
  55327. /**
  55328. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55329. */
  55330. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55331. /**
  55332. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55333. */
  55334. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55335. /**
  55336. * Color the particle will have at the end of its lifetime
  55337. */
  55338. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55339. /**
  55340. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55341. */
  55342. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55343. /**
  55344. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55345. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55346. */
  55347. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55348. this._isBillboardBased = true;
  55349. this.id = name;
  55350. this.name = name;
  55351. }
  55352. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55353. /**
  55354. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55355. */
  55356. get: function () {
  55357. return this._isAnimationSheetEnabled;
  55358. },
  55359. set: function (value) {
  55360. if (this._isAnimationSheetEnabled == value) {
  55361. return;
  55362. }
  55363. this._isAnimationSheetEnabled = value;
  55364. this._reset();
  55365. },
  55366. enumerable: true,
  55367. configurable: true
  55368. });
  55369. /**
  55370. * Gets the current list of limit velocity gradients.
  55371. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55372. * @returns the list of limit velocity gradients
  55373. */
  55374. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55375. return this._limitVelocityGradients;
  55376. };
  55377. /**
  55378. * Gets the current list of color gradients.
  55379. * You must use addColorGradient and removeColorGradient to udpate this list
  55380. * @returns the list of color gradients
  55381. */
  55382. BaseParticleSystem.prototype.getColorGradients = function () {
  55383. return this._colorGradients;
  55384. };
  55385. /**
  55386. * Gets the current list of size gradients.
  55387. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55388. * @returns the list of size gradients
  55389. */
  55390. BaseParticleSystem.prototype.getSizeGradients = function () {
  55391. return this._sizeGradients;
  55392. };
  55393. /**
  55394. * Gets the current list of life time gradients.
  55395. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55396. * @returns the list of life time gradients
  55397. */
  55398. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55399. return this._lifeTimeGradients;
  55400. };
  55401. /**
  55402. * Gets the current list of angular speed gradients.
  55403. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55404. * @returns the list of angular speed gradients
  55405. */
  55406. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55407. return this._angularSpeedGradients;
  55408. };
  55409. /**
  55410. * Gets the current list of velocity gradients.
  55411. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55412. * @returns the list of velocity gradients
  55413. */
  55414. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55415. return this._velocityGradients;
  55416. };
  55417. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55418. /**
  55419. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55420. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55421. */
  55422. get: function () {
  55423. if (this.particleEmitterType.direction1) {
  55424. return this.particleEmitterType.direction1;
  55425. }
  55426. return BABYLON.Vector3.Zero();
  55427. },
  55428. set: function (value) {
  55429. if (this.particleEmitterType.direction1) {
  55430. this.particleEmitterType.direction1 = value;
  55431. }
  55432. },
  55433. enumerable: true,
  55434. configurable: true
  55435. });
  55436. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55437. /**
  55438. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55439. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55440. */
  55441. get: function () {
  55442. if (this.particleEmitterType.direction2) {
  55443. return this.particleEmitterType.direction2;
  55444. }
  55445. return BABYLON.Vector3.Zero();
  55446. },
  55447. set: function (value) {
  55448. if (this.particleEmitterType.direction2) {
  55449. this.particleEmitterType.direction2 = value;
  55450. }
  55451. },
  55452. enumerable: true,
  55453. configurable: true
  55454. });
  55455. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55456. /**
  55457. * 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.
  55458. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55459. */
  55460. get: function () {
  55461. if (this.particleEmitterType.minEmitBox) {
  55462. return this.particleEmitterType.minEmitBox;
  55463. }
  55464. return BABYLON.Vector3.Zero();
  55465. },
  55466. set: function (value) {
  55467. if (this.particleEmitterType.minEmitBox) {
  55468. this.particleEmitterType.minEmitBox = value;
  55469. }
  55470. },
  55471. enumerable: true,
  55472. configurable: true
  55473. });
  55474. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55475. /**
  55476. * 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.
  55477. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55478. */
  55479. get: function () {
  55480. if (this.particleEmitterType.maxEmitBox) {
  55481. return this.particleEmitterType.maxEmitBox;
  55482. }
  55483. return BABYLON.Vector3.Zero();
  55484. },
  55485. set: function (value) {
  55486. if (this.particleEmitterType.maxEmitBox) {
  55487. this.particleEmitterType.maxEmitBox = value;
  55488. }
  55489. },
  55490. enumerable: true,
  55491. configurable: true
  55492. });
  55493. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55494. /**
  55495. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55496. */
  55497. get: function () {
  55498. return this._isBillboardBased;
  55499. },
  55500. set: function (value) {
  55501. if (this._isBillboardBased === value) {
  55502. return;
  55503. }
  55504. this._isBillboardBased = value;
  55505. this._reset();
  55506. },
  55507. enumerable: true,
  55508. configurable: true
  55509. });
  55510. /** @hidden */
  55511. BaseParticleSystem.prototype._reset = function () {
  55512. };
  55513. /**
  55514. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  55515. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55516. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55517. * @returns the emitter
  55518. */
  55519. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  55520. var particleEmitter = new BABYLON.PointParticleEmitter();
  55521. particleEmitter.direction1 = direction1;
  55522. particleEmitter.direction2 = direction2;
  55523. this.particleEmitterType = particleEmitter;
  55524. return particleEmitter;
  55525. };
  55526. /**
  55527. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  55528. * @param radius The radius of the hemisphere to emit from
  55529. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55530. * @returns the emitter
  55531. */
  55532. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  55533. if (radius === void 0) { radius = 1; }
  55534. if (radiusRange === void 0) { radiusRange = 1; }
  55535. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  55536. this.particleEmitterType = particleEmitter;
  55537. return particleEmitter;
  55538. };
  55539. /**
  55540. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  55541. * @param radius The radius of the sphere to emit from
  55542. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55543. * @returns the emitter
  55544. */
  55545. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  55546. if (radius === void 0) { radius = 1; }
  55547. if (radiusRange === void 0) { radiusRange = 1; }
  55548. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  55549. this.particleEmitterType = particleEmitter;
  55550. return particleEmitter;
  55551. };
  55552. /**
  55553. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  55554. * @param radius The radius of the sphere to emit from
  55555. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55556. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55557. * @returns the emitter
  55558. */
  55559. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55560. if (radius === void 0) { radius = 1; }
  55561. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55562. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55563. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55564. this.particleEmitterType = particleEmitter;
  55565. return particleEmitter;
  55566. };
  55567. /**
  55568. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  55569. * @param radius The radius of the cone to emit from
  55570. * @param angle The base angle of the cone
  55571. * @returns the emitter
  55572. */
  55573. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55574. if (radius === void 0) { radius = 1; }
  55575. if (angle === void 0) { angle = Math.PI / 4; }
  55576. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55577. this.particleEmitterType = particleEmitter;
  55578. return particleEmitter;
  55579. };
  55580. /**
  55581. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55582. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55583. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55584. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55585. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55586. * @returns the emitter
  55587. */
  55588. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55589. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55590. this.particleEmitterType = particleEmitter;
  55591. this.direction1 = direction1;
  55592. this.direction2 = direction2;
  55593. this.minEmitBox = minEmitBox;
  55594. this.maxEmitBox = maxEmitBox;
  55595. return particleEmitter;
  55596. };
  55597. /**
  55598. * Source color is added to the destination color without alpha affecting the result.
  55599. */
  55600. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  55601. /**
  55602. * Blend current color and particle color using particle’s alpha.
  55603. */
  55604. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  55605. /**
  55606. * Add current color and particle color multiplied by particle’s alpha.
  55607. */
  55608. BaseParticleSystem.BLENDMODE_ADD = 2;
  55609. return BaseParticleSystem;
  55610. }());
  55611. BABYLON.BaseParticleSystem = BaseParticleSystem;
  55612. })(BABYLON || (BABYLON = {}));
  55613. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  55614. var BABYLON;
  55615. (function (BABYLON) {
  55616. /**
  55617. * This represents a particle system in Babylon.
  55618. * 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.
  55619. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55620. * @example https://doc.babylonjs.com/babylon101/particles
  55621. */
  55622. var ParticleSystem = /** @class */ (function (_super) {
  55623. __extends(ParticleSystem, _super);
  55624. /**
  55625. * Instantiates a particle system.
  55626. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  55627. * @param name The name of the particle system
  55628. * @param capacity The max number of particles alive at the same time
  55629. * @param scene The scene the particle system belongs to
  55630. * @param customEffect a custom effect used to change the way particles are rendered by default
  55631. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55632. * @param epsilon Offset used to render the particles
  55633. */
  55634. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55635. if (customEffect === void 0) { customEffect = null; }
  55636. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55637. if (epsilon === void 0) { epsilon = 0.01; }
  55638. var _this = _super.call(this, name) || this;
  55639. /**
  55640. * An event triggered when the system is disposed
  55641. */
  55642. _this.onDisposeObservable = new BABYLON.Observable();
  55643. _this._particles = new Array();
  55644. _this._stockParticles = new Array();
  55645. _this._newPartsExcess = 0;
  55646. _this._vertexBuffers = {};
  55647. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55648. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55649. _this._scaledDirection = BABYLON.Vector3.Zero();
  55650. _this._scaledGravity = BABYLON.Vector3.Zero();
  55651. _this._currentRenderId = -1;
  55652. _this._useInstancing = false;
  55653. _this._started = false;
  55654. _this._stopped = false;
  55655. _this._actualFrame = 0;
  55656. // start of sub system methods
  55657. /**
  55658. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55659. * Its lifetime will start back at 0.
  55660. */
  55661. _this.recycleParticle = function (particle) {
  55662. var lastParticle = _this._particles.pop();
  55663. if (lastParticle !== particle) {
  55664. lastParticle.copyTo(particle);
  55665. }
  55666. _this._stockParticles.push(lastParticle);
  55667. };
  55668. _this._createParticle = function () {
  55669. var particle;
  55670. if (_this._stockParticles.length !== 0) {
  55671. particle = _this._stockParticles.pop();
  55672. particle.age = 0;
  55673. particle._currentColorGradient = null;
  55674. particle.cellIndex = _this.startSpriteCellID;
  55675. }
  55676. else {
  55677. particle = new BABYLON.Particle(_this);
  55678. }
  55679. return particle;
  55680. };
  55681. _this._emitFromParticle = function (particle) {
  55682. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55683. return;
  55684. }
  55685. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55686. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55687. subSystem._rootParticleSystem = _this;
  55688. _this.activeSubSystems.push(subSystem);
  55689. subSystem.start();
  55690. };
  55691. _this._capacity = capacity;
  55692. _this._epsilon = epsilon;
  55693. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55694. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55695. _this._customEffect = customEffect;
  55696. _this._scene.particleSystems.push(_this);
  55697. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  55698. _this._createIndexBuffer();
  55699. _this._createVertexBuffers();
  55700. // Default emitter type
  55701. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55702. _this.updateFunction = function (particles) {
  55703. var noiseTextureData = null;
  55704. var noiseTextureSize = null;
  55705. if (_this.noiseTexture) { // We need to get texture data back to CPU
  55706. noiseTextureData = (_this.noiseTexture.readPixels());
  55707. noiseTextureSize = _this.noiseTexture.getSize();
  55708. }
  55709. var _loop_1 = function () {
  55710. particle = particles[index];
  55711. particle.age += _this._scaledUpdateSpeed;
  55712. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55713. _this._emitFromParticle(particle);
  55714. _this.recycleParticle(particle);
  55715. index--;
  55716. return "continue";
  55717. }
  55718. else {
  55719. var ratio = particle.age / particle.lifeTime;
  55720. // Color
  55721. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55722. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55723. if (currentGradient !== particle._currentColorGradient) {
  55724. particle._currentColor1.copyFrom(particle._currentColor2);
  55725. nextGradient.getColorToRef(particle._currentColor2);
  55726. particle._currentColorGradient = currentGradient;
  55727. }
  55728. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55729. });
  55730. }
  55731. else {
  55732. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55733. particle.color.addInPlace(_this._scaledColorStep);
  55734. if (particle.color.a < 0) {
  55735. particle.color.a = 0;
  55736. }
  55737. }
  55738. // Angular speed
  55739. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55740. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55741. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55742. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55743. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55744. particle._currentAngularSpeedGradient = currentGradient;
  55745. }
  55746. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55747. });
  55748. }
  55749. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55750. // Direction
  55751. var directionScale_1 = _this._scaledUpdateSpeed;
  55752. /// Velocity
  55753. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55754. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55755. if (currentGradient !== particle._currentVelocityGradient) {
  55756. particle._currentVelocity1 = particle._currentVelocity2;
  55757. particle._currentVelocity2 = nextGradient.getFactor();
  55758. particle._currentVelocityGradient = currentGradient;
  55759. }
  55760. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55761. });
  55762. }
  55763. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55764. /// Limit velocity
  55765. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  55766. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  55767. if (currentGradient !== particle._currentLimitVelocityGradient) {
  55768. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  55769. particle._currentLimitVelocity2 = nextGradient.getFactor();
  55770. particle._currentLimitVelocityGradient = currentGradient;
  55771. }
  55772. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  55773. var currentVelocity = particle.direction.length();
  55774. if (currentVelocity > limitVelocity) {
  55775. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  55776. }
  55777. });
  55778. }
  55779. particle.position.addInPlace(_this._scaledDirection);
  55780. // Noise
  55781. if (noiseTextureData && noiseTextureSize) {
  55782. var localPosition = BABYLON.Tmp.Vector3[0];
  55783. var emitterPosition = BABYLON.Tmp.Vector3[1];
  55784. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  55785. particle.position.subtractToRef(emitterPosition, localPosition);
  55786. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55787. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55788. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55789. var force = BABYLON.Tmp.Vector3[0];
  55790. var scaledForce = BABYLON.Tmp.Vector3[1];
  55791. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  55792. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  55793. particle.direction.addInPlace(scaledForce);
  55794. }
  55795. // Gravity
  55796. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55797. particle.direction.addInPlace(_this._scaledGravity);
  55798. // Size
  55799. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55800. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55801. if (currentGradient !== particle._currentSizeGradient) {
  55802. particle._currentSize1 = particle._currentSize2;
  55803. particle._currentSize2 = nextGradient.getFactor();
  55804. particle._currentSizeGradient = currentGradient;
  55805. }
  55806. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55807. });
  55808. }
  55809. if (_this._isAnimationSheetEnabled) {
  55810. particle.updateCellIndex();
  55811. }
  55812. }
  55813. };
  55814. var particle;
  55815. for (var index = 0; index < particles.length; index++) {
  55816. _loop_1();
  55817. }
  55818. };
  55819. return _this;
  55820. }
  55821. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55822. /**
  55823. * Sets a callback that will be triggered when the system is disposed
  55824. */
  55825. set: function (callback) {
  55826. if (this._onDisposeObserver) {
  55827. this.onDisposeObservable.remove(this._onDisposeObserver);
  55828. }
  55829. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55830. },
  55831. enumerable: true,
  55832. configurable: true
  55833. });
  55834. /**
  55835. * Get hosting scene
  55836. * @returns the scene
  55837. */
  55838. ParticleSystem.prototype.getScene = function () {
  55839. return this._scene;
  55840. };
  55841. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55842. //end of Sub-emitter
  55843. /**
  55844. * Gets the current list of active particles
  55845. */
  55846. get: function () {
  55847. return this._particles;
  55848. },
  55849. enumerable: true,
  55850. configurable: true
  55851. });
  55852. /**
  55853. * Returns the string "ParticleSystem"
  55854. * @returns a string containing the class name
  55855. */
  55856. ParticleSystem.prototype.getClassName = function () {
  55857. return "ParticleSystem";
  55858. };
  55859. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55860. var newGradient = new BABYLON.FactorGradient();
  55861. newGradient.gradient = gradient;
  55862. newGradient.factor1 = factor;
  55863. newGradient.factor2 = factor2;
  55864. factorGradients.push(newGradient);
  55865. factorGradients.sort(function (a, b) {
  55866. if (a.gradient < b.gradient) {
  55867. return -1;
  55868. }
  55869. else if (a.gradient > b.gradient) {
  55870. return 1;
  55871. }
  55872. return 0;
  55873. });
  55874. };
  55875. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55876. if (!factorGradients) {
  55877. return;
  55878. }
  55879. var index = 0;
  55880. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55881. var factorGradient = factorGradients_1[_i];
  55882. if (factorGradient.gradient === gradient) {
  55883. factorGradients.splice(index, 1);
  55884. break;
  55885. }
  55886. index++;
  55887. }
  55888. };
  55889. /**
  55890. * Adds a new life time gradient
  55891. * @param gradient defines the gradient to use (between 0 and 1)
  55892. * @param factor defines the life time factor to affect to the specified gradient
  55893. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55894. * @returns the current particle system
  55895. */
  55896. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55897. if (!this._lifeTimeGradients) {
  55898. this._lifeTimeGradients = [];
  55899. }
  55900. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55901. return this;
  55902. };
  55903. /**
  55904. * Remove a specific life time gradient
  55905. * @param gradient defines the gradient to remove
  55906. * @returns the current particle system
  55907. */
  55908. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55909. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55910. return this;
  55911. };
  55912. /**
  55913. * Adds a new size gradient
  55914. * @param gradient defines the gradient to use (between 0 and 1)
  55915. * @param factor defines the size factor to affect to the specified gradient
  55916. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55917. * @returns the current particle system
  55918. */
  55919. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55920. if (!this._sizeGradients) {
  55921. this._sizeGradients = [];
  55922. }
  55923. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55924. return this;
  55925. };
  55926. /**
  55927. * Remove a specific size gradient
  55928. * @param gradient defines the gradient to remove
  55929. * @returns the current particle system
  55930. */
  55931. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55932. this._removeFactorGradient(this._sizeGradients, gradient);
  55933. return this;
  55934. };
  55935. /**
  55936. * Adds a new angular speed gradient
  55937. * @param gradient defines the gradient to use (between 0 and 1)
  55938. * @param factor defines the angular speed to affect to the specified gradient
  55939. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55940. * @returns the current particle system
  55941. */
  55942. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55943. if (!this._angularSpeedGradients) {
  55944. this._angularSpeedGradients = [];
  55945. }
  55946. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55947. return this;
  55948. };
  55949. /**
  55950. * Remove a specific angular speed gradient
  55951. * @param gradient defines the gradient to remove
  55952. * @returns the current particle system
  55953. */
  55954. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55955. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55956. return this;
  55957. };
  55958. /**
  55959. * Adds a new velocity gradient
  55960. * @param gradient defines the gradient to use (between 0 and 1)
  55961. * @param factor defines the velocity to affect to the specified gradient
  55962. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55963. * @returns the current particle system
  55964. */
  55965. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55966. if (!this._velocityGradients) {
  55967. this._velocityGradients = [];
  55968. }
  55969. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55970. return this;
  55971. };
  55972. /**
  55973. * Remove a specific velocity gradient
  55974. * @param gradient defines the gradient to remove
  55975. * @returns the current particle system
  55976. */
  55977. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55978. this._removeFactorGradient(this._velocityGradients, gradient);
  55979. return this;
  55980. };
  55981. /**
  55982. * Adds a new limit velocity gradient
  55983. * @param gradient defines the gradient to use (between 0 and 1)
  55984. * @param factor defines the limit velocity value to affect to the specified gradient
  55985. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55986. * @returns the current particle system
  55987. */
  55988. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  55989. if (!this._limitVelocityGradients) {
  55990. this._limitVelocityGradients = [];
  55991. }
  55992. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  55993. return this;
  55994. };
  55995. /**
  55996. * Remove a specific limit velocity gradient
  55997. * @param gradient defines the gradient to remove
  55998. * @returns the current particle system
  55999. */
  56000. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56001. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56002. return this;
  56003. };
  56004. /**
  56005. * Adds a new color gradient
  56006. * @param gradient defines the gradient to use (between 0 and 1)
  56007. * @param color defines the color to affect to the specified gradient
  56008. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56009. */
  56010. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56011. if (!this._colorGradients) {
  56012. this._colorGradients = [];
  56013. }
  56014. var colorGradient = new BABYLON.ColorGradient();
  56015. colorGradient.gradient = gradient;
  56016. colorGradient.color1 = color;
  56017. colorGradient.color2 = color2;
  56018. this._colorGradients.push(colorGradient);
  56019. this._colorGradients.sort(function (a, b) {
  56020. if (a.gradient < b.gradient) {
  56021. return -1;
  56022. }
  56023. else if (a.gradient > b.gradient) {
  56024. return 1;
  56025. }
  56026. return 0;
  56027. });
  56028. return this;
  56029. };
  56030. /**
  56031. * Remove a specific color gradient
  56032. * @param gradient defines the gradient to remove
  56033. */
  56034. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56035. if (!this._colorGradients) {
  56036. return this;
  56037. }
  56038. var index = 0;
  56039. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56040. var colorGradient = _a[_i];
  56041. if (colorGradient.gradient === gradient) {
  56042. this._colorGradients.splice(index, 1);
  56043. break;
  56044. }
  56045. index++;
  56046. }
  56047. return this;
  56048. };
  56049. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56050. u = Math.abs(u) * 0.5 + 0.5;
  56051. v = Math.abs(v) * 0.5 + 0.5;
  56052. var wrappedU = ((u * width) % width) | 0;
  56053. var wrappedV = ((v * height) % height) | 0;
  56054. var position = (wrappedU + wrappedV * width) * 4;
  56055. return pixels[position] / 255;
  56056. };
  56057. ParticleSystem.prototype._reset = function () {
  56058. this._resetEffect();
  56059. };
  56060. ParticleSystem.prototype._resetEffect = function () {
  56061. if (this._vertexBuffer) {
  56062. this._vertexBuffer.dispose();
  56063. this._vertexBuffer = null;
  56064. }
  56065. if (this._spriteBuffer) {
  56066. this._spriteBuffer.dispose();
  56067. this._spriteBuffer = null;
  56068. }
  56069. this._createVertexBuffers();
  56070. };
  56071. ParticleSystem.prototype._createVertexBuffers = function () {
  56072. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56073. if (this._isAnimationSheetEnabled) {
  56074. this._vertexBufferSize += 1;
  56075. }
  56076. if (!this._isBillboardBased) {
  56077. this._vertexBufferSize += 3;
  56078. }
  56079. var engine = this._scene.getEngine();
  56080. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56081. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56082. var dataOffset = 0;
  56083. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56084. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56085. dataOffset += 3;
  56086. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56087. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56088. dataOffset += 4;
  56089. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56090. this._vertexBuffers["angle"] = options;
  56091. dataOffset += 1;
  56092. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56093. this._vertexBuffers["size"] = size;
  56094. dataOffset += 2;
  56095. if (this._isAnimationSheetEnabled) {
  56096. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56097. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56098. dataOffset += 1;
  56099. }
  56100. if (!this._isBillboardBased) {
  56101. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56102. this._vertexBuffers["direction"] = directionBuffer;
  56103. dataOffset += 3;
  56104. }
  56105. var offsets;
  56106. if (this._useInstancing) {
  56107. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56108. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56109. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56110. }
  56111. else {
  56112. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56113. dataOffset += 2;
  56114. }
  56115. this._vertexBuffers["offset"] = offsets;
  56116. };
  56117. ParticleSystem.prototype._createIndexBuffer = function () {
  56118. if (this._useInstancing) {
  56119. return;
  56120. }
  56121. var indices = [];
  56122. var index = 0;
  56123. for (var count = 0; count < this._capacity; count++) {
  56124. indices.push(index);
  56125. indices.push(index + 1);
  56126. indices.push(index + 2);
  56127. indices.push(index);
  56128. indices.push(index + 2);
  56129. indices.push(index + 3);
  56130. index += 4;
  56131. }
  56132. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56133. };
  56134. /**
  56135. * Gets the maximum number of particles active at the same time.
  56136. * @returns The max number of active particles.
  56137. */
  56138. ParticleSystem.prototype.getCapacity = function () {
  56139. return this._capacity;
  56140. };
  56141. /**
  56142. * Gets whether there are still active particles in the system.
  56143. * @returns True if it is alive, otherwise false.
  56144. */
  56145. ParticleSystem.prototype.isAlive = function () {
  56146. return this._alive;
  56147. };
  56148. /**
  56149. * Gets whether the system has been started.
  56150. * @returns True if it has been started, otherwise false.
  56151. */
  56152. ParticleSystem.prototype.isStarted = function () {
  56153. return this._started;
  56154. };
  56155. /**
  56156. * Starts the particle system and begins to emit
  56157. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56158. */
  56159. ParticleSystem.prototype.start = function (delay) {
  56160. var _this = this;
  56161. if (delay === void 0) { delay = 0; }
  56162. if (delay) {
  56163. setTimeout(function () {
  56164. _this.start(0);
  56165. }, delay);
  56166. return;
  56167. }
  56168. this._started = true;
  56169. this._stopped = false;
  56170. this._actualFrame = 0;
  56171. if (this.subEmitters && this.subEmitters.length != 0) {
  56172. this.activeSubSystems = new Array();
  56173. }
  56174. if (this.preWarmCycles) {
  56175. for (var index = 0; index < this.preWarmCycles; index++) {
  56176. this.animate(true);
  56177. }
  56178. }
  56179. };
  56180. /**
  56181. * Stops the particle system.
  56182. * @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.
  56183. */
  56184. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56185. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56186. this._stopped = true;
  56187. if (stopSubEmitters) {
  56188. this._stopSubEmitters();
  56189. }
  56190. };
  56191. // animation sheet
  56192. /**
  56193. * Remove all active particles
  56194. */
  56195. ParticleSystem.prototype.reset = function () {
  56196. this._stockParticles = [];
  56197. this._particles = [];
  56198. };
  56199. /**
  56200. * @hidden (for internal use only)
  56201. */
  56202. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56203. var offset = index * this._vertexBufferSize;
  56204. this._vertexData[offset++] = particle.position.x;
  56205. this._vertexData[offset++] = particle.position.y;
  56206. this._vertexData[offset++] = particle.position.z;
  56207. this._vertexData[offset++] = particle.color.r;
  56208. this._vertexData[offset++] = particle.color.g;
  56209. this._vertexData[offset++] = particle.color.b;
  56210. this._vertexData[offset++] = particle.color.a;
  56211. this._vertexData[offset++] = particle.angle;
  56212. this._vertexData[offset++] = particle.scale.x * particle.size;
  56213. this._vertexData[offset++] = particle.scale.y * particle.size;
  56214. if (this._isAnimationSheetEnabled) {
  56215. this._vertexData[offset++] = particle.cellIndex;
  56216. }
  56217. if (!this._isBillboardBased) {
  56218. if (particle._initialDirection) {
  56219. this._vertexData[offset++] = particle._initialDirection.x;
  56220. this._vertexData[offset++] = particle._initialDirection.y;
  56221. this._vertexData[offset++] = particle._initialDirection.z;
  56222. }
  56223. else {
  56224. this._vertexData[offset++] = particle.direction.x;
  56225. this._vertexData[offset++] = particle.direction.y;
  56226. this._vertexData[offset++] = particle.direction.z;
  56227. }
  56228. }
  56229. if (!this._useInstancing) {
  56230. if (this._isAnimationSheetEnabled) {
  56231. if (offsetX === 0)
  56232. offsetX = this._epsilon;
  56233. else if (offsetX === 1)
  56234. offsetX = 1 - this._epsilon;
  56235. if (offsetY === 0)
  56236. offsetY = this._epsilon;
  56237. else if (offsetY === 1)
  56238. offsetY = 1 - this._epsilon;
  56239. }
  56240. this._vertexData[offset++] = offsetX;
  56241. this._vertexData[offset++] = offsetY;
  56242. }
  56243. };
  56244. ParticleSystem.prototype._stopSubEmitters = function () {
  56245. if (!this.activeSubSystems) {
  56246. return;
  56247. }
  56248. this.activeSubSystems.forEach(function (subSystem) {
  56249. subSystem.stop(true);
  56250. });
  56251. this.activeSubSystems = new Array();
  56252. };
  56253. ParticleSystem.prototype._removeFromRoot = function () {
  56254. if (!this._rootParticleSystem) {
  56255. return;
  56256. }
  56257. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56258. if (index !== -1) {
  56259. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56260. }
  56261. };
  56262. // End of sub system methods
  56263. ParticleSystem.prototype._update = function (newParticles) {
  56264. // Update current
  56265. this._alive = this._particles.length > 0;
  56266. if (this.emitter.position) {
  56267. var emitterMesh = this.emitter;
  56268. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56269. }
  56270. else {
  56271. var emitterPosition = this.emitter;
  56272. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56273. }
  56274. this.updateFunction(this._particles);
  56275. // Add new ones
  56276. var particle;
  56277. var _loop_2 = function () {
  56278. if (this_1._particles.length === this_1._capacity) {
  56279. return "break";
  56280. }
  56281. particle = this_1._createParticle();
  56282. this_1._particles.push(particle);
  56283. // Emitter
  56284. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56285. if (this_1.startPositionFunction) {
  56286. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56287. }
  56288. else {
  56289. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56290. }
  56291. if (this_1.startDirectionFunction) {
  56292. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56293. }
  56294. else {
  56295. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56296. }
  56297. if (emitPower === 0) {
  56298. if (!particle._initialDirection) {
  56299. particle._initialDirection = particle.direction.clone();
  56300. }
  56301. else {
  56302. particle._initialDirection.copyFrom(particle.direction);
  56303. }
  56304. }
  56305. else {
  56306. particle._initialDirection = null;
  56307. }
  56308. particle.direction.scaleInPlace(emitPower);
  56309. // Life time
  56310. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  56311. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  56312. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  56313. var factorGradient1 = currentGradient;
  56314. var factorGradient2 = nextGradient;
  56315. var lifeTime1 = factorGradient1.getFactor();
  56316. var lifeTime2 = factorGradient2.getFactor();
  56317. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  56318. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  56319. });
  56320. }
  56321. else {
  56322. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  56323. }
  56324. // Size
  56325. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  56326. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  56327. }
  56328. else {
  56329. particle._currentSizeGradient = this_1._sizeGradients[0];
  56330. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  56331. particle.size = particle._currentSize1;
  56332. if (this_1._sizeGradients.length > 1) {
  56333. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  56334. }
  56335. else {
  56336. particle._currentSize2 = particle._currentSize1;
  56337. }
  56338. }
  56339. // Size and scale
  56340. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  56341. // Angle
  56342. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  56343. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  56344. }
  56345. else {
  56346. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  56347. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  56348. particle._currentAngularSpeed1 = particle.angularSpeed;
  56349. if (this_1._angularSpeedGradients.length > 1) {
  56350. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  56351. }
  56352. else {
  56353. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  56354. }
  56355. }
  56356. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  56357. // Velocity
  56358. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  56359. particle._currentVelocityGradient = this_1._velocityGradients[0];
  56360. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  56361. if (this_1._velocityGradients.length > 1) {
  56362. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  56363. }
  56364. else {
  56365. particle._currentVelocity2 = particle._currentVelocity1;
  56366. }
  56367. }
  56368. // Limit velocity
  56369. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  56370. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  56371. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  56372. if (this_1._limitVelocityGradients.length > 1) {
  56373. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  56374. }
  56375. else {
  56376. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  56377. }
  56378. }
  56379. // Color
  56380. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  56381. step = BABYLON.Scalar.RandomRange(0, 1.0);
  56382. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  56383. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  56384. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56385. }
  56386. else {
  56387. particle._currentColorGradient = this_1._colorGradients[0];
  56388. particle._currentColorGradient.getColorToRef(particle.color);
  56389. particle._currentColor1.copyFrom(particle.color);
  56390. if (this_1._colorGradients.length > 1) {
  56391. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  56392. }
  56393. else {
  56394. particle._currentColor2.copyFrom(particle.color);
  56395. }
  56396. }
  56397. // Sheet
  56398. if (this_1._isAnimationSheetEnabled) {
  56399. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  56400. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  56401. }
  56402. };
  56403. var this_1 = this, step;
  56404. for (var index = 0; index < newParticles; index++) {
  56405. var state_1 = _loop_2();
  56406. if (state_1 === "break")
  56407. break;
  56408. }
  56409. };
  56410. /** @hidden */
  56411. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  56412. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56413. if (isBillboardBased === void 0) { isBillboardBased = false; }
  56414. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  56415. if (isAnimationSheetEnabled) {
  56416. attributeNamesOrOptions.push("cellIndex");
  56417. }
  56418. if (!isBillboardBased) {
  56419. attributeNamesOrOptions.push("direction");
  56420. }
  56421. return attributeNamesOrOptions;
  56422. };
  56423. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  56424. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56425. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  56426. if (isAnimationSheetEnabled) {
  56427. effectCreationOption.push("particlesInfos");
  56428. }
  56429. return effectCreationOption;
  56430. };
  56431. ParticleSystem.prototype._getEffect = function () {
  56432. if (this._customEffect) {
  56433. return this._customEffect;
  56434. }
  56435. ;
  56436. var defines = [];
  56437. if (this._scene.clipPlane) {
  56438. defines.push("#define CLIPPLANE");
  56439. }
  56440. if (this._isAnimationSheetEnabled) {
  56441. defines.push("#define ANIMATESHEET");
  56442. }
  56443. if (this._isBillboardBased) {
  56444. defines.push("#define BILLBOARD");
  56445. switch (this.billboardMode) {
  56446. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56447. defines.push("#define BILLBOARDY");
  56448. break;
  56449. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56450. default:
  56451. break;
  56452. }
  56453. }
  56454. // Effect
  56455. var join = defines.join("\n");
  56456. if (this._cachedDefines !== join) {
  56457. this._cachedDefines = join;
  56458. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56459. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56460. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56461. }
  56462. return this._effect;
  56463. };
  56464. /**
  56465. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56466. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  56467. */
  56468. ParticleSystem.prototype.animate = function (preWarmOnly) {
  56469. if (preWarmOnly === void 0) { preWarmOnly = false; }
  56470. if (!this._started)
  56471. return;
  56472. if (!preWarmOnly) {
  56473. var effect = this._getEffect();
  56474. // Check
  56475. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56476. return;
  56477. if (this._currentRenderId === this._scene.getRenderId()) {
  56478. return;
  56479. }
  56480. this._currentRenderId = this._scene.getRenderId();
  56481. }
  56482. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  56483. // determine the number of particles we need to create
  56484. var newParticles;
  56485. if (this.manualEmitCount > -1) {
  56486. newParticles = this.manualEmitCount;
  56487. this._newPartsExcess = 0;
  56488. this.manualEmitCount = 0;
  56489. }
  56490. else {
  56491. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56492. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56493. }
  56494. if (this._newPartsExcess > 1.0) {
  56495. newParticles += this._newPartsExcess >> 0;
  56496. this._newPartsExcess -= this._newPartsExcess >> 0;
  56497. }
  56498. this._alive = false;
  56499. if (!this._stopped) {
  56500. this._actualFrame += this._scaledUpdateSpeed;
  56501. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56502. this.stop();
  56503. }
  56504. else {
  56505. newParticles = 0;
  56506. }
  56507. this._update(newParticles);
  56508. // Stopped?
  56509. if (this._stopped) {
  56510. if (!this._alive) {
  56511. this._started = false;
  56512. if (this.onAnimationEnd) {
  56513. this.onAnimationEnd();
  56514. }
  56515. if (this.disposeOnStop) {
  56516. this._scene._toBeDisposed.push(this);
  56517. }
  56518. }
  56519. }
  56520. if (!preWarmOnly) {
  56521. // Update VBO
  56522. var offset = 0;
  56523. for (var index = 0; index < this._particles.length; index++) {
  56524. var particle = this._particles[index];
  56525. this._appendParticleVertices(offset, particle);
  56526. offset += this._useInstancing ? 1 : 4;
  56527. }
  56528. if (this._vertexBuffer) {
  56529. this._vertexBuffer.update(this._vertexData);
  56530. }
  56531. }
  56532. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56533. this.stop();
  56534. }
  56535. };
  56536. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56537. this._appendParticleVertex(offset++, particle, 0, 0);
  56538. if (!this._useInstancing) {
  56539. this._appendParticleVertex(offset++, particle, 1, 0);
  56540. this._appendParticleVertex(offset++, particle, 1, 1);
  56541. this._appendParticleVertex(offset++, particle, 0, 1);
  56542. }
  56543. };
  56544. /**
  56545. * Rebuilds the particle system.
  56546. */
  56547. ParticleSystem.prototype.rebuild = function () {
  56548. this._createIndexBuffer();
  56549. if (this._vertexBuffer) {
  56550. this._vertexBuffer._rebuild();
  56551. }
  56552. };
  56553. /**
  56554. * Is this system ready to be used/rendered
  56555. * @return true if the system is ready
  56556. */
  56557. ParticleSystem.prototype.isReady = function () {
  56558. var effect = this._getEffect();
  56559. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56560. return false;
  56561. }
  56562. return true;
  56563. };
  56564. /**
  56565. * Renders the particle system in its current state.
  56566. * @returns the current number of particles
  56567. */
  56568. ParticleSystem.prototype.render = function () {
  56569. var effect = this._getEffect();
  56570. // Check
  56571. if (!this.isReady() || !this._particles.length) {
  56572. return 0;
  56573. }
  56574. var engine = this._scene.getEngine();
  56575. // Render
  56576. engine.enableEffect(effect);
  56577. engine.setState(false);
  56578. var viewMatrix = this._scene.getViewMatrix();
  56579. effect.setTexture("diffuseSampler", this.particleTexture);
  56580. effect.setMatrix("view", viewMatrix);
  56581. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56582. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56583. var baseSize = this.particleTexture.getBaseSize();
  56584. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56585. }
  56586. effect.setVector2("translationPivot", this.translationPivot);
  56587. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56588. if (this._isBillboardBased) {
  56589. var camera = this._scene.activeCamera;
  56590. effect.setVector3("eyePosition", camera.globalPosition);
  56591. }
  56592. if (this._scene.clipPlane) {
  56593. var clipPlane = this._scene.clipPlane;
  56594. var invView = viewMatrix.clone();
  56595. invView.invert();
  56596. effect.setMatrix("invView", invView);
  56597. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56598. }
  56599. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56600. // Draw order
  56601. switch (this.blendMode) {
  56602. case ParticleSystem.BLENDMODE_ADD:
  56603. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56604. break;
  56605. case ParticleSystem.BLENDMODE_ONEONE:
  56606. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56607. break;
  56608. case ParticleSystem.BLENDMODE_STANDARD:
  56609. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56610. break;
  56611. }
  56612. if (this.forceDepthWrite) {
  56613. engine.setDepthWrite(true);
  56614. }
  56615. if (this._useInstancing) {
  56616. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56617. engine.unbindInstanceAttributes();
  56618. }
  56619. else {
  56620. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56621. }
  56622. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56623. return this._particles.length;
  56624. };
  56625. /**
  56626. * Disposes the particle system and free the associated resources
  56627. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56628. */
  56629. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56630. if (disposeTexture === void 0) { disposeTexture = true; }
  56631. if (this._vertexBuffer) {
  56632. this._vertexBuffer.dispose();
  56633. this._vertexBuffer = null;
  56634. }
  56635. if (this._spriteBuffer) {
  56636. this._spriteBuffer.dispose();
  56637. this._spriteBuffer = null;
  56638. }
  56639. if (this._indexBuffer) {
  56640. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56641. this._indexBuffer = null;
  56642. }
  56643. if (disposeTexture && this.particleTexture) {
  56644. this.particleTexture.dispose();
  56645. this.particleTexture = null;
  56646. }
  56647. if (disposeTexture && this.noiseTexture) {
  56648. this.noiseTexture.dispose();
  56649. this.noiseTexture = null;
  56650. }
  56651. this._removeFromRoot();
  56652. // Remove from scene
  56653. var index = this._scene.particleSystems.indexOf(this);
  56654. if (index > -1) {
  56655. this._scene.particleSystems.splice(index, 1);
  56656. }
  56657. // Callback
  56658. this.onDisposeObservable.notifyObservers(this);
  56659. this.onDisposeObservable.clear();
  56660. };
  56661. // Clone
  56662. /**
  56663. * Clones the particle system.
  56664. * @param name The name of the cloned object
  56665. * @param newEmitter The new emitter to use
  56666. * @returns the cloned particle system
  56667. */
  56668. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56669. var custom = null;
  56670. var program = null;
  56671. if (this.customShader != null) {
  56672. program = this.customShader;
  56673. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56674. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56675. }
  56676. else if (this._customEffect) {
  56677. custom = this._customEffect;
  56678. }
  56679. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56680. result.customShader = program;
  56681. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56682. if (newEmitter === undefined) {
  56683. newEmitter = this.emitter;
  56684. }
  56685. result.emitter = newEmitter;
  56686. if (this.particleTexture) {
  56687. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56688. }
  56689. if (!this.preventAutoStart) {
  56690. result.start();
  56691. }
  56692. return result;
  56693. };
  56694. /**
  56695. * Serializes the particle system to a JSON object.
  56696. * @returns the JSON object
  56697. */
  56698. ParticleSystem.prototype.serialize = function () {
  56699. var serializationObject = {};
  56700. ParticleSystem._Serialize(serializationObject, this);
  56701. serializationObject.textureMask = this.textureMask.asArray();
  56702. serializationObject.customShader = this.customShader;
  56703. serializationObject.preventAutoStart = this.preventAutoStart;
  56704. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56705. return serializationObject;
  56706. };
  56707. /** @hidden */
  56708. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56709. serializationObject.name = particleSystem.name;
  56710. serializationObject.id = particleSystem.id;
  56711. serializationObject.capacity = particleSystem.getCapacity();
  56712. // Emitter
  56713. if (particleSystem.emitter.position) {
  56714. var emitterMesh = particleSystem.emitter;
  56715. serializationObject.emitterId = emitterMesh.id;
  56716. }
  56717. else {
  56718. var emitterPosition = particleSystem.emitter;
  56719. serializationObject.emitter = emitterPosition.asArray();
  56720. }
  56721. // Emitter
  56722. if (particleSystem.particleEmitterType) {
  56723. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56724. }
  56725. if (particleSystem.particleTexture) {
  56726. serializationObject.textureName = particleSystem.particleTexture.name;
  56727. }
  56728. // Animations
  56729. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56730. // Particle system
  56731. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56732. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56733. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56734. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56735. serializationObject.minSize = particleSystem.minSize;
  56736. serializationObject.maxSize = particleSystem.maxSize;
  56737. serializationObject.minScaleX = particleSystem.minScaleX;
  56738. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56739. serializationObject.minScaleY = particleSystem.minScaleY;
  56740. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56741. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56742. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56743. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56744. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56745. serializationObject.emitRate = particleSystem.emitRate;
  56746. serializationObject.gravity = particleSystem.gravity.asArray();
  56747. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  56748. serializationObject.color1 = particleSystem.color1.asArray();
  56749. serializationObject.color2 = particleSystem.color2.asArray();
  56750. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56751. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56752. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56753. serializationObject.blendMode = particleSystem.blendMode;
  56754. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56755. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56756. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56757. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56758. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56759. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56760. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56761. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56762. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56763. var colorGradients = particleSystem.getColorGradients();
  56764. if (colorGradients) {
  56765. serializationObject.colorGradients = [];
  56766. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56767. var colorGradient = colorGradients_1[_i];
  56768. var serializedGradient = {
  56769. gradient: colorGradient.gradient,
  56770. color1: colorGradient.color1.asArray()
  56771. };
  56772. if (colorGradient.color2) {
  56773. serializedGradient.color2 = colorGradient.color2.asArray();
  56774. }
  56775. serializationObject.colorGradients.push(serializedGradient);
  56776. }
  56777. }
  56778. var sizeGradients = particleSystem.getSizeGradients();
  56779. if (sizeGradients) {
  56780. serializationObject.sizeGradients = [];
  56781. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56782. var sizeGradient = sizeGradients_1[_a];
  56783. var serializedGradient = {
  56784. gradient: sizeGradient.gradient,
  56785. factor1: sizeGradient.factor1
  56786. };
  56787. if (sizeGradient.factor2 !== undefined) {
  56788. serializedGradient.factor2 = sizeGradient.factor2;
  56789. }
  56790. serializationObject.sizeGradients.push(serializedGradient);
  56791. }
  56792. }
  56793. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56794. if (angularSpeedGradients) {
  56795. serializationObject.angularSpeedGradients = [];
  56796. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56797. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56798. var serializedGradient = {
  56799. gradient: angularSpeedGradient.gradient,
  56800. factor1: angularSpeedGradient.factor1
  56801. };
  56802. if (angularSpeedGradient.factor2 !== undefined) {
  56803. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56804. }
  56805. serializationObject.angularSpeedGradients.push(serializedGradient);
  56806. }
  56807. }
  56808. var velocityGradients = particleSystem.getVelocityGradients();
  56809. if (velocityGradients) {
  56810. serializationObject.velocityGradients = [];
  56811. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56812. var velocityGradient = velocityGradients_1[_c];
  56813. var serializedGradient = {
  56814. gradient: velocityGradient.gradient,
  56815. factor1: velocityGradient.factor1
  56816. };
  56817. if (velocityGradient.factor2 !== undefined) {
  56818. serializedGradient.factor2 = velocityGradient.factor2;
  56819. }
  56820. serializationObject.velocityGradients.push(serializedGradient);
  56821. }
  56822. }
  56823. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  56824. if (limitVelocityGradients) {
  56825. serializationObject.limitVelocityGradients = [];
  56826. for (var _d = 0, limitVelocityGradients_1 = limitVelocityGradients; _d < limitVelocityGradients_1.length; _d++) {
  56827. var limitVelocityGradient = limitVelocityGradients_1[_d];
  56828. var serializedGradient = {
  56829. gradient: limitVelocityGradient.gradient,
  56830. factor1: limitVelocityGradient.factor1
  56831. };
  56832. if (limitVelocityGradient.factor2 !== undefined) {
  56833. serializedGradient.factor2 = limitVelocityGradient.factor2;
  56834. }
  56835. serializationObject.limitVelocityGradients.push(serializedGradient);
  56836. }
  56837. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  56838. }
  56839. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  56840. var noiseTexture = particleSystem.noiseTexture;
  56841. serializationObject.noiseTexture = noiseTexture.serialize();
  56842. }
  56843. };
  56844. /** @hidden */
  56845. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56846. // Texture
  56847. if (parsedParticleSystem.textureName) {
  56848. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56849. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56850. }
  56851. // Emitter
  56852. if (parsedParticleSystem.emitterId === undefined) {
  56853. particleSystem.emitter = BABYLON.Vector3.Zero();
  56854. }
  56855. else if (parsedParticleSystem.emitterId) {
  56856. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56857. }
  56858. else {
  56859. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56860. }
  56861. // Misc.
  56862. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56863. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56864. }
  56865. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56866. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56867. }
  56868. // Animations
  56869. if (parsedParticleSystem.animations) {
  56870. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56871. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56872. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56873. }
  56874. }
  56875. if (parsedParticleSystem.autoAnimate) {
  56876. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56877. }
  56878. // Particle system
  56879. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56880. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56881. particleSystem.minSize = parsedParticleSystem.minSize;
  56882. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56883. if (parsedParticleSystem.minScaleX) {
  56884. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56885. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56886. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56887. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56888. }
  56889. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56890. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56891. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56892. }
  56893. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56894. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56895. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56896. }
  56897. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56898. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56899. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56900. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56901. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56902. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56903. if (parsedParticleSystem.noiseStrength) {
  56904. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  56905. }
  56906. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56907. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56908. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56909. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56910. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56911. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56912. if (parsedParticleSystem.colorGradients) {
  56913. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56914. var colorGradient = _a[_i];
  56915. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56916. }
  56917. }
  56918. if (parsedParticleSystem.sizeGradients) {
  56919. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56920. var sizeGradient = _c[_b];
  56921. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56922. }
  56923. }
  56924. if (parsedParticleSystem.angularSpeedGradients) {
  56925. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56926. var angularSpeedGradient = _e[_d];
  56927. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56928. }
  56929. }
  56930. if (parsedParticleSystem.velocityGradients) {
  56931. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56932. var velocityGradient = _g[_f];
  56933. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56934. }
  56935. }
  56936. if (parsedParticleSystem.limitVelocityGradients) {
  56937. for (var _h = 0, _j = parsedParticleSystem.limitVelocityGradients; _h < _j.length; _h++) {
  56938. var limitVelocityGradient = _j[_h];
  56939. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  56940. }
  56941. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  56942. }
  56943. if (parsedParticleSystem.noiseTexture) {
  56944. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  56945. }
  56946. // Emitter
  56947. var emitterType;
  56948. if (parsedParticleSystem.particleEmitterType) {
  56949. switch (parsedParticleSystem.particleEmitterType.type) {
  56950. case "SphereParticleEmitter":
  56951. emitterType = new BABYLON.SphereParticleEmitter();
  56952. break;
  56953. case "SphereDirectedParticleEmitter":
  56954. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56955. break;
  56956. case "ConeEmitter":
  56957. case "ConeParticleEmitter":
  56958. emitterType = new BABYLON.ConeParticleEmitter();
  56959. break;
  56960. case "BoxEmitter":
  56961. case "BoxParticleEmitter":
  56962. default:
  56963. emitterType = new BABYLON.BoxParticleEmitter();
  56964. break;
  56965. }
  56966. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56967. }
  56968. else {
  56969. emitterType = new BABYLON.BoxParticleEmitter();
  56970. emitterType.parse(parsedParticleSystem);
  56971. }
  56972. particleSystem.particleEmitterType = emitterType;
  56973. // Animation sheet
  56974. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56975. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56976. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56977. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56978. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56979. };
  56980. /**
  56981. * Parses a JSON object to create a particle system.
  56982. * @param parsedParticleSystem The JSON object to parse
  56983. * @param scene The scene to create the particle system in
  56984. * @param rootUrl The root url to use to load external dependencies like texture
  56985. * @returns the Parsed particle system
  56986. */
  56987. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56988. var name = parsedParticleSystem.name;
  56989. var custom = null;
  56990. var program = null;
  56991. if (parsedParticleSystem.customShader) {
  56992. program = parsedParticleSystem.customShader;
  56993. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56994. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56995. }
  56996. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56997. particleSystem.customShader = program;
  56998. if (parsedParticleSystem.id) {
  56999. particleSystem.id = parsedParticleSystem.id;
  57000. }
  57001. // Auto start
  57002. if (parsedParticleSystem.preventAutoStart) {
  57003. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57004. }
  57005. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57006. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57007. if (!particleSystem.preventAutoStart) {
  57008. particleSystem.start();
  57009. }
  57010. return particleSystem;
  57011. };
  57012. return ParticleSystem;
  57013. }(BABYLON.BaseParticleSystem));
  57014. BABYLON.ParticleSystem = ParticleSystem;
  57015. })(BABYLON || (BABYLON = {}));
  57016. //# sourceMappingURL=babylon.particleSystem.js.map
  57017. var BABYLON;
  57018. (function (BABYLON) {
  57019. /**
  57020. * Particle emitter emitting particles from the inside of a box.
  57021. * It emits the particles randomly between 2 given directions.
  57022. */
  57023. var BoxParticleEmitter = /** @class */ (function () {
  57024. /**
  57025. * Creates a new instance BoxParticleEmitter
  57026. */
  57027. function BoxParticleEmitter() {
  57028. /**
  57029. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57030. */
  57031. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57032. /**
  57033. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57034. */
  57035. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57036. /**
  57037. * 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.
  57038. */
  57039. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57040. /**
  57041. * 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.
  57042. */
  57043. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57044. }
  57045. /**
  57046. * Called by the particle System when the direction is computed for the created particle.
  57047. * @param worldMatrix is the world matrix of the particle system
  57048. * @param directionToUpdate is the direction vector to update with the result
  57049. * @param particle is the particle we are computed the direction for
  57050. */
  57051. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57052. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57053. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57054. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57055. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57056. };
  57057. /**
  57058. * Called by the particle System when the position is computed for the created particle.
  57059. * @param worldMatrix is the world matrix of the particle system
  57060. * @param positionToUpdate is the position vector to update with the result
  57061. * @param particle is the particle we are computed the position for
  57062. */
  57063. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57064. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57065. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57066. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57067. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57068. };
  57069. /**
  57070. * Clones the current emitter and returns a copy of it
  57071. * @returns the new emitter
  57072. */
  57073. BoxParticleEmitter.prototype.clone = function () {
  57074. var newOne = new BoxParticleEmitter();
  57075. BABYLON.Tools.DeepCopy(this, newOne);
  57076. return newOne;
  57077. };
  57078. /**
  57079. * Called by the GPUParticleSystem to setup the update shader
  57080. * @param effect defines the update shader
  57081. */
  57082. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57083. effect.setVector3("direction1", this.direction1);
  57084. effect.setVector3("direction2", this.direction2);
  57085. effect.setVector3("minEmitBox", this.minEmitBox);
  57086. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57087. };
  57088. /**
  57089. * Returns a string to use to update the GPU particles update shader
  57090. * @returns a string containng the defines string
  57091. */
  57092. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57093. return "#define BOXEMITTER";
  57094. };
  57095. /**
  57096. * Returns the string "BoxParticleEmitter"
  57097. * @returns a string containing the class name
  57098. */
  57099. BoxParticleEmitter.prototype.getClassName = function () {
  57100. return "BoxParticleEmitter";
  57101. };
  57102. /**
  57103. * Serializes the particle system to a JSON object.
  57104. * @returns the JSON object
  57105. */
  57106. BoxParticleEmitter.prototype.serialize = function () {
  57107. var serializationObject = {};
  57108. serializationObject.type = this.getClassName();
  57109. serializationObject.direction1 = this.direction1.asArray();
  57110. serializationObject.direction2 = this.direction2.asArray();
  57111. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57112. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57113. return serializationObject;
  57114. };
  57115. /**
  57116. * Parse properties from a JSON object
  57117. * @param serializationObject defines the JSON object
  57118. */
  57119. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57120. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57121. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57122. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  57123. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  57124. };
  57125. return BoxParticleEmitter;
  57126. }());
  57127. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57128. })(BABYLON || (BABYLON = {}));
  57129. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57130. var BABYLON;
  57131. (function (BABYLON) {
  57132. /**
  57133. * Particle emitter emitting particles from the inside of a cone.
  57134. * It emits the particles alongside the cone volume from the base to the particle.
  57135. * The emission direction might be randomized.
  57136. */
  57137. var ConeParticleEmitter = /** @class */ (function () {
  57138. /**
  57139. * Creates a new instance ConeParticleEmitter
  57140. * @param radius the radius of the emission cone (1 by default)
  57141. * @param angles the cone base angle (PI by default)
  57142. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  57143. */
  57144. function ConeParticleEmitter(radius, angle,
  57145. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  57146. directionRandomizer) {
  57147. if (radius === void 0) { radius = 1; }
  57148. if (angle === void 0) { angle = Math.PI; }
  57149. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57150. this.directionRandomizer = directionRandomizer;
  57151. /**
  57152. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  57153. */
  57154. this.radiusRange = 1;
  57155. /**
  57156. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  57157. */
  57158. this.heightRange = 1;
  57159. /**
  57160. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  57161. */
  57162. this.emitFromSpawnPointOnly = false;
  57163. this.angle = angle;
  57164. this.radius = radius;
  57165. }
  57166. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57167. /**
  57168. * Gets or sets the radius of the emission cone
  57169. */
  57170. get: function () {
  57171. return this._radius;
  57172. },
  57173. set: function (value) {
  57174. this._radius = value;
  57175. this._buildHeight();
  57176. },
  57177. enumerable: true,
  57178. configurable: true
  57179. });
  57180. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  57181. /**
  57182. * Gets or sets the angle of the emission cone
  57183. */
  57184. get: function () {
  57185. return this._angle;
  57186. },
  57187. set: function (value) {
  57188. this._angle = value;
  57189. this._buildHeight();
  57190. },
  57191. enumerable: true,
  57192. configurable: true
  57193. });
  57194. ConeParticleEmitter.prototype._buildHeight = function () {
  57195. if (this._angle !== 0) {
  57196. this._height = this._radius / Math.tan(this._angle / 2);
  57197. }
  57198. else {
  57199. this._height = 1;
  57200. }
  57201. };
  57202. /**
  57203. * Called by the particle System when the direction is computed for the created particle.
  57204. * @param worldMatrix is the world matrix of the particle system
  57205. * @param directionToUpdate is the direction vector to update with the result
  57206. * @param particle is the particle we are computed the direction for
  57207. */
  57208. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57209. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  57210. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  57211. }
  57212. else {
  57213. // measure the direction Vector from the emitter to the particle.
  57214. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57215. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57216. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57217. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57218. direction.x += randX;
  57219. direction.y += randY;
  57220. direction.z += randZ;
  57221. direction.normalize();
  57222. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57223. }
  57224. };
  57225. /**
  57226. * Called by the particle System when the position is computed for the created particle.
  57227. * @param worldMatrix is the world matrix of the particle system
  57228. * @param positionToUpdate is the position vector to update with the result
  57229. * @param particle is the particle we are computed the position for
  57230. */
  57231. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57232. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57233. var h;
  57234. if (!this.emitFromSpawnPointOnly) {
  57235. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  57236. // Better distribution in a cone at normal angles.
  57237. h = 1 - h * h;
  57238. }
  57239. else {
  57240. h = 0.0001;
  57241. }
  57242. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  57243. radius = radius * h;
  57244. var randX = radius * Math.sin(s);
  57245. var randZ = radius * Math.cos(s);
  57246. var randY = h * this._height;
  57247. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57248. };
  57249. /**
  57250. * Clones the current emitter and returns a copy of it
  57251. * @returns the new emitter
  57252. */
  57253. ConeParticleEmitter.prototype.clone = function () {
  57254. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  57255. BABYLON.Tools.DeepCopy(this, newOne);
  57256. return newOne;
  57257. };
  57258. /**
  57259. * Called by the GPUParticleSystem to setup the update shader
  57260. * @param effect defines the update shader
  57261. */
  57262. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57263. effect.setFloat2("radius", this._radius, this.radiusRange);
  57264. effect.setFloat("coneAngle", this._angle);
  57265. effect.setFloat2("height", this._height, this.heightRange);
  57266. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57267. };
  57268. /**
  57269. * Returns a string to use to update the GPU particles update shader
  57270. * @returns a string containng the defines string
  57271. */
  57272. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57273. var defines = "#define CONEEMITTER";
  57274. if (this.emitFromSpawnPointOnly) {
  57275. defines += "\n#define CONEEMITTERSPAWNPOINT";
  57276. }
  57277. return defines;
  57278. };
  57279. /**
  57280. * Returns the string "ConeParticleEmitter"
  57281. * @returns a string containing the class name
  57282. */
  57283. ConeParticleEmitter.prototype.getClassName = function () {
  57284. return "ConeParticleEmitter";
  57285. };
  57286. /**
  57287. * Serializes the particle system to a JSON object.
  57288. * @returns the JSON object
  57289. */
  57290. ConeParticleEmitter.prototype.serialize = function () {
  57291. var serializationObject = {};
  57292. serializationObject.type = this.getClassName();
  57293. serializationObject.radius = this._radius;
  57294. serializationObject.angle = this._angle;
  57295. serializationObject.directionRandomizer = this.directionRandomizer;
  57296. return serializationObject;
  57297. };
  57298. /**
  57299. * Parse properties from a JSON object
  57300. * @param serializationObject defines the JSON object
  57301. */
  57302. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57303. this.radius = serializationObject.radius;
  57304. this.angle = serializationObject.angle;
  57305. this.directionRandomizer = serializationObject.directionRandomizer;
  57306. };
  57307. return ConeParticleEmitter;
  57308. }());
  57309. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57310. })(BABYLON || (BABYLON = {}));
  57311. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57312. var BABYLON;
  57313. (function (BABYLON) {
  57314. /**
  57315. * Particle emitter emitting particles from the inside of a sphere.
  57316. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57317. */
  57318. var SphereParticleEmitter = /** @class */ (function () {
  57319. /**
  57320. * Creates a new instance SphereParticleEmitter
  57321. * @param radius the radius of the emission sphere (1 by default)
  57322. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57323. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57324. */
  57325. function SphereParticleEmitter(
  57326. /**
  57327. * The radius of the emission sphere.
  57328. */
  57329. radius,
  57330. /**
  57331. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57332. */
  57333. radiusRange,
  57334. /**
  57335. * How much to randomize the particle direction [0-1].
  57336. */
  57337. directionRandomizer) {
  57338. if (radius === void 0) { radius = 1; }
  57339. if (radiusRange === void 0) { radiusRange = 1; }
  57340. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57341. this.radius = radius;
  57342. this.radiusRange = radiusRange;
  57343. this.directionRandomizer = directionRandomizer;
  57344. }
  57345. /**
  57346. * Called by the particle System when the direction is computed for the created particle.
  57347. * @param worldMatrix is the world matrix of the particle system
  57348. * @param directionToUpdate is the direction vector to update with the result
  57349. * @param particle is the particle we are computed the direction for
  57350. */
  57351. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57352. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57353. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57354. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57355. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57356. direction.x += randX;
  57357. direction.y += randY;
  57358. direction.z += randZ;
  57359. direction.normalize();
  57360. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57361. };
  57362. /**
  57363. * Called by the particle System when the position is computed for the created particle.
  57364. * @param worldMatrix is the world matrix of the particle system
  57365. * @param positionToUpdate is the position vector to update with the result
  57366. * @param particle is the particle we are computed the position for
  57367. */
  57368. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57369. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  57370. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  57371. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57372. var theta = Math.acos(2 * v - 1);
  57373. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57374. var randY = randRadius * Math.cos(theta);
  57375. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57376. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57377. };
  57378. /**
  57379. * Clones the current emitter and returns a copy of it
  57380. * @returns the new emitter
  57381. */
  57382. SphereParticleEmitter.prototype.clone = function () {
  57383. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57384. BABYLON.Tools.DeepCopy(this, newOne);
  57385. return newOne;
  57386. };
  57387. /**
  57388. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57389. * @param effect defines the update shader
  57390. */
  57391. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57392. effect.setFloat("radius", this.radius);
  57393. effect.setFloat("radiusRange", this.radiusRange);
  57394. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57395. };
  57396. /**
  57397. * Returns a string to use to update the GPU particles update shader
  57398. * @returns a string containng the defines string
  57399. */
  57400. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57401. return "#define SPHEREEMITTER";
  57402. };
  57403. /**
  57404. * Returns the string "SphereParticleEmitter"
  57405. * @returns a string containing the class name
  57406. */
  57407. SphereParticleEmitter.prototype.getClassName = function () {
  57408. return "SphereParticleEmitter";
  57409. };
  57410. /**
  57411. * Serializes the particle system to a JSON object.
  57412. * @returns the JSON object
  57413. */
  57414. SphereParticleEmitter.prototype.serialize = function () {
  57415. var serializationObject = {};
  57416. serializationObject.type = this.getClassName();
  57417. serializationObject.radius = this.radius;
  57418. serializationObject.radiusRange = this.radiusRange;
  57419. serializationObject.directionRandomizer = this.directionRandomizer;
  57420. return serializationObject;
  57421. };
  57422. /**
  57423. * Parse properties from a JSON object
  57424. * @param serializationObject defines the JSON object
  57425. */
  57426. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57427. this.radius = serializationObject.radius;
  57428. this.radiusRange = serializationObject.radiusRange;
  57429. this.directionRandomizer = serializationObject.directionRandomizer;
  57430. };
  57431. return SphereParticleEmitter;
  57432. }());
  57433. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57434. /**
  57435. * Particle emitter emitting particles from the inside of a sphere.
  57436. * It emits the particles randomly between two vectors.
  57437. */
  57438. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57439. __extends(SphereDirectedParticleEmitter, _super);
  57440. /**
  57441. * Creates a new instance SphereDirectedParticleEmitter
  57442. * @param radius the radius of the emission sphere (1 by default)
  57443. * @param direction1 the min limit of the emission direction (up vector by default)
  57444. * @param direction2 the max limit of the emission direction (up vector by default)
  57445. */
  57446. function SphereDirectedParticleEmitter(radius,
  57447. /**
  57448. * The min limit of the emission direction.
  57449. */
  57450. direction1,
  57451. /**
  57452. * The max limit of the emission direction.
  57453. */
  57454. direction2) {
  57455. if (radius === void 0) { radius = 1; }
  57456. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57457. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57458. var _this = _super.call(this, radius) || this;
  57459. _this.direction1 = direction1;
  57460. _this.direction2 = direction2;
  57461. return _this;
  57462. }
  57463. /**
  57464. * Called by the particle System when the direction is computed for the created particle.
  57465. * @param worldMatrix is the world matrix of the particle system
  57466. * @param directionToUpdate is the direction vector to update with the result
  57467. * @param particle is the particle we are computed the direction for
  57468. */
  57469. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57470. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57471. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57472. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57473. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57474. };
  57475. /**
  57476. * Clones the current emitter and returns a copy of it
  57477. * @returns the new emitter
  57478. */
  57479. SphereDirectedParticleEmitter.prototype.clone = function () {
  57480. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57481. BABYLON.Tools.DeepCopy(this, newOne);
  57482. return newOne;
  57483. };
  57484. /**
  57485. * Called by the GPUParticleSystem to setup the update shader
  57486. * @param effect defines the update shader
  57487. */
  57488. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57489. effect.setFloat("radius", this.radius);
  57490. effect.setFloat("radiusRange", this.radiusRange);
  57491. effect.setVector3("direction1", this.direction1);
  57492. effect.setVector3("direction2", this.direction2);
  57493. };
  57494. /**
  57495. * Returns a string to use to update the GPU particles update shader
  57496. * @returns a string containng the defines string
  57497. */
  57498. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57499. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57500. };
  57501. /**
  57502. * Returns the string "SphereDirectedParticleEmitter"
  57503. * @returns a string containing the class name
  57504. */
  57505. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57506. return "SphereDirectedParticleEmitter";
  57507. };
  57508. /**
  57509. * Serializes the particle system to a JSON object.
  57510. * @returns the JSON object
  57511. */
  57512. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57513. var serializationObject = _super.prototype.serialize.call(this);
  57514. serializationObject.direction1 = this.direction1.asArray();
  57515. serializationObject.direction2 = this.direction2.asArray();
  57516. return serializationObject;
  57517. };
  57518. /**
  57519. * Parse properties from a JSON object
  57520. * @param serializationObject defines the JSON object
  57521. */
  57522. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57523. _super.prototype.parse.call(this, serializationObject);
  57524. this.direction1.copyFrom(serializationObject.direction1);
  57525. this.direction2.copyFrom(serializationObject.direction2);
  57526. };
  57527. return SphereDirectedParticleEmitter;
  57528. }(SphereParticleEmitter));
  57529. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57530. })(BABYLON || (BABYLON = {}));
  57531. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57532. var BABYLON;
  57533. (function (BABYLON) {
  57534. /**
  57535. * Particle emitter emitting particles from the inside of a hemisphere.
  57536. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  57537. */
  57538. var HemisphericParticleEmitter = /** @class */ (function () {
  57539. /**
  57540. * Creates a new instance HemisphericParticleEmitter
  57541. * @param radius the radius of the emission hemisphere (1 by default)
  57542. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57543. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57544. */
  57545. function HemisphericParticleEmitter(
  57546. /**
  57547. * The radius of the emission hemisphere.
  57548. */
  57549. radius,
  57550. /**
  57551. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57552. */
  57553. radiusRange,
  57554. /**
  57555. * How much to randomize the particle direction [0-1].
  57556. */
  57557. directionRandomizer) {
  57558. if (radius === void 0) { radius = 1; }
  57559. if (radiusRange === void 0) { radiusRange = 1; }
  57560. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57561. this.radius = radius;
  57562. this.radiusRange = radiusRange;
  57563. this.directionRandomizer = directionRandomizer;
  57564. }
  57565. /**
  57566. * Called by the particle System when the direction is computed for the created particle.
  57567. * @param worldMatrix is the world matrix of the particle system
  57568. * @param directionToUpdate is the direction vector to update with the result
  57569. * @param particle is the particle we are computed the direction for
  57570. */
  57571. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57572. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57573. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57574. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57575. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57576. direction.x += randX;
  57577. direction.y += randY;
  57578. direction.z += randZ;
  57579. direction.normalize();
  57580. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57581. };
  57582. /**
  57583. * Called by the particle System when the position is computed for the created particle.
  57584. * @param worldMatrix is the world matrix of the particle system
  57585. * @param positionToUpdate is the position vector to update with the result
  57586. * @param particle is the particle we are computed the position for
  57587. */
  57588. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57589. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  57590. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  57591. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57592. var theta = Math.acos(2 * v - 1);
  57593. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57594. var randY = randRadius * Math.cos(theta);
  57595. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57596. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  57597. };
  57598. /**
  57599. * Clones the current emitter and returns a copy of it
  57600. * @returns the new emitter
  57601. */
  57602. HemisphericParticleEmitter.prototype.clone = function () {
  57603. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  57604. BABYLON.Tools.DeepCopy(this, newOne);
  57605. return newOne;
  57606. };
  57607. /**
  57608. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57609. * @param effect defines the update shader
  57610. */
  57611. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  57612. effect.setFloat("radius", this.radius);
  57613. effect.setFloat("radiusRange", this.radiusRange);
  57614. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57615. };
  57616. /**
  57617. * Returns a string to use to update the GPU particles update shader
  57618. * @returns a string containng the defines string
  57619. */
  57620. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  57621. return "#define HEMISPHERICEMITTER";
  57622. };
  57623. /**
  57624. * Returns the string "HemisphericParticleEmitter"
  57625. * @returns a string containing the class name
  57626. */
  57627. HemisphericParticleEmitter.prototype.getClassName = function () {
  57628. return "HemisphericParticleEmitter";
  57629. };
  57630. /**
  57631. * Serializes the particle system to a JSON object.
  57632. * @returns the JSON object
  57633. */
  57634. HemisphericParticleEmitter.prototype.serialize = function () {
  57635. var serializationObject = {};
  57636. serializationObject.type = this.getClassName();
  57637. serializationObject.radius = this.radius;
  57638. serializationObject.radiusRange = this.radiusRange;
  57639. serializationObject.directionRandomizer = this.directionRandomizer;
  57640. return serializationObject;
  57641. };
  57642. /**
  57643. * Parse properties from a JSON object
  57644. * @param serializationObject defines the JSON object
  57645. */
  57646. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  57647. this.radius = serializationObject.radius;
  57648. this.radiusRange = serializationObject.radiusRange;
  57649. this.directionRandomizer = serializationObject.directionRandomizer;
  57650. };
  57651. return HemisphericParticleEmitter;
  57652. }());
  57653. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  57654. })(BABYLON || (BABYLON = {}));
  57655. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  57656. var BABYLON;
  57657. (function (BABYLON) {
  57658. /**
  57659. * Particle emitter emitting particles from a point.
  57660. * It emits the particles randomly between 2 given directions.
  57661. */
  57662. var PointParticleEmitter = /** @class */ (function () {
  57663. /**
  57664. * Creates a new instance PointParticleEmitter
  57665. */
  57666. function PointParticleEmitter() {
  57667. /**
  57668. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57669. */
  57670. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57671. /**
  57672. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57673. */
  57674. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57675. }
  57676. /**
  57677. * Called by the particle System when the direction is computed for the created particle.
  57678. * @param worldMatrix is the world matrix of the particle system
  57679. * @param directionToUpdate is the direction vector to update with the result
  57680. * @param particle is the particle we are computed the direction for
  57681. */
  57682. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57683. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57684. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57685. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57686. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57687. };
  57688. /**
  57689. * Called by the particle System when the position is computed for the created particle.
  57690. * @param worldMatrix is the world matrix of the particle system
  57691. * @param positionToUpdate is the position vector to update with the result
  57692. * @param particle is the particle we are computed the position for
  57693. */
  57694. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57695. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  57696. };
  57697. /**
  57698. * Clones the current emitter and returns a copy of it
  57699. * @returns the new emitter
  57700. */
  57701. PointParticleEmitter.prototype.clone = function () {
  57702. var newOne = new PointParticleEmitter();
  57703. BABYLON.Tools.DeepCopy(this, newOne);
  57704. return newOne;
  57705. };
  57706. /**
  57707. * Called by the GPUParticleSystem to setup the update shader
  57708. * @param effect defines the update shader
  57709. */
  57710. PointParticleEmitter.prototype.applyToShader = function (effect) {
  57711. effect.setVector3("direction1", this.direction1);
  57712. effect.setVector3("direction2", this.direction2);
  57713. };
  57714. /**
  57715. * Returns a string to use to update the GPU particles update shader
  57716. * @returns a string containng the defines string
  57717. */
  57718. PointParticleEmitter.prototype.getEffectDefines = function () {
  57719. return "#define POINTEMITTER";
  57720. };
  57721. /**
  57722. * Returns the string "PointParticleEmitter"
  57723. * @returns a string containing the class name
  57724. */
  57725. PointParticleEmitter.prototype.getClassName = function () {
  57726. return "PointParticleEmitter";
  57727. };
  57728. /**
  57729. * Serializes the particle system to a JSON object.
  57730. * @returns the JSON object
  57731. */
  57732. PointParticleEmitter.prototype.serialize = function () {
  57733. var serializationObject = {};
  57734. serializationObject.type = this.getClassName();
  57735. serializationObject.direction1 = this.direction1.asArray();
  57736. serializationObject.direction2 = this.direction2.asArray();
  57737. return serializationObject;
  57738. };
  57739. /**
  57740. * Parse properties from a JSON object
  57741. * @param serializationObject defines the JSON object
  57742. */
  57743. PointParticleEmitter.prototype.parse = function (serializationObject) {
  57744. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57745. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57746. };
  57747. return PointParticleEmitter;
  57748. }());
  57749. BABYLON.PointParticleEmitter = PointParticleEmitter;
  57750. })(BABYLON || (BABYLON = {}));
  57751. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  57752. var BABYLON;
  57753. (function (BABYLON) {
  57754. // Adds the parsers to the scene parsers.
  57755. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  57756. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  57757. if (!individualParser) {
  57758. return;
  57759. }
  57760. // Particles Systems
  57761. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57762. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57763. var parsedParticleSystem = parsedData.particleSystems[index];
  57764. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  57765. }
  57766. }
  57767. });
  57768. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  57769. if (parsedParticleSystem.activeParticleCount) {
  57770. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57771. return ps;
  57772. }
  57773. else {
  57774. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57775. return ps;
  57776. }
  57777. });
  57778. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  57779. if (uniformsNames === void 0) { uniformsNames = []; }
  57780. if (samplers === void 0) { samplers = []; }
  57781. if (defines === void 0) { defines = ""; }
  57782. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  57783. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  57784. if (defines.indexOf(" BILLBOARD") === -1) {
  57785. defines += "\n#define BILLBOARD\n";
  57786. }
  57787. if (samplers.indexOf("diffuseSampler") === -1) {
  57788. samplers.push("diffuseSampler");
  57789. }
  57790. return this.createEffect({
  57791. vertex: "particles",
  57792. fragmentElement: fragmentName
  57793. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  57794. };
  57795. })(BABYLON || (BABYLON = {}));
  57796. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  57797. var BABYLON;
  57798. (function (BABYLON) {
  57799. var ShaderMaterial = /** @class */ (function (_super) {
  57800. __extends(ShaderMaterial, _super);
  57801. function ShaderMaterial(name, scene, shaderPath, options) {
  57802. var _this = _super.call(this, name, scene) || this;
  57803. _this._textures = {};
  57804. _this._textureArrays = {};
  57805. _this._floats = {};
  57806. _this._ints = {};
  57807. _this._floatsArrays = {};
  57808. _this._colors3 = {};
  57809. _this._colors3Arrays = {};
  57810. _this._colors4 = {};
  57811. _this._vectors2 = {};
  57812. _this._vectors3 = {};
  57813. _this._vectors4 = {};
  57814. _this._matrices = {};
  57815. _this._matrices3x3 = {};
  57816. _this._matrices2x2 = {};
  57817. _this._vectors2Arrays = {};
  57818. _this._vectors3Arrays = {};
  57819. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  57820. _this._shaderPath = shaderPath;
  57821. options.needAlphaBlending = options.needAlphaBlending || false;
  57822. options.needAlphaTesting = options.needAlphaTesting || false;
  57823. options.attributes = options.attributes || ["position", "normal", "uv"];
  57824. options.uniforms = options.uniforms || ["worldViewProjection"];
  57825. options.uniformBuffers = options.uniformBuffers || [];
  57826. options.samplers = options.samplers || [];
  57827. options.defines = options.defines || [];
  57828. _this._options = options;
  57829. return _this;
  57830. }
  57831. ShaderMaterial.prototype.getClassName = function () {
  57832. return "ShaderMaterial";
  57833. };
  57834. ShaderMaterial.prototype.needAlphaBlending = function () {
  57835. return this._options.needAlphaBlending;
  57836. };
  57837. ShaderMaterial.prototype.needAlphaTesting = function () {
  57838. return this._options.needAlphaTesting;
  57839. };
  57840. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  57841. if (this._options.uniforms.indexOf(uniformName) === -1) {
  57842. this._options.uniforms.push(uniformName);
  57843. }
  57844. };
  57845. ShaderMaterial.prototype.setTexture = function (name, texture) {
  57846. if (this._options.samplers.indexOf(name) === -1) {
  57847. this._options.samplers.push(name);
  57848. }
  57849. this._textures[name] = texture;
  57850. return this;
  57851. };
  57852. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  57853. if (this._options.samplers.indexOf(name) === -1) {
  57854. this._options.samplers.push(name);
  57855. }
  57856. this._checkUniform(name);
  57857. this._textureArrays[name] = textures;
  57858. return this;
  57859. };
  57860. ShaderMaterial.prototype.setFloat = function (name, value) {
  57861. this._checkUniform(name);
  57862. this._floats[name] = value;
  57863. return this;
  57864. };
  57865. ShaderMaterial.prototype.setInt = function (name, value) {
  57866. this._checkUniform(name);
  57867. this._ints[name] = value;
  57868. return this;
  57869. };
  57870. ShaderMaterial.prototype.setFloats = function (name, value) {
  57871. this._checkUniform(name);
  57872. this._floatsArrays[name] = value;
  57873. return this;
  57874. };
  57875. ShaderMaterial.prototype.setColor3 = function (name, value) {
  57876. this._checkUniform(name);
  57877. this._colors3[name] = value;
  57878. return this;
  57879. };
  57880. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  57881. this._checkUniform(name);
  57882. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  57883. color.toArray(arr, arr.length);
  57884. return arr;
  57885. }, []);
  57886. return this;
  57887. };
  57888. ShaderMaterial.prototype.setColor4 = function (name, value) {
  57889. this._checkUniform(name);
  57890. this._colors4[name] = value;
  57891. return this;
  57892. };
  57893. ShaderMaterial.prototype.setVector2 = function (name, value) {
  57894. this._checkUniform(name);
  57895. this._vectors2[name] = value;
  57896. return this;
  57897. };
  57898. ShaderMaterial.prototype.setVector3 = function (name, value) {
  57899. this._checkUniform(name);
  57900. this._vectors3[name] = value;
  57901. return this;
  57902. };
  57903. ShaderMaterial.prototype.setVector4 = function (name, value) {
  57904. this._checkUniform(name);
  57905. this._vectors4[name] = value;
  57906. return this;
  57907. };
  57908. ShaderMaterial.prototype.setMatrix = function (name, value) {
  57909. this._checkUniform(name);
  57910. this._matrices[name] = value;
  57911. return this;
  57912. };
  57913. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  57914. this._checkUniform(name);
  57915. this._matrices3x3[name] = value;
  57916. return this;
  57917. };
  57918. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  57919. this._checkUniform(name);
  57920. this._matrices2x2[name] = value;
  57921. return this;
  57922. };
  57923. ShaderMaterial.prototype.setArray2 = function (name, value) {
  57924. this._checkUniform(name);
  57925. this._vectors2Arrays[name] = value;
  57926. return this;
  57927. };
  57928. ShaderMaterial.prototype.setArray3 = function (name, value) {
  57929. this._checkUniform(name);
  57930. this._vectors3Arrays[name] = value;
  57931. return this;
  57932. };
  57933. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57934. if (!mesh) {
  57935. return true;
  57936. }
  57937. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  57938. return false;
  57939. }
  57940. return false;
  57941. };
  57942. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  57943. var scene = this.getScene();
  57944. var engine = scene.getEngine();
  57945. if (!this.checkReadyOnEveryCall) {
  57946. if (this._renderId === scene.getRenderId()) {
  57947. if (this._checkCache(scene, mesh, useInstances)) {
  57948. return true;
  57949. }
  57950. }
  57951. }
  57952. // Instances
  57953. var defines = [];
  57954. var attribs = [];
  57955. var fallbacks = new BABYLON.EffectFallbacks();
  57956. if (useInstances) {
  57957. defines.push("#define INSTANCES");
  57958. }
  57959. for (var index = 0; index < this._options.defines.length; index++) {
  57960. defines.push(this._options.defines[index]);
  57961. }
  57962. for (var index = 0; index < this._options.attributes.length; index++) {
  57963. attribs.push(this._options.attributes[index]);
  57964. }
  57965. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57966. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57967. defines.push("#define VERTEXCOLOR");
  57968. }
  57969. // Bones
  57970. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57971. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57972. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57973. if (mesh.numBoneInfluencers > 4) {
  57974. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57975. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57976. }
  57977. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57978. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57979. fallbacks.addCPUSkinningFallback(0, mesh);
  57980. if (this._options.uniforms.indexOf("mBones") === -1) {
  57981. this._options.uniforms.push("mBones");
  57982. }
  57983. }
  57984. else {
  57985. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57986. }
  57987. // Textures
  57988. for (var name in this._textures) {
  57989. if (!this._textures[name].isReady()) {
  57990. return false;
  57991. }
  57992. }
  57993. // Alpha test
  57994. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  57995. defines.push("#define ALPHATEST");
  57996. }
  57997. var previousEffect = this._effect;
  57998. var join = defines.join("\n");
  57999. this._effect = engine.createEffect(this._shaderPath, {
  58000. attributes: attribs,
  58001. uniformsNames: this._options.uniforms,
  58002. uniformBuffersNames: this._options.uniformBuffers,
  58003. samplers: this._options.samplers,
  58004. defines: join,
  58005. fallbacks: fallbacks,
  58006. onCompiled: this.onCompiled,
  58007. onError: this.onError
  58008. }, engine);
  58009. if (!this._effect.isReady()) {
  58010. return false;
  58011. }
  58012. if (previousEffect !== this._effect) {
  58013. scene.resetCachedMaterial();
  58014. }
  58015. this._renderId = scene.getRenderId();
  58016. return true;
  58017. };
  58018. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58019. var scene = this.getScene();
  58020. if (!this._effect) {
  58021. return;
  58022. }
  58023. if (this._options.uniforms.indexOf("world") !== -1) {
  58024. this._effect.setMatrix("world", world);
  58025. }
  58026. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58027. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58028. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58029. }
  58030. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58031. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58032. }
  58033. };
  58034. ShaderMaterial.prototype.bind = function (world, mesh) {
  58035. // Std values
  58036. this.bindOnlyWorldMatrix(world);
  58037. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58038. if (this._options.uniforms.indexOf("view") !== -1) {
  58039. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58040. }
  58041. if (this._options.uniforms.indexOf("projection") !== -1) {
  58042. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58043. }
  58044. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58045. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58046. }
  58047. // Bones
  58048. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58049. var name;
  58050. // Texture
  58051. for (name in this._textures) {
  58052. this._effect.setTexture(name, this._textures[name]);
  58053. }
  58054. // Texture arrays
  58055. for (name in this._textureArrays) {
  58056. this._effect.setTextureArray(name, this._textureArrays[name]);
  58057. }
  58058. // Int
  58059. for (name in this._ints) {
  58060. this._effect.setInt(name, this._ints[name]);
  58061. }
  58062. // Float
  58063. for (name in this._floats) {
  58064. this._effect.setFloat(name, this._floats[name]);
  58065. }
  58066. // Floats
  58067. for (name in this._floatsArrays) {
  58068. this._effect.setArray(name, this._floatsArrays[name]);
  58069. }
  58070. // Color3
  58071. for (name in this._colors3) {
  58072. this._effect.setColor3(name, this._colors3[name]);
  58073. }
  58074. for (name in this._colors3Arrays) {
  58075. this._effect.setArray3(name, this._colors3Arrays[name]);
  58076. }
  58077. // Color4
  58078. for (name in this._colors4) {
  58079. var color = this._colors4[name];
  58080. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58081. }
  58082. // Vector2
  58083. for (name in this._vectors2) {
  58084. this._effect.setVector2(name, this._vectors2[name]);
  58085. }
  58086. // Vector3
  58087. for (name in this._vectors3) {
  58088. this._effect.setVector3(name, this._vectors3[name]);
  58089. }
  58090. // Vector4
  58091. for (name in this._vectors4) {
  58092. this._effect.setVector4(name, this._vectors4[name]);
  58093. }
  58094. // Matrix
  58095. for (name in this._matrices) {
  58096. this._effect.setMatrix(name, this._matrices[name]);
  58097. }
  58098. // Matrix 3x3
  58099. for (name in this._matrices3x3) {
  58100. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58101. }
  58102. // Matrix 2x2
  58103. for (name in this._matrices2x2) {
  58104. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58105. }
  58106. // Vector2Array
  58107. for (name in this._vectors2Arrays) {
  58108. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58109. }
  58110. // Vector3Array
  58111. for (name in this._vectors3Arrays) {
  58112. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58113. }
  58114. }
  58115. this._afterBind(mesh);
  58116. };
  58117. ShaderMaterial.prototype.getActiveTextures = function () {
  58118. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58119. for (var name in this._textures) {
  58120. activeTextures.push(this._textures[name]);
  58121. }
  58122. for (var name in this._textureArrays) {
  58123. var array = this._textureArrays[name];
  58124. for (var index = 0; index < array.length; index++) {
  58125. activeTextures.push(array[index]);
  58126. }
  58127. }
  58128. return activeTextures;
  58129. };
  58130. ShaderMaterial.prototype.hasTexture = function (texture) {
  58131. if (_super.prototype.hasTexture.call(this, texture)) {
  58132. return true;
  58133. }
  58134. for (var name in this._textures) {
  58135. if (this._textures[name] === texture) {
  58136. return true;
  58137. }
  58138. }
  58139. for (var name in this._textureArrays) {
  58140. var array = this._textureArrays[name];
  58141. for (var index = 0; index < array.length; index++) {
  58142. if (array[index] === texture) {
  58143. return true;
  58144. }
  58145. }
  58146. }
  58147. return false;
  58148. };
  58149. ShaderMaterial.prototype.clone = function (name) {
  58150. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58151. return newShaderMaterial;
  58152. };
  58153. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58154. if (forceDisposeTextures) {
  58155. var name;
  58156. for (name in this._textures) {
  58157. this._textures[name].dispose();
  58158. }
  58159. for (name in this._textureArrays) {
  58160. var array = this._textureArrays[name];
  58161. for (var index = 0; index < array.length; index++) {
  58162. array[index].dispose();
  58163. }
  58164. }
  58165. }
  58166. this._textures = {};
  58167. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58168. };
  58169. ShaderMaterial.prototype.serialize = function () {
  58170. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58171. serializationObject.customType = "BABYLON.ShaderMaterial";
  58172. serializationObject.options = this._options;
  58173. serializationObject.shaderPath = this._shaderPath;
  58174. var name;
  58175. // Texture
  58176. serializationObject.textures = {};
  58177. for (name in this._textures) {
  58178. serializationObject.textures[name] = this._textures[name].serialize();
  58179. }
  58180. // Texture arrays
  58181. serializationObject.textureArrays = {};
  58182. for (name in this._textureArrays) {
  58183. serializationObject.textureArrays[name] = [];
  58184. var array = this._textureArrays[name];
  58185. for (var index = 0; index < array.length; index++) {
  58186. serializationObject.textureArrays[name].push(array[index].serialize());
  58187. }
  58188. }
  58189. // Float
  58190. serializationObject.floats = {};
  58191. for (name in this._floats) {
  58192. serializationObject.floats[name] = this._floats[name];
  58193. }
  58194. // Float s
  58195. serializationObject.FloatArrays = {};
  58196. for (name in this._floatsArrays) {
  58197. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58198. }
  58199. // Color3
  58200. serializationObject.colors3 = {};
  58201. for (name in this._colors3) {
  58202. serializationObject.colors3[name] = this._colors3[name].asArray();
  58203. }
  58204. // Color3 array
  58205. serializationObject.colors3Arrays = {};
  58206. for (name in this._colors3Arrays) {
  58207. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58208. }
  58209. // Color4
  58210. serializationObject.colors4 = {};
  58211. for (name in this._colors4) {
  58212. serializationObject.colors4[name] = this._colors4[name].asArray();
  58213. }
  58214. // Vector2
  58215. serializationObject.vectors2 = {};
  58216. for (name in this._vectors2) {
  58217. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58218. }
  58219. // Vector3
  58220. serializationObject.vectors3 = {};
  58221. for (name in this._vectors3) {
  58222. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58223. }
  58224. // Vector4
  58225. serializationObject.vectors4 = {};
  58226. for (name in this._vectors4) {
  58227. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58228. }
  58229. // Matrix
  58230. serializationObject.matrices = {};
  58231. for (name in this._matrices) {
  58232. serializationObject.matrices[name] = this._matrices[name].asArray();
  58233. }
  58234. // Matrix 3x3
  58235. serializationObject.matrices3x3 = {};
  58236. for (name in this._matrices3x3) {
  58237. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58238. }
  58239. // Matrix 2x2
  58240. serializationObject.matrices2x2 = {};
  58241. for (name in this._matrices2x2) {
  58242. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58243. }
  58244. // Vector2Array
  58245. serializationObject.vectors2Arrays = {};
  58246. for (name in this._vectors2Arrays) {
  58247. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58248. }
  58249. // Vector3Array
  58250. serializationObject.vectors3Arrays = {};
  58251. for (name in this._vectors3Arrays) {
  58252. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58253. }
  58254. return serializationObject;
  58255. };
  58256. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58257. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58258. var name;
  58259. // Texture
  58260. for (name in source.textures) {
  58261. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58262. }
  58263. // Texture arrays
  58264. for (name in source.textureArrays) {
  58265. var array = source.textureArrays[name];
  58266. var textureArray = new Array();
  58267. for (var index = 0; index < array.length; index++) {
  58268. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58269. }
  58270. material.setTextureArray(name, textureArray);
  58271. }
  58272. // Float
  58273. for (name in source.floats) {
  58274. material.setFloat(name, source.floats[name]);
  58275. }
  58276. // Float s
  58277. for (name in source.floatsArrays) {
  58278. material.setFloats(name, source.floatsArrays[name]);
  58279. }
  58280. // Color3
  58281. for (name in source.colors3) {
  58282. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58283. }
  58284. // Color3 arrays
  58285. for (name in source.colors3Arrays) {
  58286. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58287. if (i % 3 === 0) {
  58288. arr.push([num]);
  58289. }
  58290. else {
  58291. arr[arr.length - 1].push(num);
  58292. }
  58293. return arr;
  58294. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58295. material.setColor3Array(name, colors);
  58296. }
  58297. // Color4
  58298. for (name in source.colors4) {
  58299. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58300. }
  58301. // Vector2
  58302. for (name in source.vectors2) {
  58303. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58304. }
  58305. // Vector3
  58306. for (name in source.vectors3) {
  58307. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58308. }
  58309. // Vector4
  58310. for (name in source.vectors4) {
  58311. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58312. }
  58313. // Matrix
  58314. for (name in source.matrices) {
  58315. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58316. }
  58317. // Matrix 3x3
  58318. for (name in source.matrices3x3) {
  58319. material.setMatrix3x3(name, source.matrices3x3[name]);
  58320. }
  58321. // Matrix 2x2
  58322. for (name in source.matrices2x2) {
  58323. material.setMatrix2x2(name, source.matrices2x2[name]);
  58324. }
  58325. // Vector2Array
  58326. for (name in source.vectors2Arrays) {
  58327. material.setArray2(name, source.vectors2Arrays[name]);
  58328. }
  58329. // Vector3Array
  58330. for (name in source.vectors3Arrays) {
  58331. material.setArray3(name, source.vectors3Arrays[name]);
  58332. }
  58333. return material;
  58334. };
  58335. return ShaderMaterial;
  58336. }(BABYLON.Material));
  58337. BABYLON.ShaderMaterial = ShaderMaterial;
  58338. })(BABYLON || (BABYLON = {}));
  58339. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58340. var BABYLON;
  58341. (function (BABYLON) {
  58342. var GroundMesh = /** @class */ (function (_super) {
  58343. __extends(GroundMesh, _super);
  58344. function GroundMesh(name, scene) {
  58345. var _this = _super.call(this, name, scene) || this;
  58346. _this.generateOctree = false;
  58347. return _this;
  58348. }
  58349. GroundMesh.prototype.getClassName = function () {
  58350. return "GroundMesh";
  58351. };
  58352. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58353. get: function () {
  58354. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58355. },
  58356. enumerable: true,
  58357. configurable: true
  58358. });
  58359. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58360. get: function () {
  58361. return this._subdivisionsX;
  58362. },
  58363. enumerable: true,
  58364. configurable: true
  58365. });
  58366. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58367. get: function () {
  58368. return this._subdivisionsY;
  58369. },
  58370. enumerable: true,
  58371. configurable: true
  58372. });
  58373. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58374. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58375. this._subdivisionsX = chunksCount;
  58376. this._subdivisionsY = chunksCount;
  58377. this.subdivide(chunksCount);
  58378. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58379. };
  58380. /**
  58381. * Returns a height (y) value in the Worl system :
  58382. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58383. * Returns the ground y position if (x, z) are outside the ground surface.
  58384. */
  58385. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58386. var world = this.getWorldMatrix();
  58387. var invMat = BABYLON.Tmp.Matrix[5];
  58388. world.invertToRef(invMat);
  58389. var tmpVect = BABYLON.Tmp.Vector3[8];
  58390. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58391. x = tmpVect.x;
  58392. z = tmpVect.z;
  58393. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58394. return this.position.y;
  58395. }
  58396. if (!this._heightQuads || this._heightQuads.length == 0) {
  58397. this._initHeightQuads();
  58398. this._computeHeightQuads();
  58399. }
  58400. var facet = this._getFacetAt(x, z);
  58401. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58402. // return y in the World system
  58403. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58404. return tmpVect.y;
  58405. };
  58406. /**
  58407. * Returns a normalized vector (Vector3) orthogonal to the ground
  58408. * at the ground coordinates (x, z) expressed in the World system.
  58409. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58410. */
  58411. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58412. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58413. this.getNormalAtCoordinatesToRef(x, z, normal);
  58414. return normal;
  58415. };
  58416. /**
  58417. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58418. * at the ground coordinates (x, z) expressed in the World system.
  58419. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58420. * Returns the GroundMesh.
  58421. */
  58422. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58423. var world = this.getWorldMatrix();
  58424. var tmpMat = BABYLON.Tmp.Matrix[5];
  58425. world.invertToRef(tmpMat);
  58426. var tmpVect = BABYLON.Tmp.Vector3[8];
  58427. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58428. x = tmpVect.x;
  58429. z = tmpVect.z;
  58430. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58431. return this;
  58432. }
  58433. if (!this._heightQuads || this._heightQuads.length == 0) {
  58434. this._initHeightQuads();
  58435. this._computeHeightQuads();
  58436. }
  58437. var facet = this._getFacetAt(x, z);
  58438. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58439. return this;
  58440. };
  58441. /**
  58442. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58443. * if the ground has been updated.
  58444. * This can be used in the render loop.
  58445. * Returns the GroundMesh.
  58446. */
  58447. GroundMesh.prototype.updateCoordinateHeights = function () {
  58448. if (!this._heightQuads || this._heightQuads.length == 0) {
  58449. this._initHeightQuads();
  58450. }
  58451. this._computeHeightQuads();
  58452. return this;
  58453. };
  58454. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58455. GroundMesh.prototype._getFacetAt = function (x, z) {
  58456. // retrieve col and row from x, z coordinates in the ground local system
  58457. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58458. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58459. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58460. var facet;
  58461. if (z < quad.slope.x * x + quad.slope.y) {
  58462. facet = quad.facet1;
  58463. }
  58464. else {
  58465. facet = quad.facet2;
  58466. }
  58467. return facet;
  58468. };
  58469. // Creates and populates the heightMap array with "facet" elements :
  58470. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58471. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58472. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58473. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58474. // Returns the GroundMesh.
  58475. GroundMesh.prototype._initHeightQuads = function () {
  58476. var subdivisionsX = this._subdivisionsX;
  58477. var subdivisionsY = this._subdivisionsY;
  58478. this._heightQuads = new Array();
  58479. for (var row = 0; row < subdivisionsY; row++) {
  58480. for (var col = 0; col < subdivisionsX; col++) {
  58481. 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) };
  58482. this._heightQuads[row * subdivisionsX + col] = quad;
  58483. }
  58484. }
  58485. return this;
  58486. };
  58487. // Compute each quad element values and update the the heightMap array :
  58488. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58489. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58490. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58491. // Returns the GroundMesh.
  58492. GroundMesh.prototype._computeHeightQuads = function () {
  58493. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58494. if (!positions) {
  58495. return this;
  58496. }
  58497. var v1 = BABYLON.Tmp.Vector3[3];
  58498. var v2 = BABYLON.Tmp.Vector3[2];
  58499. var v3 = BABYLON.Tmp.Vector3[1];
  58500. var v4 = BABYLON.Tmp.Vector3[0];
  58501. var v1v2 = BABYLON.Tmp.Vector3[4];
  58502. var v1v3 = BABYLON.Tmp.Vector3[5];
  58503. var v1v4 = BABYLON.Tmp.Vector3[6];
  58504. var norm1 = BABYLON.Tmp.Vector3[7];
  58505. var norm2 = BABYLON.Tmp.Vector3[8];
  58506. var i = 0;
  58507. var j = 0;
  58508. var k = 0;
  58509. var cd = 0; // 2D slope coefficient : z = cd * x + h
  58510. var h = 0;
  58511. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  58512. var d2 = 0;
  58513. var subdivisionsX = this._subdivisionsX;
  58514. var subdivisionsY = this._subdivisionsY;
  58515. for (var row = 0; row < subdivisionsY; row++) {
  58516. for (var col = 0; col < subdivisionsX; col++) {
  58517. i = col * 3;
  58518. j = row * (subdivisionsX + 1) * 3;
  58519. k = (row + 1) * (subdivisionsX + 1) * 3;
  58520. v1.x = positions[j + i];
  58521. v1.y = positions[j + i + 1];
  58522. v1.z = positions[j + i + 2];
  58523. v2.x = positions[j + i + 3];
  58524. v2.y = positions[j + i + 4];
  58525. v2.z = positions[j + i + 5];
  58526. v3.x = positions[k + i];
  58527. v3.y = positions[k + i + 1];
  58528. v3.z = positions[k + i + 2];
  58529. v4.x = positions[k + i + 3];
  58530. v4.y = positions[k + i + 4];
  58531. v4.z = positions[k + i + 5];
  58532. // 2D slope V1V4
  58533. cd = (v4.z - v1.z) / (v4.x - v1.x);
  58534. h = v1.z - cd * v1.x; // v1 belongs to the slope
  58535. // facet equations :
  58536. // we compute each facet normal vector
  58537. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  58538. // we compute the value d by applying the equation to v1 which belongs to the plane
  58539. // then we store the facet equation in a Vector4
  58540. v2.subtractToRef(v1, v1v2);
  58541. v3.subtractToRef(v1, v1v3);
  58542. v4.subtractToRef(v1, v1v4);
  58543. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  58544. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  58545. norm1.normalize();
  58546. norm2.normalize();
  58547. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  58548. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  58549. var quad = this._heightQuads[row * subdivisionsX + col];
  58550. quad.slope.copyFromFloats(cd, h);
  58551. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  58552. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  58553. }
  58554. }
  58555. return this;
  58556. };
  58557. GroundMesh.prototype.serialize = function (serializationObject) {
  58558. _super.prototype.serialize.call(this, serializationObject);
  58559. serializationObject.subdivisionsX = this._subdivisionsX;
  58560. serializationObject.subdivisionsY = this._subdivisionsY;
  58561. serializationObject.minX = this._minX;
  58562. serializationObject.maxX = this._maxX;
  58563. serializationObject.minZ = this._minZ;
  58564. serializationObject.maxZ = this._maxZ;
  58565. serializationObject.width = this._width;
  58566. serializationObject.height = this._height;
  58567. };
  58568. GroundMesh.Parse = function (parsedMesh, scene) {
  58569. var result = new GroundMesh(parsedMesh.name, scene);
  58570. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  58571. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  58572. result._minX = parsedMesh.minX;
  58573. result._maxX = parsedMesh.maxX;
  58574. result._minZ = parsedMesh.minZ;
  58575. result._maxZ = parsedMesh.maxZ;
  58576. result._width = parsedMesh.width;
  58577. result._height = parsedMesh.height;
  58578. return result;
  58579. };
  58580. return GroundMesh;
  58581. }(BABYLON.Mesh));
  58582. BABYLON.GroundMesh = GroundMesh;
  58583. })(BABYLON || (BABYLON = {}));
  58584. //# sourceMappingURL=babylon.groundMesh.js.map
  58585. var BABYLON;
  58586. (function (BABYLON) {
  58587. /**
  58588. * Creates an instance based on a source mesh.
  58589. */
  58590. var InstancedMesh = /** @class */ (function (_super) {
  58591. __extends(InstancedMesh, _super);
  58592. function InstancedMesh(name, source) {
  58593. var _this = _super.call(this, name, source.getScene()) || this;
  58594. source.instances.push(_this);
  58595. _this._sourceMesh = source;
  58596. _this.position.copyFrom(source.position);
  58597. _this.rotation.copyFrom(source.rotation);
  58598. _this.scaling.copyFrom(source.scaling);
  58599. if (source.rotationQuaternion) {
  58600. _this.rotationQuaternion = source.rotationQuaternion.clone();
  58601. }
  58602. _this.infiniteDistance = source.infiniteDistance;
  58603. _this.setPivotMatrix(source.getPivotMatrix());
  58604. _this.refreshBoundingInfo();
  58605. _this._syncSubMeshes();
  58606. return _this;
  58607. }
  58608. /**
  58609. * Returns the string "InstancedMesh".
  58610. */
  58611. InstancedMesh.prototype.getClassName = function () {
  58612. return "InstancedMesh";
  58613. };
  58614. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  58615. // Methods
  58616. get: function () {
  58617. return this._sourceMesh.receiveShadows;
  58618. },
  58619. enumerable: true,
  58620. configurable: true
  58621. });
  58622. Object.defineProperty(InstancedMesh.prototype, "material", {
  58623. get: function () {
  58624. return this._sourceMesh.material;
  58625. },
  58626. enumerable: true,
  58627. configurable: true
  58628. });
  58629. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  58630. get: function () {
  58631. return this._sourceMesh.visibility;
  58632. },
  58633. enumerable: true,
  58634. configurable: true
  58635. });
  58636. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  58637. get: function () {
  58638. return this._sourceMesh.skeleton;
  58639. },
  58640. enumerable: true,
  58641. configurable: true
  58642. });
  58643. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  58644. get: function () {
  58645. return this._sourceMesh.renderingGroupId;
  58646. },
  58647. set: function (value) {
  58648. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  58649. return;
  58650. }
  58651. //no-op with warning
  58652. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  58653. },
  58654. enumerable: true,
  58655. configurable: true
  58656. });
  58657. /**
  58658. * Returns the total number of vertices (integer).
  58659. */
  58660. InstancedMesh.prototype.getTotalVertices = function () {
  58661. return this._sourceMesh.getTotalVertices();
  58662. };
  58663. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  58664. get: function () {
  58665. return this._sourceMesh;
  58666. },
  58667. enumerable: true,
  58668. configurable: true
  58669. });
  58670. /**
  58671. * Is this node ready to be used/rendered
  58672. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  58673. * @return {boolean} is it ready
  58674. */
  58675. InstancedMesh.prototype.isReady = function (completeCheck) {
  58676. if (completeCheck === void 0) { completeCheck = false; }
  58677. return this._sourceMesh.isReady(completeCheck, true);
  58678. };
  58679. /**
  58680. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  58681. */
  58682. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  58683. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  58684. };
  58685. /**
  58686. * Sets the vertex data of the mesh geometry for the requested `kind`.
  58687. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  58688. * The `data` are either a numeric array either a Float32Array.
  58689. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  58690. * 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).
  58691. * Note that a new underlying VertexBuffer object is created each call.
  58692. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58693. *
  58694. * Possible `kind` values :
  58695. * - BABYLON.VertexBuffer.PositionKind
  58696. * - BABYLON.VertexBuffer.UVKind
  58697. * - BABYLON.VertexBuffer.UV2Kind
  58698. * - BABYLON.VertexBuffer.UV3Kind
  58699. * - BABYLON.VertexBuffer.UV4Kind
  58700. * - BABYLON.VertexBuffer.UV5Kind
  58701. * - BABYLON.VertexBuffer.UV6Kind
  58702. * - BABYLON.VertexBuffer.ColorKind
  58703. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58704. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58705. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58706. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58707. *
  58708. * Returns the Mesh.
  58709. */
  58710. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58711. if (this.sourceMesh) {
  58712. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58713. }
  58714. return this.sourceMesh;
  58715. };
  58716. /**
  58717. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58718. * If the mesh has no geometry, it is simply returned as it is.
  58719. * The `data` are either a numeric array either a Float32Array.
  58720. * No new underlying VertexBuffer object is created.
  58721. * 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.
  58722. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58723. *
  58724. * Possible `kind` values :
  58725. * - BABYLON.VertexBuffer.PositionKind
  58726. * - BABYLON.VertexBuffer.UVKind
  58727. * - BABYLON.VertexBuffer.UV2Kind
  58728. * - BABYLON.VertexBuffer.UV3Kind
  58729. * - BABYLON.VertexBuffer.UV4Kind
  58730. * - BABYLON.VertexBuffer.UV5Kind
  58731. * - BABYLON.VertexBuffer.UV6Kind
  58732. * - BABYLON.VertexBuffer.ColorKind
  58733. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58734. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58735. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58736. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58737. *
  58738. * Returns the Mesh.
  58739. */
  58740. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58741. if (this.sourceMesh) {
  58742. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58743. }
  58744. return this.sourceMesh;
  58745. };
  58746. /**
  58747. * Sets the mesh indices.
  58748. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58749. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58750. * This method creates a new index buffer each call.
  58751. * Returns the Mesh.
  58752. */
  58753. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58754. if (totalVertices === void 0) { totalVertices = null; }
  58755. if (this.sourceMesh) {
  58756. this.sourceMesh.setIndices(indices, totalVertices);
  58757. }
  58758. return this.sourceMesh;
  58759. };
  58760. /**
  58761. * Boolean : True if the mesh owns the requested kind of data.
  58762. */
  58763. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58764. return this._sourceMesh.isVerticesDataPresent(kind);
  58765. };
  58766. /**
  58767. * Returns an array of indices (IndicesArray).
  58768. */
  58769. InstancedMesh.prototype.getIndices = function () {
  58770. return this._sourceMesh.getIndices();
  58771. };
  58772. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58773. get: function () {
  58774. return this._sourceMesh._positions;
  58775. },
  58776. enumerable: true,
  58777. configurable: true
  58778. });
  58779. /**
  58780. * Sets a new updated BoundingInfo to the mesh.
  58781. * Returns the mesh.
  58782. */
  58783. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58784. var meshBB = this._sourceMesh.getBoundingInfo();
  58785. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58786. this._updateBoundingInfo();
  58787. return this;
  58788. };
  58789. InstancedMesh.prototype._preActivate = function () {
  58790. if (this._currentLOD) {
  58791. this._currentLOD._preActivate();
  58792. }
  58793. return this;
  58794. };
  58795. InstancedMesh.prototype._activate = function (renderId) {
  58796. if (this._currentLOD) {
  58797. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58798. }
  58799. return this;
  58800. };
  58801. /**
  58802. * Returns the current associated LOD AbstractMesh.
  58803. */
  58804. InstancedMesh.prototype.getLOD = function (camera) {
  58805. if (!camera) {
  58806. return this;
  58807. }
  58808. var boundingInfo = this.getBoundingInfo();
  58809. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  58810. if (this._currentLOD === this.sourceMesh) {
  58811. return this;
  58812. }
  58813. return this._currentLOD;
  58814. };
  58815. InstancedMesh.prototype._syncSubMeshes = function () {
  58816. this.releaseSubMeshes();
  58817. if (this._sourceMesh.subMeshes) {
  58818. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  58819. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  58820. }
  58821. }
  58822. return this;
  58823. };
  58824. InstancedMesh.prototype._generatePointsArray = function () {
  58825. return this._sourceMesh._generatePointsArray();
  58826. };
  58827. /**
  58828. * Creates a new InstancedMesh from the current mesh.
  58829. * - name (string) : the cloned mesh name
  58830. * - newParent (optional Node) : the optional Node to parent the clone to.
  58831. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  58832. *
  58833. * Returns the clone.
  58834. */
  58835. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58836. var result = this._sourceMesh.createInstance(name);
  58837. // Deep copy
  58838. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  58839. // Bounding info
  58840. this.refreshBoundingInfo();
  58841. // Parent
  58842. if (newParent) {
  58843. result.parent = newParent;
  58844. }
  58845. if (!doNotCloneChildren) {
  58846. // Children
  58847. for (var index = 0; index < this.getScene().meshes.length; index++) {
  58848. var mesh = this.getScene().meshes[index];
  58849. if (mesh.parent === this) {
  58850. mesh.clone(mesh.name, result);
  58851. }
  58852. }
  58853. }
  58854. result.computeWorldMatrix(true);
  58855. return result;
  58856. };
  58857. /**
  58858. * Disposes the InstancedMesh.
  58859. * Returns nothing.
  58860. */
  58861. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  58862. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  58863. // Remove from mesh
  58864. var index = this._sourceMesh.instances.indexOf(this);
  58865. this._sourceMesh.instances.splice(index, 1);
  58866. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  58867. };
  58868. return InstancedMesh;
  58869. }(BABYLON.AbstractMesh));
  58870. BABYLON.InstancedMesh = InstancedMesh;
  58871. })(BABYLON || (BABYLON = {}));
  58872. //# sourceMappingURL=babylon.instancedMesh.js.map
  58873. var BABYLON;
  58874. (function (BABYLON) {
  58875. var LinesMesh = /** @class */ (function (_super) {
  58876. __extends(LinesMesh, _super);
  58877. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  58878. if (scene === void 0) { scene = null; }
  58879. if (parent === void 0) { parent = null; }
  58880. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  58881. _this.useVertexColor = useVertexColor;
  58882. _this.useVertexAlpha = useVertexAlpha;
  58883. _this.color = new BABYLON.Color3(1, 1, 1);
  58884. _this.alpha = 1;
  58885. if (source) {
  58886. _this.color = source.color.clone();
  58887. _this.alpha = source.alpha;
  58888. _this.useVertexColor = source.useVertexColor;
  58889. _this.useVertexAlpha = source.useVertexAlpha;
  58890. }
  58891. _this._intersectionThreshold = 0.1;
  58892. var defines = [];
  58893. var options = {
  58894. attributes: [BABYLON.VertexBuffer.PositionKind],
  58895. uniforms: ["world", "viewProjection"],
  58896. needAlphaBlending: true,
  58897. defines: defines
  58898. };
  58899. if (useVertexAlpha === false) {
  58900. options.needAlphaBlending = false;
  58901. }
  58902. if (!useVertexColor) {
  58903. options.uniforms.push("color");
  58904. }
  58905. else {
  58906. options.defines.push("#define VERTEXCOLOR");
  58907. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  58908. }
  58909. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  58910. return _this;
  58911. }
  58912. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  58913. /**
  58914. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58915. * This margin is expressed in world space coordinates, so its value may vary.
  58916. * Default value is 0.1
  58917. * @returns the intersection Threshold value.
  58918. */
  58919. get: function () {
  58920. return this._intersectionThreshold;
  58921. },
  58922. /**
  58923. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58924. * This margin is expressed in world space coordinates, so its value may vary.
  58925. * @param value the new threshold to apply
  58926. */
  58927. set: function (value) {
  58928. if (this._intersectionThreshold === value) {
  58929. return;
  58930. }
  58931. this._intersectionThreshold = value;
  58932. if (this.geometry) {
  58933. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  58934. }
  58935. },
  58936. enumerable: true,
  58937. configurable: true
  58938. });
  58939. /**
  58940. * Returns the string "LineMesh"
  58941. */
  58942. LinesMesh.prototype.getClassName = function () {
  58943. return "LinesMesh";
  58944. };
  58945. Object.defineProperty(LinesMesh.prototype, "material", {
  58946. /**
  58947. * @hidden
  58948. */
  58949. get: function () {
  58950. return this._colorShader;
  58951. },
  58952. /**
  58953. * @hidden
  58954. */
  58955. set: function (value) {
  58956. // Do nothing
  58957. },
  58958. enumerable: true,
  58959. configurable: true
  58960. });
  58961. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  58962. /**
  58963. * @hidden
  58964. */
  58965. get: function () {
  58966. return false;
  58967. },
  58968. enumerable: true,
  58969. configurable: true
  58970. });
  58971. LinesMesh.prototype.createInstance = function (name) {
  58972. throw new Error("LinesMeshes do not support createInstance.");
  58973. };
  58974. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  58975. if (!this._geometry) {
  58976. return this;
  58977. }
  58978. // VBOs
  58979. this._geometry._bind(this._colorShader.getEffect());
  58980. // Color
  58981. if (!this.useVertexColor) {
  58982. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  58983. }
  58984. return this;
  58985. };
  58986. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  58987. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  58988. return this;
  58989. }
  58990. var engine = this.getScene().getEngine();
  58991. // Draw order
  58992. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  58993. return this;
  58994. };
  58995. LinesMesh.prototype.dispose = function (doNotRecurse) {
  58996. this._colorShader.dispose();
  58997. _super.prototype.dispose.call(this, doNotRecurse);
  58998. };
  58999. /**
  59000. * Returns a new LineMesh object cloned from the current one.
  59001. */
  59002. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59003. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59004. };
  59005. return LinesMesh;
  59006. }(BABYLON.Mesh));
  59007. BABYLON.LinesMesh = LinesMesh;
  59008. })(BABYLON || (BABYLON = {}));
  59009. //# sourceMappingURL=babylon.linesMesh.js.map
  59010. var BABYLON;
  59011. (function (BABYLON) {
  59012. /**
  59013. * This class implement a typical dictionary using a string as key and the generic type T as value.
  59014. * The underlying implementation relies on an associative array to ensure the best performances.
  59015. * The value can be anything including 'null' but except 'undefined'
  59016. */
  59017. var StringDictionary = /** @class */ (function () {
  59018. function StringDictionary() {
  59019. this._count = 0;
  59020. this._data = {};
  59021. }
  59022. /**
  59023. * This will clear this dictionary and copy the content from the 'source' one.
  59024. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  59025. * @param source the dictionary to take the content from and copy to this dictionary
  59026. */
  59027. StringDictionary.prototype.copyFrom = function (source) {
  59028. var _this = this;
  59029. this.clear();
  59030. source.forEach(function (t, v) { return _this.add(t, v); });
  59031. };
  59032. /**
  59033. * Get a value based from its key
  59034. * @param key the given key to get the matching value from
  59035. * @return the value if found, otherwise undefined is returned
  59036. */
  59037. StringDictionary.prototype.get = function (key) {
  59038. var val = this._data[key];
  59039. if (val !== undefined) {
  59040. return val;
  59041. }
  59042. return undefined;
  59043. };
  59044. /**
  59045. * Get a value from its key or add it if it doesn't exist.
  59046. * This method will ensure you that a given key/data will be present in the dictionary.
  59047. * @param key the given key to get the matching value from
  59048. * @param factory the factory that will create the value if the key is not present in the dictionary.
  59049. * The factory will only be invoked if there's no data for the given key.
  59050. * @return the value corresponding to the key.
  59051. */
  59052. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  59053. var val = this.get(key);
  59054. if (val !== undefined) {
  59055. return val;
  59056. }
  59057. val = factory(key);
  59058. if (val) {
  59059. this.add(key, val);
  59060. }
  59061. return val;
  59062. };
  59063. /**
  59064. * Get a value from its key if present in the dictionary otherwise add it
  59065. * @param key the key to get the value from
  59066. * @param val if there's no such key/value pair in the dictionary add it with this value
  59067. * @return the value corresponding to the key
  59068. */
  59069. StringDictionary.prototype.getOrAdd = function (key, val) {
  59070. var curVal = this.get(key);
  59071. if (curVal !== undefined) {
  59072. return curVal;
  59073. }
  59074. this.add(key, val);
  59075. return val;
  59076. };
  59077. /**
  59078. * Check if there's a given key in the dictionary
  59079. * @param key the key to check for
  59080. * @return true if the key is present, false otherwise
  59081. */
  59082. StringDictionary.prototype.contains = function (key) {
  59083. return this._data[key] !== undefined;
  59084. };
  59085. /**
  59086. * Add a new key and its corresponding value
  59087. * @param key the key to add
  59088. * @param value the value corresponding to the key
  59089. * @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
  59090. */
  59091. StringDictionary.prototype.add = function (key, value) {
  59092. if (this._data[key] !== undefined) {
  59093. return false;
  59094. }
  59095. this._data[key] = value;
  59096. ++this._count;
  59097. return true;
  59098. };
  59099. StringDictionary.prototype.set = function (key, value) {
  59100. if (this._data[key] === undefined) {
  59101. return false;
  59102. }
  59103. this._data[key] = value;
  59104. return true;
  59105. };
  59106. /**
  59107. * Get the element of the given key and remove it from the dictionary
  59108. * @param key
  59109. */
  59110. StringDictionary.prototype.getAndRemove = function (key) {
  59111. var val = this.get(key);
  59112. if (val !== undefined) {
  59113. delete this._data[key];
  59114. --this._count;
  59115. return val;
  59116. }
  59117. return null;
  59118. };
  59119. /**
  59120. * Remove a key/value from the dictionary.
  59121. * @param key the key to remove
  59122. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  59123. */
  59124. StringDictionary.prototype.remove = function (key) {
  59125. if (this.contains(key)) {
  59126. delete this._data[key];
  59127. --this._count;
  59128. return true;
  59129. }
  59130. return false;
  59131. };
  59132. /**
  59133. * Clear the whole content of the dictionary
  59134. */
  59135. StringDictionary.prototype.clear = function () {
  59136. this._data = {};
  59137. this._count = 0;
  59138. };
  59139. Object.defineProperty(StringDictionary.prototype, "count", {
  59140. get: function () {
  59141. return this._count;
  59142. },
  59143. enumerable: true,
  59144. configurable: true
  59145. });
  59146. /**
  59147. * Execute a callback on each key/val of the dictionary.
  59148. * Note that you can remove any element in this dictionary in the callback implementation
  59149. * @param callback the callback to execute on a given key/value pair
  59150. */
  59151. StringDictionary.prototype.forEach = function (callback) {
  59152. for (var cur in this._data) {
  59153. var val = this._data[cur];
  59154. callback(cur, val);
  59155. }
  59156. };
  59157. /**
  59158. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  59159. * If the callback returns null or undefined the method will iterate to the next key/value pair
  59160. * Note that you can remove any element in this dictionary in the callback implementation
  59161. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  59162. */
  59163. StringDictionary.prototype.first = function (callback) {
  59164. for (var cur in this._data) {
  59165. var val = this._data[cur];
  59166. var res = callback(cur, val);
  59167. if (res) {
  59168. return res;
  59169. }
  59170. }
  59171. return null;
  59172. };
  59173. return StringDictionary;
  59174. }());
  59175. BABYLON.StringDictionary = StringDictionary;
  59176. })(BABYLON || (BABYLON = {}));
  59177. //# sourceMappingURL=babylon.stringDictionary.js.map
  59178. var BABYLON;
  59179. (function (BABYLON) {
  59180. var Debug;
  59181. (function (Debug) {
  59182. /**
  59183. * Class used to render a debug view of a given skeleton
  59184. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  59185. */
  59186. var SkeletonViewer = /** @class */ (function () {
  59187. /**
  59188. * Creates a new SkeletonViewer
  59189. * @param skeleton defines the skeleton to render
  59190. * @param mesh defines the mesh attached to the skeleton
  59191. * @param scene defines the hosting scene
  59192. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  59193. * @param renderingGroupId defines the rendering group id to use with the viewer
  59194. */
  59195. function SkeletonViewer(
  59196. /** defines the skeleton to render */
  59197. skeleton,
  59198. /** defines the mesh attached to the skeleton */
  59199. mesh, scene,
  59200. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  59201. autoUpdateBonesMatrices,
  59202. /** defines the rendering group id to use with the viewer */
  59203. renderingGroupId) {
  59204. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59205. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59206. this.skeleton = skeleton;
  59207. this.mesh = mesh;
  59208. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59209. this.renderingGroupId = renderingGroupId;
  59210. /** Gets or sets the color used to render the skeleton */
  59211. this.color = BABYLON.Color3.White();
  59212. this._debugLines = new Array();
  59213. this._isEnabled = false;
  59214. this._scene = scene;
  59215. this.update();
  59216. this._renderFunction = this.update.bind(this);
  59217. }
  59218. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59219. get: function () {
  59220. return this._isEnabled;
  59221. },
  59222. /** Gets or sets a boolean indicating if the viewer is enabled */
  59223. set: function (value) {
  59224. if (this._isEnabled === value) {
  59225. return;
  59226. }
  59227. this._isEnabled = value;
  59228. if (value) {
  59229. this._scene.registerBeforeRender(this._renderFunction);
  59230. }
  59231. else {
  59232. this._scene.unregisterBeforeRender(this._renderFunction);
  59233. }
  59234. },
  59235. enumerable: true,
  59236. configurable: true
  59237. });
  59238. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59239. if (x === void 0) { x = 0; }
  59240. if (y === void 0) { y = 0; }
  59241. if (z === void 0) { z = 0; }
  59242. var tmat = BABYLON.Tmp.Matrix[0];
  59243. var parentBone = bone.getParent();
  59244. tmat.copyFrom(bone.getLocalMatrix());
  59245. if (x !== 0 || y !== 0 || z !== 0) {
  59246. var tmat2 = BABYLON.Tmp.Matrix[1];
  59247. BABYLON.Matrix.IdentityToRef(tmat2);
  59248. tmat2.m[12] = x;
  59249. tmat2.m[13] = y;
  59250. tmat2.m[14] = z;
  59251. tmat2.multiplyToRef(tmat, tmat);
  59252. }
  59253. if (parentBone) {
  59254. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59255. }
  59256. tmat.multiplyToRef(meshMat, tmat);
  59257. position.x = tmat.m[12];
  59258. position.y = tmat.m[13];
  59259. position.z = tmat.m[14];
  59260. };
  59261. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59262. var len = bones.length;
  59263. var meshPos = this.mesh.position;
  59264. for (var i = 0; i < len; i++) {
  59265. var bone = bones[i];
  59266. var points = this._debugLines[i];
  59267. if (!points) {
  59268. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59269. this._debugLines[i] = points;
  59270. }
  59271. this._getBonePosition(points[0], bone, meshMat);
  59272. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59273. points[0].subtractInPlace(meshPos);
  59274. points[1].subtractInPlace(meshPos);
  59275. }
  59276. };
  59277. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59278. var len = bones.length;
  59279. var boneNum = 0;
  59280. var meshPos = this.mesh.position;
  59281. for (var i = len - 1; i >= 0; i--) {
  59282. var childBone = bones[i];
  59283. var parentBone = childBone.getParent();
  59284. if (!parentBone) {
  59285. continue;
  59286. }
  59287. var points = this._debugLines[boneNum];
  59288. if (!points) {
  59289. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59290. this._debugLines[boneNum] = points;
  59291. }
  59292. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  59293. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  59294. points[0].subtractInPlace(meshPos);
  59295. points[1].subtractInPlace(meshPos);
  59296. boneNum++;
  59297. }
  59298. };
  59299. /** Update the viewer to sync with current skeleton state */
  59300. SkeletonViewer.prototype.update = function () {
  59301. if (this.autoUpdateBonesMatrices) {
  59302. this.skeleton.computeAbsoluteTransforms();
  59303. }
  59304. if (this.skeleton.bones[0].length === undefined) {
  59305. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59306. }
  59307. else {
  59308. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59309. }
  59310. if (!this._debugMesh) {
  59311. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  59312. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59313. }
  59314. else {
  59315. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59316. }
  59317. this._debugMesh.position.copyFrom(this.mesh.position);
  59318. this._debugMesh.color = this.color;
  59319. };
  59320. /** Release associated resources */
  59321. SkeletonViewer.prototype.dispose = function () {
  59322. if (this._debugMesh) {
  59323. this.isEnabled = false;
  59324. this._debugMesh.dispose();
  59325. this._debugMesh = null;
  59326. }
  59327. };
  59328. return SkeletonViewer;
  59329. }());
  59330. Debug.SkeletonViewer = SkeletonViewer;
  59331. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59332. })(BABYLON || (BABYLON = {}));
  59333. //# sourceMappingURL=babylon.skeletonViewer.js.map
  59334. /**
  59335. * Module Debug contains the (visual) components to debug a scene correctly
  59336. */
  59337. var BABYLON;
  59338. (function (BABYLON) {
  59339. var Debug;
  59340. (function (Debug) {
  59341. /**
  59342. * The Axes viewer will show 3 axes in a specific point in space
  59343. */
  59344. var AxesViewer = /** @class */ (function () {
  59345. /**
  59346. * Creates a new AxesViewer
  59347. * @param scene defines the hosting scene
  59348. * @param scaleLines defines a number used to scale line length (1 by default)
  59349. */
  59350. function AxesViewer(scene, scaleLines) {
  59351. if (scaleLines === void 0) { scaleLines = 1; }
  59352. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59353. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59354. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59355. /**
  59356. * Gets or sets a number used to scale line length
  59357. */
  59358. this.scaleLines = 1;
  59359. this.scaleLines = scaleLines;
  59360. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  59361. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  59362. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  59363. this._xmesh.renderingGroupId = 2;
  59364. this._ymesh.renderingGroupId = 2;
  59365. this._zmesh.renderingGroupId = 2;
  59366. this._xmesh.material.checkReadyOnlyOnce = true;
  59367. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  59368. this._ymesh.material.checkReadyOnlyOnce = true;
  59369. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  59370. this._zmesh.material.checkReadyOnlyOnce = true;
  59371. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  59372. this.scene = scene;
  59373. }
  59374. /**
  59375. * Force the viewer to update
  59376. * @param position defines the position of the viewer
  59377. * @param xaxis defines the x axis of the viewer
  59378. * @param yaxis defines the y axis of the viewer
  59379. * @param zaxis defines the z axis of the viewer
  59380. */
  59381. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  59382. var scaleLines = this.scaleLines;
  59383. if (this._xmesh) {
  59384. this._xmesh.position.copyFrom(position);
  59385. }
  59386. if (this._ymesh) {
  59387. this._ymesh.position.copyFrom(position);
  59388. }
  59389. if (this._zmesh) {
  59390. this._zmesh.position.copyFrom(position);
  59391. }
  59392. var point2 = this._xline[1];
  59393. point2.x = xaxis.x * scaleLines;
  59394. point2.y = xaxis.y * scaleLines;
  59395. point2.z = xaxis.z * scaleLines;
  59396. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  59397. point2 = this._yline[1];
  59398. point2.x = yaxis.x * scaleLines;
  59399. point2.y = yaxis.y * scaleLines;
  59400. point2.z = yaxis.z * scaleLines;
  59401. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  59402. point2 = this._zline[1];
  59403. point2.x = zaxis.x * scaleLines;
  59404. point2.y = zaxis.y * scaleLines;
  59405. point2.z = zaxis.z * scaleLines;
  59406. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  59407. };
  59408. /** Releases resources */
  59409. AxesViewer.prototype.dispose = function () {
  59410. if (this._xmesh) {
  59411. this._xmesh.dispose();
  59412. }
  59413. if (this._ymesh) {
  59414. this._ymesh.dispose();
  59415. }
  59416. if (this._zmesh) {
  59417. this._zmesh.dispose();
  59418. }
  59419. this._xmesh = null;
  59420. this._ymesh = null;
  59421. this._zmesh = null;
  59422. this.scene = null;
  59423. };
  59424. return AxesViewer;
  59425. }());
  59426. Debug.AxesViewer = AxesViewer;
  59427. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59428. })(BABYLON || (BABYLON = {}));
  59429. //# sourceMappingURL=babylon.axesViewer.js.map
  59430. var BABYLON;
  59431. (function (BABYLON) {
  59432. var Debug;
  59433. (function (Debug) {
  59434. /**
  59435. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  59436. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  59437. */
  59438. var BoneAxesViewer = /** @class */ (function (_super) {
  59439. __extends(BoneAxesViewer, _super);
  59440. /**
  59441. * Creates a new BoneAxesViewer
  59442. * @param scene defines the hosting scene
  59443. * @param bone defines the target bone
  59444. * @param mesh defines the target mesh
  59445. * @param scaleLines defines a scaling factor for line length (1 by default)
  59446. */
  59447. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  59448. if (scaleLines === void 0) { scaleLines = 1; }
  59449. var _this = _super.call(this, scene, scaleLines) || this;
  59450. /** Gets current position */
  59451. _this.pos = BABYLON.Vector3.Zero();
  59452. /** Gets direction of X axis */
  59453. _this.xaxis = BABYLON.Vector3.Zero();
  59454. /** Gets direction of Y axis */
  59455. _this.yaxis = BABYLON.Vector3.Zero();
  59456. /** Gets direction of Z axis */
  59457. _this.zaxis = BABYLON.Vector3.Zero();
  59458. _this.mesh = mesh;
  59459. _this.bone = bone;
  59460. return _this;
  59461. }
  59462. /**
  59463. * Force the viewer to update
  59464. */
  59465. BoneAxesViewer.prototype.update = function () {
  59466. if (!this.mesh || !this.bone) {
  59467. return;
  59468. }
  59469. var bone = this.bone;
  59470. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  59471. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  59472. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  59473. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  59474. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  59475. };
  59476. /** Releases resources */
  59477. BoneAxesViewer.prototype.dispose = function () {
  59478. if (this.mesh) {
  59479. this.mesh = null;
  59480. this.bone = null;
  59481. _super.prototype.dispose.call(this);
  59482. }
  59483. };
  59484. return BoneAxesViewer;
  59485. }(Debug.AxesViewer));
  59486. Debug.BoneAxesViewer = BoneAxesViewer;
  59487. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59488. })(BABYLON || (BABYLON = {}));
  59489. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  59490. var BABYLON;
  59491. (function (BABYLON) {
  59492. var RayHelper = /** @class */ (function () {
  59493. function RayHelper(ray) {
  59494. this.ray = ray;
  59495. }
  59496. RayHelper.CreateAndShow = function (ray, scene, color) {
  59497. var helper = new RayHelper(ray);
  59498. helper.show(scene, color);
  59499. return helper;
  59500. };
  59501. RayHelper.prototype.show = function (scene, color) {
  59502. if (!this._renderFunction && this.ray) {
  59503. var ray = this.ray;
  59504. this._renderFunction = this._render.bind(this);
  59505. this._scene = scene;
  59506. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  59507. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  59508. if (this._renderFunction) {
  59509. this._scene.registerBeforeRender(this._renderFunction);
  59510. }
  59511. }
  59512. if (color && this._renderLine) {
  59513. this._renderLine.color.copyFrom(color);
  59514. }
  59515. };
  59516. RayHelper.prototype.hide = function () {
  59517. if (this._renderFunction && this._scene) {
  59518. this._scene.unregisterBeforeRender(this._renderFunction);
  59519. this._scene = null;
  59520. this._renderFunction = null;
  59521. if (this._renderLine) {
  59522. this._renderLine.dispose();
  59523. this._renderLine = null;
  59524. }
  59525. this._renderPoints = [];
  59526. }
  59527. };
  59528. RayHelper.prototype._render = function () {
  59529. var ray = this.ray;
  59530. if (!ray) {
  59531. return;
  59532. }
  59533. var point = this._renderPoints[1];
  59534. var len = Math.min(ray.length, 1000000);
  59535. point.copyFrom(ray.direction);
  59536. point.scaleInPlace(len);
  59537. point.addInPlace(ray.origin);
  59538. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  59539. };
  59540. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  59541. this._attachedToMesh = mesh;
  59542. var ray = this.ray;
  59543. if (!ray) {
  59544. return;
  59545. }
  59546. if (!ray.direction) {
  59547. ray.direction = BABYLON.Vector3.Zero();
  59548. }
  59549. if (!ray.origin) {
  59550. ray.origin = BABYLON.Vector3.Zero();
  59551. }
  59552. if (length) {
  59553. ray.length = length;
  59554. }
  59555. if (!meshSpaceOrigin) {
  59556. meshSpaceOrigin = BABYLON.Vector3.Zero();
  59557. }
  59558. if (!meshSpaceDirection) {
  59559. // -1 so that this will work with Mesh.lookAt
  59560. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  59561. }
  59562. if (!this._meshSpaceDirection) {
  59563. this._meshSpaceDirection = meshSpaceDirection.clone();
  59564. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  59565. }
  59566. else {
  59567. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  59568. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  59569. }
  59570. if (!this._updateToMeshFunction) {
  59571. this._updateToMeshFunction = this._updateToMesh.bind(this);
  59572. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  59573. }
  59574. this._updateToMesh();
  59575. };
  59576. RayHelper.prototype.detachFromMesh = function () {
  59577. if (this._attachedToMesh) {
  59578. if (this._updateToMeshFunction) {
  59579. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  59580. }
  59581. this._attachedToMesh = null;
  59582. this._updateToMeshFunction = null;
  59583. }
  59584. };
  59585. RayHelper.prototype._updateToMesh = function () {
  59586. var ray = this.ray;
  59587. if (!this._attachedToMesh || !ray) {
  59588. return;
  59589. }
  59590. if (this._attachedToMesh._isDisposed) {
  59591. this.detachFromMesh();
  59592. return;
  59593. }
  59594. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  59595. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  59596. };
  59597. RayHelper.prototype.dispose = function () {
  59598. this.hide();
  59599. this.detachFromMesh();
  59600. this.ray = null;
  59601. };
  59602. return RayHelper;
  59603. }());
  59604. BABYLON.RayHelper = RayHelper;
  59605. })(BABYLON || (BABYLON = {}));
  59606. //# sourceMappingURL=babylon.rayHelper.js.map
  59607. var BABYLON;
  59608. (function (BABYLON) {
  59609. // load the inspector using require, if not present in the global namespace.
  59610. var DebugLayer = /** @class */ (function () {
  59611. function DebugLayer(scene) {
  59612. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  59613. this.onPropertyChangedObservable = new BABYLON.Observable();
  59614. this._scene = scene;
  59615. }
  59616. /** Creates the inspector window. */
  59617. DebugLayer.prototype._createInspector = function (config) {
  59618. if (config === void 0) { config = {}; }
  59619. var popup = config.popup || false;
  59620. var initialTab = config.initialTab || 0;
  59621. var parentElement = config.parentElement || null;
  59622. if (!this._inspector) {
  59623. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  59624. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  59625. } // else nothing to do as instance is already created
  59626. };
  59627. DebugLayer.prototype.isVisible = function () {
  59628. if (!this._inspector) {
  59629. return false;
  59630. }
  59631. return true;
  59632. };
  59633. DebugLayer.prototype.hide = function () {
  59634. if (this._inspector) {
  59635. try {
  59636. this._inspector.dispose();
  59637. }
  59638. catch (e) {
  59639. // If the inspector has been removed directly from the inspector tool
  59640. }
  59641. this.onPropertyChangedObservable.clear();
  59642. this._inspector = null;
  59643. }
  59644. };
  59645. /**
  59646. *
  59647. * Launch the debugLayer.
  59648. *
  59649. * initialTab:
  59650. * | Value | Tab Name |
  59651. * | --- | --- |
  59652. * | 0 | Scene |
  59653. * | 1 | Console |
  59654. * | 2 | Stats |
  59655. * | 3 | Textures |
  59656. * | 4 | Mesh |
  59657. * | 5 | Light |
  59658. * | 6 | Material |
  59659. * | 7 | GLTF |
  59660. * | 8 | GUI |
  59661. * | 9 | Physics |
  59662. * | 10 | Camera |
  59663. * | 11 | Audio |
  59664. *
  59665. */
  59666. DebugLayer.prototype.show = function (config) {
  59667. if (config === void 0) { config = {}; }
  59668. if (typeof this.BJSINSPECTOR == 'undefined') {
  59669. // Load inspector and add it to the DOM
  59670. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  59671. }
  59672. else {
  59673. // Otherwise creates the inspector
  59674. this._createInspector(config);
  59675. }
  59676. };
  59677. /**
  59678. * Gets the active tab
  59679. * @return the index of the active tab or -1 if the inspector is hidden
  59680. */
  59681. DebugLayer.prototype.getActiveTab = function () {
  59682. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  59683. };
  59684. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  59685. return DebugLayer;
  59686. }());
  59687. BABYLON.DebugLayer = DebugLayer;
  59688. })(BABYLON || (BABYLON = {}));
  59689. //# sourceMappingURL=babylon.debugLayer.js.map
  59690. var BABYLON;
  59691. (function (BABYLON) {
  59692. var Debug;
  59693. (function (Debug) {
  59694. /**
  59695. * Used to show the physics impostor around the specific mesh
  59696. */
  59697. var PhysicsViewer = /** @class */ (function () {
  59698. /**
  59699. * Creates a new PhysicsViewer
  59700. * @param scene defines the hosting scene
  59701. */
  59702. function PhysicsViewer(scene) {
  59703. /** @hidden */
  59704. this._impostors = [];
  59705. /** @hidden */
  59706. this._meshes = [];
  59707. /** @hidden */
  59708. this._numMeshes = 0;
  59709. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59710. var physicEngine = this._scene.getPhysicsEngine();
  59711. if (physicEngine) {
  59712. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  59713. }
  59714. }
  59715. /** @hidden */
  59716. PhysicsViewer.prototype._updateDebugMeshes = function () {
  59717. var plugin = this._physicsEnginePlugin;
  59718. for (var i = 0; i < this._numMeshes; i++) {
  59719. var impostor = this._impostors[i];
  59720. if (!impostor) {
  59721. continue;
  59722. }
  59723. if (impostor.isDisposed) {
  59724. this.hideImpostor(this._impostors[i--]);
  59725. }
  59726. else {
  59727. var mesh = this._meshes[i];
  59728. if (mesh && plugin) {
  59729. plugin.syncMeshWithImpostor(mesh, impostor);
  59730. }
  59731. }
  59732. }
  59733. };
  59734. /**
  59735. * Renders a specified physic impostor
  59736. * @param impostor defines the impostor to render
  59737. */
  59738. PhysicsViewer.prototype.showImpostor = function (impostor) {
  59739. if (!this._scene) {
  59740. return;
  59741. }
  59742. for (var i = 0; i < this._numMeshes; i++) {
  59743. if (this._impostors[i] == impostor) {
  59744. return;
  59745. }
  59746. }
  59747. var debugMesh = this._getDebugMesh(impostor, this._scene);
  59748. if (debugMesh) {
  59749. this._impostors[this._numMeshes] = impostor;
  59750. this._meshes[this._numMeshes] = debugMesh;
  59751. if (this._numMeshes === 0) {
  59752. this._renderFunction = this._updateDebugMeshes.bind(this);
  59753. this._scene.registerBeforeRender(this._renderFunction);
  59754. }
  59755. this._numMeshes++;
  59756. }
  59757. };
  59758. /**
  59759. * Hides a specified physic impostor
  59760. * @param impostor defines the impostor to hide
  59761. */
  59762. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  59763. if (!impostor || !this._scene) {
  59764. return;
  59765. }
  59766. var removed = false;
  59767. for (var i = 0; i < this._numMeshes; i++) {
  59768. if (this._impostors[i] == impostor) {
  59769. var mesh = this._meshes[i];
  59770. if (!mesh) {
  59771. continue;
  59772. }
  59773. this._scene.removeMesh(mesh);
  59774. mesh.dispose();
  59775. this._numMeshes--;
  59776. if (this._numMeshes > 0) {
  59777. this._meshes[i] = this._meshes[this._numMeshes];
  59778. this._impostors[i] = this._impostors[this._numMeshes];
  59779. this._meshes[this._numMeshes] = null;
  59780. this._impostors[this._numMeshes] = null;
  59781. }
  59782. else {
  59783. this._meshes[0] = null;
  59784. this._impostors[0] = null;
  59785. }
  59786. removed = true;
  59787. break;
  59788. }
  59789. }
  59790. if (removed && this._numMeshes === 0) {
  59791. this._scene.unregisterBeforeRender(this._renderFunction);
  59792. }
  59793. };
  59794. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  59795. if (!this._debugMaterial) {
  59796. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59797. this._debugMaterial.wireframe = true;
  59798. }
  59799. return this._debugMaterial;
  59800. };
  59801. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  59802. if (!this._debugBoxMesh) {
  59803. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59804. this._debugBoxMesh.renderingGroupId = 1;
  59805. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59806. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59807. scene.removeMesh(this._debugBoxMesh);
  59808. }
  59809. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59810. };
  59811. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  59812. if (!this._debugSphereMesh) {
  59813. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59814. this._debugSphereMesh.renderingGroupId = 1;
  59815. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59816. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59817. scene.removeMesh(this._debugSphereMesh);
  59818. }
  59819. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59820. };
  59821. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  59822. var mesh = null;
  59823. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  59824. mesh = this._getDebugBoxMesh(scene);
  59825. impostor.getBoxSizeToRef(mesh.scaling);
  59826. }
  59827. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  59828. mesh = this._getDebugSphereMesh(scene);
  59829. var radius = impostor.getRadius();
  59830. mesh.scaling.x = radius * 2;
  59831. mesh.scaling.y = radius * 2;
  59832. mesh.scaling.z = radius * 2;
  59833. }
  59834. return mesh;
  59835. };
  59836. /** Releases all resources */
  59837. PhysicsViewer.prototype.dispose = function () {
  59838. for (var i = 0; i < this._numMeshes; i++) {
  59839. this.hideImpostor(this._impostors[i]);
  59840. }
  59841. if (this._debugBoxMesh) {
  59842. this._debugBoxMesh.dispose();
  59843. }
  59844. if (this._debugSphereMesh) {
  59845. this._debugSphereMesh.dispose();
  59846. }
  59847. if (this._debugMaterial) {
  59848. this._debugMaterial.dispose();
  59849. }
  59850. this._impostors.length = 0;
  59851. this._scene = null;
  59852. this._physicsEnginePlugin = null;
  59853. };
  59854. return PhysicsViewer;
  59855. }());
  59856. Debug.PhysicsViewer = PhysicsViewer;
  59857. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59858. })(BABYLON || (BABYLON = {}));
  59859. //# sourceMappingURL=babylon.physicsViewer.js.map
  59860. var BABYLON;
  59861. (function (BABYLON) {
  59862. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  59863. get: function () {
  59864. return this._forceShowBoundingBoxes || false;
  59865. },
  59866. set: function (value) {
  59867. this._forceShowBoundingBoxes = value;
  59868. // Lazyly creates a BB renderer if needed.
  59869. if (value) {
  59870. this.getBoundingBoxRenderer();
  59871. }
  59872. },
  59873. enumerable: true,
  59874. configurable: true
  59875. });
  59876. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  59877. if (!this._boundingBoxRenderer) {
  59878. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  59879. }
  59880. return this._boundingBoxRenderer;
  59881. };
  59882. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  59883. get: function () {
  59884. return this._showBoundingBox || false;
  59885. },
  59886. set: function (value) {
  59887. this._showBoundingBox = value;
  59888. // Lazyly creates a BB renderer if needed.
  59889. if (value) {
  59890. this.getScene().getBoundingBoxRenderer();
  59891. }
  59892. },
  59893. enumerable: true,
  59894. configurable: true
  59895. });
  59896. var BoundingBoxRenderer = /** @class */ (function () {
  59897. function BoundingBoxRenderer(scene) {
  59898. /**
  59899. * The component name helpfull to identify the component in the list of scene components.
  59900. */
  59901. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  59902. this.frontColor = new BABYLON.Color3(1, 1, 1);
  59903. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  59904. this.showBackLines = true;
  59905. this.renderList = new BABYLON.SmartArray(32);
  59906. this._vertexBuffers = {};
  59907. this.scene = scene;
  59908. scene._addComponent(this);
  59909. }
  59910. /**
  59911. * Registers the component in a given scene
  59912. */
  59913. BoundingBoxRenderer.prototype.register = function () {
  59914. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  59915. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  59916. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  59917. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  59918. };
  59919. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  59920. if (mesh.showSubMeshesBoundingBox) {
  59921. var boundingInfo = subMesh.getBoundingInfo();
  59922. if (boundingInfo !== null && boundingInfo !== undefined) {
  59923. this.renderList.push(boundingInfo.boundingBox);
  59924. }
  59925. }
  59926. };
  59927. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  59928. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  59929. var boundingInfo = sourceMesh.getBoundingInfo();
  59930. this.renderList.push(boundingInfo.boundingBox);
  59931. }
  59932. };
  59933. BoundingBoxRenderer.prototype._prepareRessources = function () {
  59934. if (this._colorShader) {
  59935. return;
  59936. }
  59937. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  59938. attributes: [BABYLON.VertexBuffer.PositionKind],
  59939. uniforms: ["world", "viewProjection", "color"]
  59940. });
  59941. var engine = this.scene.getEngine();
  59942. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  59943. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  59944. this._createIndexBuffer();
  59945. };
  59946. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  59947. var engine = this.scene.getEngine();
  59948. 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]);
  59949. };
  59950. /**
  59951. * Rebuilds the elements related to this component in case of
  59952. * context lost for instance.
  59953. */
  59954. BoundingBoxRenderer.prototype.rebuild = function () {
  59955. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59956. if (vb) {
  59957. vb._rebuild();
  59958. }
  59959. this._createIndexBuffer();
  59960. };
  59961. BoundingBoxRenderer.prototype.reset = function () {
  59962. this.renderList.reset();
  59963. };
  59964. BoundingBoxRenderer.prototype.render = function () {
  59965. if (this.renderList.length === 0) {
  59966. return;
  59967. }
  59968. this._prepareRessources();
  59969. if (!this._colorShader.isReady()) {
  59970. return;
  59971. }
  59972. var engine = this.scene.getEngine();
  59973. engine.setDepthWrite(false);
  59974. this._colorShader._preBind();
  59975. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  59976. var boundingBox = this.renderList.data[boundingBoxIndex];
  59977. var min = boundingBox.minimum;
  59978. var max = boundingBox.maximum;
  59979. var diff = max.subtract(min);
  59980. var median = min.add(diff.scale(0.5));
  59981. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59982. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59983. .multiply(boundingBox.getWorldMatrix());
  59984. // VBOs
  59985. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59986. if (this.showBackLines) {
  59987. // Back
  59988. engine.setDepthFunctionToGreaterOrEqual();
  59989. this.scene.resetCachedMaterial();
  59990. this._colorShader.setColor4("color", this.backColor.toColor4());
  59991. this._colorShader.bind(worldMatrix);
  59992. // Draw order
  59993. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59994. }
  59995. // Front
  59996. engine.setDepthFunctionToLess();
  59997. this.scene.resetCachedMaterial();
  59998. this._colorShader.setColor4("color", this.frontColor.toColor4());
  59999. this._colorShader.bind(worldMatrix);
  60000. // Draw order
  60001. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60002. }
  60003. this._colorShader.unbind();
  60004. engine.setDepthFunctionToLessOrEqual();
  60005. engine.setDepthWrite(true);
  60006. };
  60007. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  60008. this._prepareRessources();
  60009. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  60010. return;
  60011. }
  60012. var engine = this.scene.getEngine();
  60013. engine.setDepthWrite(false);
  60014. engine.setColorWrite(false);
  60015. this._colorShader._preBind();
  60016. var boundingBox = mesh._boundingInfo.boundingBox;
  60017. var min = boundingBox.minimum;
  60018. var max = boundingBox.maximum;
  60019. var diff = max.subtract(min);
  60020. var median = min.add(diff.scale(0.5));
  60021. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60022. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60023. .multiply(boundingBox.getWorldMatrix());
  60024. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60025. engine.setDepthFunctionToLess();
  60026. this.scene.resetCachedMaterial();
  60027. this._colorShader.bind(worldMatrix);
  60028. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60029. this._colorShader.unbind();
  60030. engine.setDepthFunctionToLessOrEqual();
  60031. engine.setDepthWrite(true);
  60032. engine.setColorWrite(true);
  60033. };
  60034. BoundingBoxRenderer.prototype.dispose = function () {
  60035. if (!this._colorShader) {
  60036. return;
  60037. }
  60038. this.renderList.dispose();
  60039. this._colorShader.dispose();
  60040. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60041. if (buffer) {
  60042. buffer.dispose();
  60043. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60044. }
  60045. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  60046. };
  60047. return BoundingBoxRenderer;
  60048. }());
  60049. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  60050. })(BABYLON || (BABYLON = {}));
  60051. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  60052. var BABYLON;
  60053. (function (BABYLON) {
  60054. BABYLON.Engine.prototype.createTransformFeedback = function () {
  60055. return this._gl.createTransformFeedback();
  60056. };
  60057. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  60058. this._gl.deleteTransformFeedback(value);
  60059. };
  60060. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  60061. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  60062. };
  60063. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  60064. if (usePoints === void 0) { usePoints = true; }
  60065. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  60066. };
  60067. BABYLON.Engine.prototype.endTransformFeedback = function () {
  60068. this._gl.endTransformFeedback();
  60069. };
  60070. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  60071. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  60072. };
  60073. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  60074. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  60075. };
  60076. })(BABYLON || (BABYLON = {}));
  60077. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  60078. var BABYLON;
  60079. (function (BABYLON) {
  60080. /**
  60081. * This represents a GPU particle system in Babylon
  60082. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  60083. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  60084. */
  60085. var GPUParticleSystem = /** @class */ (function (_super) {
  60086. __extends(GPUParticleSystem, _super);
  60087. /**
  60088. * Instantiates a GPU particle system.
  60089. * 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.
  60090. * @param name The name of the particle system
  60091. * @param options The options used to create the system
  60092. * @param scene The scene the particle system belongs to
  60093. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60094. */
  60095. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  60096. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60097. var _this = _super.call(this, name) || this;
  60098. /**
  60099. * The layer mask we are rendering the particles through.
  60100. */
  60101. _this.layerMask = 0x0FFFFFFF;
  60102. _this._accumulatedCount = 0;
  60103. _this._targetIndex = 0;
  60104. _this._currentRenderId = -1;
  60105. _this._started = false;
  60106. _this._stopped = false;
  60107. _this._timeDelta = 0;
  60108. _this._attributesStrideSize = 21;
  60109. _this._actualFrame = 0;
  60110. _this._rawTextureWidth = 256;
  60111. /**
  60112. * An event triggered when the system is disposed.
  60113. */
  60114. _this.onDisposeObservable = new BABYLON.Observable();
  60115. /**
  60116. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  60117. * to override the particles.
  60118. */
  60119. _this.forceDepthWrite = false;
  60120. _this._preWarmDone = false;
  60121. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60122. _this._engine = _this._scene.getEngine();
  60123. if (!options.randomTextureSize) {
  60124. delete options.randomTextureSize;
  60125. }
  60126. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  60127. var optionsAsNumber = options;
  60128. if (isFinite(optionsAsNumber)) {
  60129. fullOptions.capacity = optionsAsNumber;
  60130. }
  60131. _this._capacity = fullOptions.capacity;
  60132. _this._activeCount = fullOptions.capacity;
  60133. _this._currentActiveCount = 0;
  60134. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60135. _this._scene.particleSystems.push(_this);
  60136. _this._updateEffectOptions = {
  60137. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  60138. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  60139. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  60140. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  60141. uniformBuffersNames: [],
  60142. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  60143. defines: "",
  60144. fallbacks: null,
  60145. onCompiled: null,
  60146. onError: null,
  60147. indexParameters: null,
  60148. maxSimultaneousLights: 0,
  60149. transformFeedbackVaryings: []
  60150. };
  60151. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60152. // Random data
  60153. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  60154. var d = [];
  60155. for (var i = 0; i < maxTextureSize; ++i) {
  60156. d.push(Math.random());
  60157. d.push(Math.random());
  60158. d.push(Math.random());
  60159. d.push(Math.random());
  60160. }
  60161. _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);
  60162. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60163. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60164. d = [];
  60165. for (var i = 0; i < maxTextureSize; ++i) {
  60166. d.push(Math.random());
  60167. d.push(Math.random());
  60168. d.push(Math.random());
  60169. d.push(Math.random());
  60170. }
  60171. _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);
  60172. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60173. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60174. _this._randomTextureSize = maxTextureSize;
  60175. return _this;
  60176. }
  60177. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  60178. /**
  60179. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  60180. */
  60181. get: function () {
  60182. if (!BABYLON.Engine.LastCreatedEngine) {
  60183. return false;
  60184. }
  60185. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  60186. },
  60187. enumerable: true,
  60188. configurable: true
  60189. });
  60190. /**
  60191. * Gets the maximum number of particles active at the same time.
  60192. * @returns The max number of active particles.
  60193. */
  60194. GPUParticleSystem.prototype.getCapacity = function () {
  60195. return this._capacity;
  60196. };
  60197. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  60198. /**
  60199. * Gets or set the number of active particles
  60200. */
  60201. get: function () {
  60202. return this._activeCount;
  60203. },
  60204. set: function (value) {
  60205. this._activeCount = Math.min(value, this._capacity);
  60206. },
  60207. enumerable: true,
  60208. configurable: true
  60209. });
  60210. /**
  60211. * Is this system ready to be used/rendered
  60212. * @return true if the system is ready
  60213. */
  60214. GPUParticleSystem.prototype.isReady = function () {
  60215. if (!this._updateEffect) {
  60216. this._recreateUpdateEffect();
  60217. this._recreateRenderEffect();
  60218. return false;
  60219. }
  60220. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60221. return false;
  60222. }
  60223. return true;
  60224. };
  60225. /**
  60226. * Gets Wether the system has been started.
  60227. * @returns True if it has been started, otherwise false.
  60228. */
  60229. GPUParticleSystem.prototype.isStarted = function () {
  60230. return this._started;
  60231. };
  60232. /**
  60233. * Starts the particle system and begins to emit
  60234. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  60235. */
  60236. GPUParticleSystem.prototype.start = function (delay) {
  60237. var _this = this;
  60238. if (delay === void 0) { delay = 0; }
  60239. if (delay) {
  60240. setTimeout(function () {
  60241. _this.start(0);
  60242. }, delay);
  60243. return;
  60244. }
  60245. this._started = true;
  60246. this._stopped = false;
  60247. this._preWarmDone = false;
  60248. };
  60249. /**
  60250. * Stops the particle system.
  60251. */
  60252. GPUParticleSystem.prototype.stop = function () {
  60253. this._stopped = true;
  60254. };
  60255. /**
  60256. * Remove all active particles
  60257. */
  60258. GPUParticleSystem.prototype.reset = function () {
  60259. this._releaseBuffers();
  60260. this._releaseVAOs();
  60261. this._currentActiveCount = 0;
  60262. this._targetIndex = 0;
  60263. };
  60264. /**
  60265. * Returns the string "GPUParticleSystem"
  60266. * @returns a string containing the class name
  60267. */
  60268. GPUParticleSystem.prototype.getClassName = function () {
  60269. return "GPUParticleSystem";
  60270. };
  60271. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  60272. if (!gradients) {
  60273. return this;
  60274. }
  60275. var index = 0;
  60276. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60277. var valueGradient = gradients_1[_i];
  60278. if (valueGradient.gradient === gradient) {
  60279. gradients.splice(index, 1);
  60280. break;
  60281. }
  60282. index++;
  60283. }
  60284. if (texture) {
  60285. texture.dispose();
  60286. }
  60287. this._releaseBuffers();
  60288. return this;
  60289. };
  60290. /**
  60291. * Adds a new color gradient
  60292. * @param gradient defines the gradient to use (between 0 and 1)
  60293. * @param color defines the color to affect to the specified gradient
  60294. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  60295. * @returns the current particle system
  60296. */
  60297. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  60298. if (!this._colorGradients) {
  60299. this._colorGradients = [];
  60300. }
  60301. var colorGradient = new BABYLON.ColorGradient();
  60302. colorGradient.gradient = gradient;
  60303. colorGradient.color1 = color1;
  60304. this._colorGradients.push(colorGradient);
  60305. this._colorGradients.sort(function (a, b) {
  60306. if (a.gradient < b.gradient) {
  60307. return -1;
  60308. }
  60309. else if (a.gradient > b.gradient) {
  60310. return 1;
  60311. }
  60312. return 0;
  60313. });
  60314. if (this._colorGradientsTexture) {
  60315. this._colorGradientsTexture.dispose();
  60316. this._colorGradientsTexture = null;
  60317. }
  60318. this._releaseBuffers();
  60319. return this;
  60320. };
  60321. /**
  60322. * Remove a specific color gradient
  60323. * @param gradient defines the gradient to remove
  60324. * @returns the current particle system
  60325. */
  60326. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  60327. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  60328. this._colorGradientsTexture = null;
  60329. return this;
  60330. };
  60331. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  60332. var valueGradient = new BABYLON.FactorGradient();
  60333. valueGradient.gradient = gradient;
  60334. valueGradient.factor1 = factor;
  60335. factorGradients.push(valueGradient);
  60336. factorGradients.sort(function (a, b) {
  60337. if (a.gradient < b.gradient) {
  60338. return -1;
  60339. }
  60340. else if (a.gradient > b.gradient) {
  60341. return 1;
  60342. }
  60343. return 0;
  60344. });
  60345. this._releaseBuffers();
  60346. };
  60347. /**
  60348. * Adds a new size gradient
  60349. * @param gradient defines the gradient to use (between 0 and 1)
  60350. * @param factor defines the size factor to affect to the specified gradient
  60351. * @returns the current particle system
  60352. */
  60353. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  60354. if (!this._sizeGradients) {
  60355. this._sizeGradients = [];
  60356. }
  60357. this._addFactorGradient(this._sizeGradients, gradient, factor);
  60358. if (this._sizeGradientsTexture) {
  60359. this._sizeGradientsTexture.dispose();
  60360. this._sizeGradientsTexture = null;
  60361. }
  60362. this._releaseBuffers();
  60363. return this;
  60364. };
  60365. /**
  60366. * Remove a specific size gradient
  60367. * @param gradient defines the gradient to remove
  60368. * @returns the current particle system
  60369. */
  60370. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  60371. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  60372. this._sizeGradientsTexture = null;
  60373. return this;
  60374. };
  60375. /**
  60376. * Adds a new angular speed gradient
  60377. * @param gradient defines the gradient to use (between 0 and 1)
  60378. * @param factor defines the angular speed to affect to the specified gradient
  60379. * @returns the current particle system
  60380. */
  60381. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  60382. if (!this._angularSpeedGradients) {
  60383. this._angularSpeedGradients = [];
  60384. }
  60385. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  60386. if (this._angularSpeedGradientsTexture) {
  60387. this._angularSpeedGradientsTexture.dispose();
  60388. this._angularSpeedGradientsTexture = null;
  60389. }
  60390. this._releaseBuffers();
  60391. return this;
  60392. };
  60393. /**
  60394. * Remove a specific angular speed gradient
  60395. * @param gradient defines the gradient to remove
  60396. * @returns the current particle system
  60397. */
  60398. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  60399. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  60400. this._angularSpeedGradientsTexture = null;
  60401. return this;
  60402. };
  60403. /**
  60404. * Adds a new velocity gradient
  60405. * @param gradient defines the gradient to use (between 0 and 1)
  60406. * @param factor defines the velocity to affect to the specified gradient
  60407. * @returns the current particle system
  60408. */
  60409. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  60410. if (!this._velocityGradients) {
  60411. this._velocityGradients = [];
  60412. }
  60413. this._addFactorGradient(this._velocityGradients, gradient, factor);
  60414. if (this._velocityGradientsTexture) {
  60415. this._velocityGradientsTexture.dispose();
  60416. this._velocityGradientsTexture = null;
  60417. }
  60418. this._releaseBuffers();
  60419. return this;
  60420. };
  60421. /**
  60422. * Remove a specific velocity gradient
  60423. * @param gradient defines the gradient to remove
  60424. * @returns the current particle system
  60425. */
  60426. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60427. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  60428. this._velocityGradientsTexture = null;
  60429. return this;
  60430. };
  60431. /**
  60432. * Adds a new limit velocity gradient
  60433. * @param gradient defines the gradient to use (between 0 and 1)
  60434. * @param factor defines the limit velocity value to affect to the specified gradient
  60435. * @returns the current particle system
  60436. */
  60437. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  60438. if (!this._limitVelocityGradients) {
  60439. this._limitVelocityGradients = [];
  60440. }
  60441. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  60442. if (this._limitVelocityGradientsTexture) {
  60443. this._limitVelocityGradientsTexture.dispose();
  60444. this._limitVelocityGradientsTexture = null;
  60445. }
  60446. this._releaseBuffers();
  60447. return this;
  60448. };
  60449. /**
  60450. * Remove a specific limit velocity gradient
  60451. * @param gradient defines the gradient to remove
  60452. * @returns the current particle system
  60453. */
  60454. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  60455. this._removeGradient(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  60456. this._limitVelocityGradientsTexture = null;
  60457. return this;
  60458. };
  60459. GPUParticleSystem.prototype._reset = function () {
  60460. this._releaseBuffers();
  60461. };
  60462. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  60463. var updateVertexBuffers = {};
  60464. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  60465. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  60466. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  60467. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  60468. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  60469. var offset = 12;
  60470. if (!this._colorGradientsTexture) {
  60471. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  60472. offset += 4;
  60473. }
  60474. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  60475. offset += 3;
  60476. if (!this._isBillboardBased) {
  60477. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  60478. offset += 3;
  60479. }
  60480. if (this._angularSpeedGradientsTexture) {
  60481. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  60482. offset += 1;
  60483. }
  60484. else {
  60485. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  60486. offset += 2;
  60487. }
  60488. if (this._isAnimationSheetEnabled) {
  60489. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  60490. offset += 1;
  60491. }
  60492. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  60493. this._engine.bindArrayBuffer(null);
  60494. return vao;
  60495. };
  60496. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  60497. var renderVertexBuffers = {};
  60498. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  60499. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  60500. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  60501. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  60502. var offset = 12;
  60503. if (!this._colorGradientsTexture) {
  60504. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  60505. offset += 4;
  60506. }
  60507. offset += 3; // Direction
  60508. if (!this._isBillboardBased) {
  60509. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  60510. offset += 3;
  60511. }
  60512. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  60513. if (this._angularSpeedGradientsTexture) {
  60514. offset++;
  60515. }
  60516. else {
  60517. offset += 2;
  60518. }
  60519. if (this._isAnimationSheetEnabled) {
  60520. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  60521. offset += 1;
  60522. }
  60523. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  60524. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  60525. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  60526. this._engine.bindArrayBuffer(null);
  60527. return vao;
  60528. };
  60529. GPUParticleSystem.prototype._initialize = function (force) {
  60530. if (force === void 0) { force = false; }
  60531. if (this._buffer0 && !force) {
  60532. return;
  60533. }
  60534. var engine = this._scene.getEngine();
  60535. var data = new Array();
  60536. if (!this.isBillboardBased) {
  60537. this._attributesStrideSize += 3;
  60538. }
  60539. if (this._colorGradientsTexture) {
  60540. this._attributesStrideSize -= 4;
  60541. }
  60542. if (this._angularSpeedGradientsTexture) {
  60543. this._attributesStrideSize -= 1;
  60544. }
  60545. if (this._isAnimationSheetEnabled) {
  60546. this._attributesStrideSize += 1;
  60547. }
  60548. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  60549. // position
  60550. data.push(0.0);
  60551. data.push(0.0);
  60552. data.push(0.0);
  60553. // Age and life
  60554. data.push(0.0); // create the particle as a dead one to create a new one at start
  60555. data.push(0.0);
  60556. // Seed
  60557. data.push(Math.random());
  60558. data.push(Math.random());
  60559. data.push(Math.random());
  60560. data.push(Math.random());
  60561. // Size
  60562. data.push(0.0);
  60563. data.push(0.0);
  60564. data.push(0.0);
  60565. if (!this._colorGradientsTexture) {
  60566. // color
  60567. data.push(0.0);
  60568. data.push(0.0);
  60569. data.push(0.0);
  60570. data.push(0.0);
  60571. }
  60572. // direction
  60573. data.push(0.0);
  60574. data.push(0.0);
  60575. data.push(0.0);
  60576. if (!this.isBillboardBased) {
  60577. // initialDirection
  60578. data.push(0.0);
  60579. data.push(0.0);
  60580. data.push(0.0);
  60581. }
  60582. // angle
  60583. data.push(0.0);
  60584. if (!this._angularSpeedGradientsTexture) {
  60585. data.push(0.0);
  60586. }
  60587. if (this._isAnimationSheetEnabled) {
  60588. data.push(0.0);
  60589. }
  60590. }
  60591. // Sprite data
  60592. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  60593. -0.5, 0.5, 0, 1,
  60594. -0.5, -0.5, 0, 0,
  60595. 0.5, -0.5, 1, 0]);
  60596. // Buffers
  60597. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60598. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60599. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  60600. // Update VAO
  60601. this._updateVAO = [];
  60602. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  60603. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  60604. // Render VAO
  60605. this._renderVAO = [];
  60606. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  60607. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  60608. // Links
  60609. this._sourceBuffer = this._buffer0;
  60610. this._targetBuffer = this._buffer1;
  60611. };
  60612. /** @hidden */
  60613. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  60614. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  60615. if (this._isBillboardBased) {
  60616. defines += "\n#define BILLBOARD";
  60617. }
  60618. if (this._colorGradientsTexture) {
  60619. defines += "\n#define COLORGRADIENTS";
  60620. }
  60621. if (this._sizeGradientsTexture) {
  60622. defines += "\n#define SIZEGRADIENTS";
  60623. }
  60624. if (this._angularSpeedGradientsTexture) {
  60625. defines += "\n#define ANGULARSPEEDGRADIENTS";
  60626. }
  60627. if (this._velocityGradientsTexture) {
  60628. defines += "\n#define VELOCITYGRADIENTS";
  60629. }
  60630. if (this.isAnimationSheetEnabled) {
  60631. defines += "\n#define ANIMATESHEET";
  60632. }
  60633. if (this.noiseTexture) {
  60634. defines += "\n#define NOISE";
  60635. }
  60636. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  60637. return;
  60638. }
  60639. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  60640. if (!this._colorGradientsTexture) {
  60641. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  60642. }
  60643. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  60644. if (!this._isBillboardBased) {
  60645. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  60646. }
  60647. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  60648. if (this.isAnimationSheetEnabled) {
  60649. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  60650. }
  60651. this._updateEffectOptions.defines = defines;
  60652. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  60653. };
  60654. /** @hidden */
  60655. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  60656. var defines = "";
  60657. if (this._scene.clipPlane) {
  60658. defines = "\n#define CLIPPLANE";
  60659. }
  60660. if (this._isBillboardBased) {
  60661. defines += "\n#define BILLBOARD";
  60662. switch (this.billboardMode) {
  60663. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  60664. defines += "\n#define BILLBOARDY";
  60665. break;
  60666. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  60667. default:
  60668. break;
  60669. }
  60670. }
  60671. if (this._colorGradientsTexture) {
  60672. defines += "\n#define COLORGRADIENTS";
  60673. }
  60674. if (this.isAnimationSheetEnabled) {
  60675. defines += "\n#define ANIMATESHEET";
  60676. }
  60677. if (this._renderEffect && this._renderEffect.defines === defines) {
  60678. return;
  60679. }
  60680. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  60681. };
  60682. /**
  60683. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60684. * @param preWarm defines if we are in the pre-warmimg phase
  60685. */
  60686. GPUParticleSystem.prototype.animate = function (preWarm) {
  60687. if (preWarm === void 0) { preWarm = false; }
  60688. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60689. this._actualFrame += this._timeDelta;
  60690. if (!this._stopped) {
  60691. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  60692. this.stop();
  60693. }
  60694. }
  60695. };
  60696. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  60697. var texture = this[textureName];
  60698. if (!factorGradients || !factorGradients.length || texture) {
  60699. return;
  60700. }
  60701. var data = new Float32Array(this._rawTextureWidth);
  60702. for (var x = 0; x < this._rawTextureWidth; x++) {
  60703. var ratio = x / this._rawTextureWidth;
  60704. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  60705. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60706. });
  60707. }
  60708. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60709. };
  60710. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  60711. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  60712. };
  60713. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  60714. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  60715. };
  60716. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  60717. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  60718. };
  60719. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  60720. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  60721. return;
  60722. }
  60723. var data = new Uint8Array(this._rawTextureWidth * 4);
  60724. var tmpColor = BABYLON.Tmp.Color4[0];
  60725. for (var x = 0; x < this._rawTextureWidth; x++) {
  60726. var ratio = x / this._rawTextureWidth;
  60727. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  60728. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  60729. data[x * 4] = tmpColor.r * 255;
  60730. data[x * 4 + 1] = tmpColor.g * 255;
  60731. data[x * 4 + 2] = tmpColor.b * 255;
  60732. data[x * 4 + 3] = tmpColor.a * 255;
  60733. });
  60734. }
  60735. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60736. };
  60737. /**
  60738. * Renders the particle system in its current state
  60739. * @param preWarm defines if the system should only update the particles but not render them
  60740. * @returns the current number of particles
  60741. */
  60742. GPUParticleSystem.prototype.render = function (preWarm) {
  60743. if (preWarm === void 0) { preWarm = false; }
  60744. if (!this._started) {
  60745. return 0;
  60746. }
  60747. this._createColorGradientTexture();
  60748. this._createSizeGradientTexture();
  60749. this._createAngularSpeedGradientTexture();
  60750. this._createVelocityGradientTexture();
  60751. this._recreateUpdateEffect();
  60752. this._recreateRenderEffect();
  60753. if (!this.isReady()) {
  60754. return 0;
  60755. }
  60756. if (!preWarm) {
  60757. if (!this._preWarmDone && this.preWarmCycles) {
  60758. for (var index = 0; index < this.preWarmCycles; index++) {
  60759. this.animate(true);
  60760. this.render(true);
  60761. }
  60762. this._preWarmDone = true;
  60763. }
  60764. if (this._currentRenderId === this._scene.getRenderId()) {
  60765. return 0;
  60766. }
  60767. this._currentRenderId = this._scene.getRenderId();
  60768. }
  60769. // Get everything ready to render
  60770. this._initialize();
  60771. this._accumulatedCount += this.emitRate * this._timeDelta;
  60772. if (this._accumulatedCount > 1) {
  60773. var intPart = this._accumulatedCount | 0;
  60774. this._accumulatedCount -= intPart;
  60775. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  60776. }
  60777. if (!this._currentActiveCount) {
  60778. return 0;
  60779. }
  60780. // Enable update effect
  60781. this._engine.enableEffect(this._updateEffect);
  60782. this._engine.setState(false);
  60783. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  60784. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  60785. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  60786. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  60787. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  60788. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  60789. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  60790. if (!this._colorGradientsTexture) {
  60791. this._updateEffect.setDirectColor4("color1", this.color1);
  60792. this._updateEffect.setDirectColor4("color2", this.color2);
  60793. }
  60794. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  60795. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  60796. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  60797. this._updateEffect.setVector3("gravity", this.gravity);
  60798. if (this._sizeGradientsTexture) {
  60799. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  60800. }
  60801. if (this._angularSpeedGradientsTexture) {
  60802. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  60803. }
  60804. if (this._velocityGradientsTexture) {
  60805. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  60806. }
  60807. if (this.particleEmitterType) {
  60808. this.particleEmitterType.applyToShader(this._updateEffect);
  60809. }
  60810. if (this._isAnimationSheetEnabled) {
  60811. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  60812. }
  60813. if (this.noiseTexture) {
  60814. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  60815. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  60816. }
  60817. var emitterWM;
  60818. if (this.emitter.position) {
  60819. var emitterMesh = this.emitter;
  60820. emitterWM = emitterMesh.getWorldMatrix();
  60821. }
  60822. else {
  60823. var emitterPosition = this.emitter;
  60824. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  60825. }
  60826. this._updateEffect.setMatrix("emitterWM", emitterWM);
  60827. // Bind source VAO
  60828. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  60829. // Update
  60830. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  60831. this._engine.setRasterizerState(false);
  60832. this._engine.beginTransformFeedback(true);
  60833. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  60834. this._engine.endTransformFeedback();
  60835. this._engine.setRasterizerState(true);
  60836. this._engine.bindTransformFeedbackBuffer(null);
  60837. if (!preWarm) {
  60838. // Enable render effect
  60839. this._engine.enableEffect(this._renderEffect);
  60840. var viewMatrix = this._scene.getViewMatrix();
  60841. this._renderEffect.setMatrix("view", viewMatrix);
  60842. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  60843. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  60844. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  60845. if (this._colorGradientsTexture) {
  60846. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  60847. }
  60848. else {
  60849. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  60850. }
  60851. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60852. var baseSize = this.particleTexture.getBaseSize();
  60853. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60854. }
  60855. if (this._isBillboardBased) {
  60856. var camera = this._scene.activeCamera;
  60857. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  60858. }
  60859. if (this._scene.clipPlane) {
  60860. var clipPlane = this._scene.clipPlane;
  60861. var invView = viewMatrix.clone();
  60862. invView.invert();
  60863. this._renderEffect.setMatrix("invView", invView);
  60864. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  60865. }
  60866. // Draw order
  60867. switch (this.blendMode) {
  60868. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  60869. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60870. break;
  60871. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  60872. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60873. break;
  60874. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  60875. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60876. break;
  60877. }
  60878. if (this.forceDepthWrite) {
  60879. this._engine.setDepthWrite(true);
  60880. }
  60881. // Bind source VAO
  60882. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  60883. // Render
  60884. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  60885. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60886. }
  60887. // Switch VAOs
  60888. this._targetIndex++;
  60889. if (this._targetIndex === 2) {
  60890. this._targetIndex = 0;
  60891. }
  60892. // Switch buffers
  60893. var tmpBuffer = this._sourceBuffer;
  60894. this._sourceBuffer = this._targetBuffer;
  60895. this._targetBuffer = tmpBuffer;
  60896. return this._currentActiveCount;
  60897. };
  60898. /**
  60899. * Rebuilds the particle system
  60900. */
  60901. GPUParticleSystem.prototype.rebuild = function () {
  60902. this._initialize(true);
  60903. };
  60904. GPUParticleSystem.prototype._releaseBuffers = function () {
  60905. if (this._buffer0) {
  60906. this._buffer0.dispose();
  60907. this._buffer0 = null;
  60908. }
  60909. if (this._buffer1) {
  60910. this._buffer1.dispose();
  60911. this._buffer1 = null;
  60912. }
  60913. if (this._spriteBuffer) {
  60914. this._spriteBuffer.dispose();
  60915. this._spriteBuffer = null;
  60916. }
  60917. };
  60918. GPUParticleSystem.prototype._releaseVAOs = function () {
  60919. if (!this._updateVAO) {
  60920. return;
  60921. }
  60922. for (var index = 0; index < this._updateVAO.length; index++) {
  60923. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  60924. }
  60925. this._updateVAO = [];
  60926. for (var index = 0; index < this._renderVAO.length; index++) {
  60927. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  60928. }
  60929. this._renderVAO = [];
  60930. };
  60931. /**
  60932. * Disposes the particle system and free the associated resources
  60933. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60934. */
  60935. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  60936. if (disposeTexture === void 0) { disposeTexture = true; }
  60937. var index = this._scene.particleSystems.indexOf(this);
  60938. if (index > -1) {
  60939. this._scene.particleSystems.splice(index, 1);
  60940. }
  60941. this._releaseBuffers();
  60942. this._releaseVAOs();
  60943. if (this._colorGradientsTexture) {
  60944. this._colorGradientsTexture.dispose();
  60945. this._colorGradientsTexture = null;
  60946. }
  60947. if (this._sizeGradientsTexture) {
  60948. this._sizeGradientsTexture.dispose();
  60949. this._sizeGradientsTexture = null;
  60950. }
  60951. if (this._angularSpeedGradientsTexture) {
  60952. this._angularSpeedGradientsTexture.dispose();
  60953. this._angularSpeedGradientsTexture = null;
  60954. }
  60955. if (this._velocityGradientsTexture) {
  60956. this._velocityGradientsTexture.dispose();
  60957. this._velocityGradientsTexture = null;
  60958. }
  60959. if (this._limitVelocityGradientsTexture) {
  60960. this._limitVelocityGradientsTexture.dispose();
  60961. this._limitVelocityGradientsTexture = null;
  60962. }
  60963. if (this._randomTexture) {
  60964. this._randomTexture.dispose();
  60965. this._randomTexture = null;
  60966. }
  60967. if (this._randomTexture2) {
  60968. this._randomTexture2.dispose();
  60969. this._randomTexture2 = null;
  60970. }
  60971. if (disposeTexture && this.particleTexture) {
  60972. this.particleTexture.dispose();
  60973. this.particleTexture = null;
  60974. }
  60975. if (disposeTexture && this.noiseTexture) {
  60976. this.noiseTexture.dispose();
  60977. this.noiseTexture = null;
  60978. }
  60979. // Callback
  60980. this.onDisposeObservable.notifyObservers(this);
  60981. this.onDisposeObservable.clear();
  60982. };
  60983. /**
  60984. * Clones the particle system.
  60985. * @param name The name of the cloned object
  60986. * @param newEmitter The new emitter to use
  60987. * @returns the cloned particle system
  60988. */
  60989. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  60990. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  60991. BABYLON.Tools.DeepCopy(this, result);
  60992. if (newEmitter === undefined) {
  60993. newEmitter = this.emitter;
  60994. }
  60995. result.emitter = newEmitter;
  60996. if (this.particleTexture) {
  60997. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60998. }
  60999. return result;
  61000. };
  61001. /**
  61002. * Serializes the particle system to a JSON object.
  61003. * @returns the JSON object
  61004. */
  61005. GPUParticleSystem.prototype.serialize = function () {
  61006. var serializationObject = {};
  61007. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  61008. serializationObject.activeParticleCount = this.activeParticleCount;
  61009. return serializationObject;
  61010. };
  61011. /**
  61012. * Parses a JSON object to create a GPU particle system.
  61013. * @param parsedParticleSystem The JSON object to parse
  61014. * @param scene The scene to create the particle system in
  61015. * @param rootUrl The root url to use to load external dependencies like texture
  61016. * @returns the parsed GPU particle system
  61017. */
  61018. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  61019. var name = parsedParticleSystem.name;
  61020. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  61021. if (parsedParticleSystem.activeParticleCount) {
  61022. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  61023. }
  61024. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61025. return particleSystem;
  61026. };
  61027. return GPUParticleSystem;
  61028. }(BABYLON.BaseParticleSystem));
  61029. BABYLON.GPUParticleSystem = GPUParticleSystem;
  61030. })(BABYLON || (BABYLON = {}));
  61031. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  61032. var BABYLON;
  61033. (function (BABYLON) {
  61034. /**
  61035. * Represents one particle of a solid particle system.
  61036. */
  61037. var SolidParticle = /** @class */ (function () {
  61038. /**
  61039. * Creates a Solid Particle object.
  61040. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  61041. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  61042. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  61043. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  61044. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  61045. * @param shapeId (integer) is the model shape identifier in the SPS.
  61046. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  61047. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  61048. */
  61049. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  61050. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  61051. /**
  61052. * particle global index
  61053. */
  61054. this.idx = 0;
  61055. /**
  61056. * The color of the particle
  61057. */
  61058. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61059. /**
  61060. * The world space position of the particle.
  61061. */
  61062. this.position = BABYLON.Vector3.Zero();
  61063. /**
  61064. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  61065. */
  61066. this.rotation = BABYLON.Vector3.Zero();
  61067. /**
  61068. * The scaling of the particle.
  61069. */
  61070. this.scaling = BABYLON.Vector3.One();
  61071. /**
  61072. * The uvs of the particle.
  61073. */
  61074. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  61075. /**
  61076. * The current speed of the particle.
  61077. */
  61078. this.velocity = BABYLON.Vector3.Zero();
  61079. /**
  61080. * The pivot point in the particle local space.
  61081. */
  61082. this.pivot = BABYLON.Vector3.Zero();
  61083. /**
  61084. * Must the particle be translated from its pivot point in its local space ?
  61085. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  61086. * Default : false
  61087. */
  61088. this.translateFromPivot = false;
  61089. /**
  61090. * Is the particle active or not ?
  61091. */
  61092. this.alive = true;
  61093. /**
  61094. * Is the particle visible or not ?
  61095. */
  61096. this.isVisible = true;
  61097. /**
  61098. * Index of this particle in the global "positions" array (Internal use)
  61099. */
  61100. this._pos = 0;
  61101. /**
  61102. * Index of this particle in the global "indices" array (Internal use)
  61103. */
  61104. this._ind = 0;
  61105. /**
  61106. * ModelShape id of this particle
  61107. */
  61108. this.shapeId = 0;
  61109. /**
  61110. * Index of the particle in its shape id (Internal use)
  61111. */
  61112. this.idxInShape = 0;
  61113. /**
  61114. * Still set as invisible in order to skip useless computations (Internal use)
  61115. */
  61116. this._stillInvisible = false;
  61117. /**
  61118. * Last computed particle rotation matrix
  61119. */
  61120. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  61121. /**
  61122. * Parent particle Id, if any.
  61123. * Default null.
  61124. */
  61125. this.parentId = null;
  61126. /**
  61127. * Internal global position in the SPS.
  61128. */
  61129. this._globalPosition = BABYLON.Vector3.Zero();
  61130. this.idx = particleIndex;
  61131. this._pos = positionIndex;
  61132. this._ind = indiceIndex;
  61133. this._model = model;
  61134. this.shapeId = shapeId;
  61135. this.idxInShape = idxInShape;
  61136. this._sps = sps;
  61137. if (modelBoundingInfo) {
  61138. this._modelBoundingInfo = modelBoundingInfo;
  61139. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  61140. }
  61141. }
  61142. Object.defineProperty(SolidParticle.prototype, "scale", {
  61143. /**
  61144. * Legacy support, changed scale to scaling
  61145. */
  61146. get: function () {
  61147. return this.scaling;
  61148. },
  61149. /**
  61150. * Legacy support, changed scale to scaling
  61151. */
  61152. set: function (scale) {
  61153. this.scaling = scale;
  61154. },
  61155. enumerable: true,
  61156. configurable: true
  61157. });
  61158. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  61159. /**
  61160. * Legacy support, changed quaternion to rotationQuaternion
  61161. */
  61162. get: function () {
  61163. return this.rotationQuaternion;
  61164. },
  61165. /**
  61166. * Legacy support, changed quaternion to rotationQuaternion
  61167. */
  61168. set: function (q) {
  61169. this.rotationQuaternion = q;
  61170. },
  61171. enumerable: true,
  61172. configurable: true
  61173. });
  61174. /**
  61175. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  61176. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  61177. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  61178. * @returns true if it intersects
  61179. */
  61180. SolidParticle.prototype.intersectsMesh = function (target) {
  61181. if (!this._boundingInfo || !target._boundingInfo) {
  61182. return false;
  61183. }
  61184. if (this._sps._bSphereOnly) {
  61185. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  61186. }
  61187. return this._boundingInfo.intersects(target._boundingInfo, false);
  61188. };
  61189. return SolidParticle;
  61190. }());
  61191. BABYLON.SolidParticle = SolidParticle;
  61192. /**
  61193. * Represents the shape of the model used by one particle of a solid particle system.
  61194. * SPS internal tool, don't use it manually.
  61195. */
  61196. var ModelShape = /** @class */ (function () {
  61197. /**
  61198. * 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.
  61199. * SPS internal tool, don't use it manually.
  61200. * @hidden
  61201. */
  61202. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  61203. /**
  61204. * length of the shape in the model indices array (internal use)
  61205. */
  61206. this._indicesLength = 0;
  61207. this.shapeID = id;
  61208. this._shape = shape;
  61209. this._indicesLength = indicesLength;
  61210. this._shapeUV = shapeUV;
  61211. this._positionFunction = posFunction;
  61212. this._vertexFunction = vtxFunction;
  61213. }
  61214. return ModelShape;
  61215. }());
  61216. BABYLON.ModelShape = ModelShape;
  61217. /**
  61218. * Represents a Depth Sorted Particle in the solid particle system.
  61219. */
  61220. var DepthSortedParticle = /** @class */ (function () {
  61221. function DepthSortedParticle() {
  61222. /**
  61223. * Index of the particle in the "indices" array
  61224. */
  61225. this.ind = 0;
  61226. /**
  61227. * Length of the particle shape in the "indices" array
  61228. */
  61229. this.indicesLength = 0;
  61230. /**
  61231. * Squared distance from the particle to the camera
  61232. */
  61233. this.sqDistance = 0.0;
  61234. }
  61235. return DepthSortedParticle;
  61236. }());
  61237. BABYLON.DepthSortedParticle = DepthSortedParticle;
  61238. })(BABYLON || (BABYLON = {}));
  61239. //# sourceMappingURL=babylon.solidParticle.js.map
  61240. var BABYLON;
  61241. (function (BABYLON) {
  61242. /**
  61243. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  61244. *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.
  61245. * The SPS is also a particle system. It provides some methods to manage the particles.
  61246. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  61247. *
  61248. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  61249. */
  61250. var SolidParticleSystem = /** @class */ (function () {
  61251. /**
  61252. * Creates a SPS (Solid Particle System) object.
  61253. * @param name (String) is the SPS name, this will be the underlying mesh name.
  61254. * @param scene (Scene) is the scene in which the SPS is added.
  61255. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  61256. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  61257. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  61258. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  61259. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  61260. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  61261. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  61262. */
  61263. function SolidParticleSystem(name, scene, options) {
  61264. /**
  61265. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  61266. * Example : var p = SPS.particles[i];
  61267. */
  61268. this.particles = new Array();
  61269. /**
  61270. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  61271. */
  61272. this.nbParticles = 0;
  61273. /**
  61274. * If the particles must ever face the camera (default false). Useful for planar particles.
  61275. */
  61276. this.billboard = false;
  61277. /**
  61278. * Recompute normals when adding a shape
  61279. */
  61280. this.recomputeNormals = true;
  61281. /**
  61282. * This a counter ofr your own usage. It's not set by any SPS functions.
  61283. */
  61284. this.counter = 0;
  61285. /**
  61286. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  61287. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  61288. */
  61289. this.vars = {};
  61290. /**
  61291. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  61292. */
  61293. this._bSphereOnly = false;
  61294. /**
  61295. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  61296. */
  61297. this._bSphereRadiusFactor = 1.0;
  61298. this._positions = new Array();
  61299. this._indices = new Array();
  61300. this._normals = new Array();
  61301. this._colors = new Array();
  61302. this._uvs = new Array();
  61303. this._index = 0; // indices index
  61304. this._updatable = true;
  61305. this._pickable = false;
  61306. this._isVisibilityBoxLocked = false;
  61307. this._alwaysVisible = false;
  61308. this._depthSort = false;
  61309. this._shapeCounter = 0;
  61310. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  61311. this._color = new BABYLON.Color4(0, 0, 0, 0);
  61312. this._computeParticleColor = true;
  61313. this._computeParticleTexture = true;
  61314. this._computeParticleRotation = true;
  61315. this._computeParticleVertex = false;
  61316. this._computeBoundingBox = false;
  61317. this._depthSortParticles = true;
  61318. this._cam_axisZ = BABYLON.Vector3.Zero();
  61319. this._cam_axisY = BABYLON.Vector3.Zero();
  61320. this._cam_axisX = BABYLON.Vector3.Zero();
  61321. this._axisZ = BABYLON.Axis.Z;
  61322. this._camDir = BABYLON.Vector3.Zero();
  61323. this._camInvertedPosition = BABYLON.Vector3.Zero();
  61324. this._rotMatrix = new BABYLON.Matrix();
  61325. this._invertMatrix = new BABYLON.Matrix();
  61326. this._rotated = BABYLON.Vector3.Zero();
  61327. this._quaternion = new BABYLON.Quaternion();
  61328. this._vertex = BABYLON.Vector3.Zero();
  61329. this._normal = BABYLON.Vector3.Zero();
  61330. this._yaw = 0.0;
  61331. this._pitch = 0.0;
  61332. this._roll = 0.0;
  61333. this._halfroll = 0.0;
  61334. this._halfpitch = 0.0;
  61335. this._halfyaw = 0.0;
  61336. this._sinRoll = 0.0;
  61337. this._cosRoll = 0.0;
  61338. this._sinPitch = 0.0;
  61339. this._cosPitch = 0.0;
  61340. this._sinYaw = 0.0;
  61341. this._cosYaw = 0.0;
  61342. this._mustUnrotateFixedNormals = false;
  61343. this._minimum = BABYLON.Vector3.Zero();
  61344. this._maximum = BABYLON.Vector3.Zero();
  61345. this._minBbox = BABYLON.Vector3.Zero();
  61346. this._maxBbox = BABYLON.Vector3.Zero();
  61347. this._particlesIntersect = false;
  61348. this._depthSortFunction = function (p1, p2) {
  61349. return (p2.sqDistance - p1.sqDistance);
  61350. };
  61351. this._needs32Bits = false;
  61352. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  61353. this._scaledPivot = BABYLON.Vector3.Zero();
  61354. this._particleHasParent = false;
  61355. this.name = name;
  61356. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61357. this._camera = scene.activeCamera;
  61358. this._pickable = options ? options.isPickable : false;
  61359. this._depthSort = options ? options.enableDepthSort : false;
  61360. this._particlesIntersect = options ? options.particleIntersection : false;
  61361. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  61362. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  61363. if (options && options.updatable !== undefined) {
  61364. this._updatable = options.updatable;
  61365. }
  61366. else {
  61367. this._updatable = true;
  61368. }
  61369. if (this._pickable) {
  61370. this.pickedParticles = [];
  61371. }
  61372. if (this._depthSort) {
  61373. this.depthSortedParticles = [];
  61374. }
  61375. }
  61376. /**
  61377. * Builds the SPS underlying mesh. Returns a standard Mesh.
  61378. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  61379. * @returns the created mesh
  61380. */
  61381. SolidParticleSystem.prototype.buildMesh = function () {
  61382. if (this.nbParticles === 0) {
  61383. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  61384. this.addShape(triangle, 1);
  61385. triangle.dispose();
  61386. }
  61387. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  61388. this._positions32 = new Float32Array(this._positions);
  61389. this._uvs32 = new Float32Array(this._uvs);
  61390. this._colors32 = new Float32Array(this._colors);
  61391. if (this.recomputeNormals) {
  61392. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  61393. }
  61394. this._normals32 = new Float32Array(this._normals);
  61395. this._fixedNormal32 = new Float32Array(this._normals);
  61396. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  61397. this._unrotateFixedNormals();
  61398. }
  61399. var vertexData = new BABYLON.VertexData();
  61400. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  61401. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  61402. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  61403. if (this._uvs32.length > 0) {
  61404. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  61405. }
  61406. if (this._colors32.length > 0) {
  61407. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  61408. }
  61409. var mesh = new BABYLON.Mesh(this.name, this._scene);
  61410. vertexData.applyToMesh(mesh, this._updatable);
  61411. this.mesh = mesh;
  61412. this.mesh.isPickable = this._pickable;
  61413. // free memory
  61414. if (!this._depthSort) {
  61415. this._indices = null;
  61416. }
  61417. this._positions = null;
  61418. this._normals = null;
  61419. this._uvs = null;
  61420. this._colors = null;
  61421. if (!this._updatable) {
  61422. this.particles.length = 0;
  61423. }
  61424. return mesh;
  61425. };
  61426. /**
  61427. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  61428. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  61429. * Thus the particles generated from `digest()` have their property `position` set yet.
  61430. * @param mesh ( Mesh ) is the mesh to be digested
  61431. * @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
  61432. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  61433. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  61434. * @returns the current SPS
  61435. */
  61436. SolidParticleSystem.prototype.digest = function (mesh, options) {
  61437. var size = (options && options.facetNb) || 1;
  61438. var number = (options && options.number) || 0;
  61439. var delta = (options && options.delta) || 0;
  61440. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61441. var meshInd = mesh.getIndices();
  61442. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61443. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61444. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61445. var f = 0; // facet counter
  61446. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  61447. // compute size from number
  61448. if (number) {
  61449. number = (number > totalFacets) ? totalFacets : number;
  61450. size = Math.round(totalFacets / number);
  61451. delta = 0;
  61452. }
  61453. else {
  61454. size = (size > totalFacets) ? totalFacets : size;
  61455. }
  61456. var facetPos = []; // submesh positions
  61457. var facetInd = []; // submesh indices
  61458. var facetUV = []; // submesh UV
  61459. var facetCol = []; // submesh colors
  61460. var barycenter = BABYLON.Vector3.Zero();
  61461. var sizeO = size;
  61462. while (f < totalFacets) {
  61463. size = sizeO + Math.floor((1 + delta) * Math.random());
  61464. if (f > totalFacets - size) {
  61465. size = totalFacets - f;
  61466. }
  61467. // reset temp arrays
  61468. facetPos.length = 0;
  61469. facetInd.length = 0;
  61470. facetUV.length = 0;
  61471. facetCol.length = 0;
  61472. // iterate over "size" facets
  61473. var fi = 0;
  61474. for (var j = f * 3; j < (f + size) * 3; j++) {
  61475. facetInd.push(fi);
  61476. var i = meshInd[j];
  61477. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  61478. if (meshUV) {
  61479. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  61480. }
  61481. if (meshCol) {
  61482. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  61483. }
  61484. fi++;
  61485. }
  61486. // create a model shape for each single particle
  61487. var idx = this.nbParticles;
  61488. var shape = this._posToShape(facetPos);
  61489. var shapeUV = this._uvsToShapeUV(facetUV);
  61490. // compute the barycenter of the shape
  61491. var v;
  61492. for (v = 0; v < shape.length; v++) {
  61493. barycenter.addInPlace(shape[v]);
  61494. }
  61495. barycenter.scaleInPlace(1 / shape.length);
  61496. // shift the shape from its barycenter to the origin
  61497. for (v = 0; v < shape.length; v++) {
  61498. shape[v].subtractInPlace(barycenter);
  61499. }
  61500. var bInfo;
  61501. if (this._particlesIntersect) {
  61502. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  61503. }
  61504. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  61505. // add the particle in the SPS
  61506. var currentPos = this._positions.length;
  61507. var currentInd = this._indices.length;
  61508. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  61509. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  61510. // initialize the particle position
  61511. this.particles[this.nbParticles].position.addInPlace(barycenter);
  61512. this._index += shape.length;
  61513. idx++;
  61514. this.nbParticles++;
  61515. this._shapeCounter++;
  61516. f += size;
  61517. }
  61518. return this;
  61519. };
  61520. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  61521. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  61522. var index = 0;
  61523. var idx = 0;
  61524. for (var p = 0; p < this.particles.length; p++) {
  61525. this._particle = this.particles[p];
  61526. this._shape = this._particle._model._shape;
  61527. if (this._particle.rotationQuaternion) {
  61528. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61529. }
  61530. else {
  61531. this._yaw = this._particle.rotation.y;
  61532. this._pitch = this._particle.rotation.x;
  61533. this._roll = this._particle.rotation.z;
  61534. this._quaternionRotationYPR();
  61535. }
  61536. this._quaternionToRotationMatrix();
  61537. this._rotMatrix.invertToRef(this._invertMatrix);
  61538. for (var pt = 0; pt < this._shape.length; pt++) {
  61539. idx = index + pt * 3;
  61540. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  61541. this._fixedNormal32[idx] = this._normal.x;
  61542. this._fixedNormal32[idx + 1] = this._normal.y;
  61543. this._fixedNormal32[idx + 2] = this._normal.z;
  61544. }
  61545. index = idx + 3;
  61546. }
  61547. };
  61548. //reset copy
  61549. SolidParticleSystem.prototype._resetCopy = function () {
  61550. this._copy.position.x = 0;
  61551. this._copy.position.y = 0;
  61552. this._copy.position.z = 0;
  61553. this._copy.rotation.x = 0;
  61554. this._copy.rotation.y = 0;
  61555. this._copy.rotation.z = 0;
  61556. this._copy.rotationQuaternion = null;
  61557. this._copy.scaling.x = 1.0;
  61558. this._copy.scaling.y = 1.0;
  61559. this._copy.scaling.z = 1.0;
  61560. this._copy.uvs.x = 0;
  61561. this._copy.uvs.y = 0;
  61562. this._copy.uvs.z = 1.0;
  61563. this._copy.uvs.w = 1.0;
  61564. this._copy.color = null;
  61565. this._copy.translateFromPivot = false;
  61566. };
  61567. // _meshBuilder : inserts the shape model in the global SPS mesh
  61568. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  61569. var i;
  61570. var u = 0;
  61571. var c = 0;
  61572. var n = 0;
  61573. this._resetCopy();
  61574. if (options && options.positionFunction) { // call to custom positionFunction
  61575. options.positionFunction(this._copy, idx, idxInShape);
  61576. this._mustUnrotateFixedNormals = true;
  61577. }
  61578. if (this._copy.rotationQuaternion) {
  61579. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61580. }
  61581. else {
  61582. this._yaw = this._copy.rotation.y;
  61583. this._pitch = this._copy.rotation.x;
  61584. this._roll = this._copy.rotation.z;
  61585. this._quaternionRotationYPR();
  61586. }
  61587. this._quaternionToRotationMatrix();
  61588. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  61589. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  61590. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  61591. if (this._copy.translateFromPivot) {
  61592. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61593. }
  61594. else {
  61595. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61596. }
  61597. for (i = 0; i < shape.length; i++) {
  61598. this._vertex.x = shape[i].x;
  61599. this._vertex.y = shape[i].y;
  61600. this._vertex.z = shape[i].z;
  61601. if (options && options.vertexFunction) {
  61602. options.vertexFunction(this._copy, this._vertex, i);
  61603. }
  61604. this._vertex.x *= this._copy.scaling.x;
  61605. this._vertex.y *= this._copy.scaling.y;
  61606. this._vertex.z *= this._copy.scaling.z;
  61607. this._vertex.x -= this._scaledPivot.x;
  61608. this._vertex.y -= this._scaledPivot.y;
  61609. this._vertex.z -= this._scaledPivot.z;
  61610. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61611. this._rotated.addInPlace(this._pivotBackTranslation);
  61612. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  61613. if (meshUV) {
  61614. 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);
  61615. u += 2;
  61616. }
  61617. if (this._copy.color) {
  61618. this._color = this._copy.color;
  61619. }
  61620. else if (meshCol && meshCol[c] !== undefined) {
  61621. this._color.r = meshCol[c];
  61622. this._color.g = meshCol[c + 1];
  61623. this._color.b = meshCol[c + 2];
  61624. this._color.a = meshCol[c + 3];
  61625. }
  61626. else {
  61627. this._color.r = 1.0;
  61628. this._color.g = 1.0;
  61629. this._color.b = 1.0;
  61630. this._color.a = 1.0;
  61631. }
  61632. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  61633. c += 4;
  61634. if (!this.recomputeNormals && meshNor) {
  61635. this._normal.x = meshNor[n];
  61636. this._normal.y = meshNor[n + 1];
  61637. this._normal.z = meshNor[n + 2];
  61638. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  61639. normals.push(this._normal.x, this._normal.y, this._normal.z);
  61640. n += 3;
  61641. }
  61642. }
  61643. for (i = 0; i < meshInd.length; i++) {
  61644. var current_ind = p + meshInd[i];
  61645. indices.push(current_ind);
  61646. if (current_ind > 65535) {
  61647. this._needs32Bits = true;
  61648. }
  61649. }
  61650. if (this._pickable) {
  61651. var nbfaces = meshInd.length / 3;
  61652. for (i = 0; i < nbfaces; i++) {
  61653. this.pickedParticles.push({ idx: idx, faceId: i });
  61654. }
  61655. }
  61656. if (this._depthSort) {
  61657. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  61658. }
  61659. return this._copy;
  61660. };
  61661. // returns a shape array from positions array
  61662. SolidParticleSystem.prototype._posToShape = function (positions) {
  61663. var shape = [];
  61664. for (var i = 0; i < positions.length; i += 3) {
  61665. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  61666. }
  61667. return shape;
  61668. };
  61669. // returns a shapeUV array from a Vector4 uvs
  61670. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  61671. var shapeUV = [];
  61672. if (uvs) {
  61673. for (var i = 0; i < uvs.length; i++)
  61674. shapeUV.push(uvs[i]);
  61675. }
  61676. return shapeUV;
  61677. };
  61678. // adds a new particle object in the particles array
  61679. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  61680. if (bInfo === void 0) { bInfo = null; }
  61681. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  61682. this.particles.push(sp);
  61683. return sp;
  61684. };
  61685. /**
  61686. * Adds some particles to the SPS from the model shape. Returns the shape id.
  61687. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  61688. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  61689. * @param nb (positive integer) the number of particles to be created from this model
  61690. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  61691. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  61692. * @returns the number of shapes in the system
  61693. */
  61694. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  61695. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61696. var meshInd = mesh.getIndices();
  61697. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61698. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61699. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61700. var bbInfo;
  61701. if (this._particlesIntersect) {
  61702. bbInfo = mesh.getBoundingInfo();
  61703. }
  61704. var shape = this._posToShape(meshPos);
  61705. var shapeUV = this._uvsToShapeUV(meshUV);
  61706. var posfunc = options ? options.positionFunction : null;
  61707. var vtxfunc = options ? options.vertexFunction : null;
  61708. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  61709. // particles
  61710. var sp;
  61711. var currentCopy;
  61712. var idx = this.nbParticles;
  61713. for (var i = 0; i < nb; i++) {
  61714. var currentPos = this._positions.length;
  61715. var currentInd = this._indices.length;
  61716. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  61717. if (this._updatable) {
  61718. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  61719. sp.position.copyFrom(currentCopy.position);
  61720. sp.rotation.copyFrom(currentCopy.rotation);
  61721. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  61722. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  61723. }
  61724. if (currentCopy.color && sp.color) {
  61725. sp.color.copyFrom(currentCopy.color);
  61726. }
  61727. sp.scaling.copyFrom(currentCopy.scaling);
  61728. sp.uvs.copyFrom(currentCopy.uvs);
  61729. }
  61730. this._index += shape.length;
  61731. idx++;
  61732. }
  61733. this.nbParticles += nb;
  61734. this._shapeCounter++;
  61735. return this._shapeCounter - 1;
  61736. };
  61737. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  61738. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  61739. this._resetCopy();
  61740. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  61741. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  61742. }
  61743. if (this._copy.rotationQuaternion) {
  61744. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61745. }
  61746. else {
  61747. this._yaw = this._copy.rotation.y;
  61748. this._pitch = this._copy.rotation.x;
  61749. this._roll = this._copy.rotation.z;
  61750. this._quaternionRotationYPR();
  61751. }
  61752. this._quaternionToRotationMatrix();
  61753. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61754. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61755. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61756. if (this._copy.translateFromPivot) {
  61757. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61758. }
  61759. else {
  61760. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61761. }
  61762. this._shape = particle._model._shape;
  61763. for (var pt = 0; pt < this._shape.length; pt++) {
  61764. this._vertex.x = this._shape[pt].x;
  61765. this._vertex.y = this._shape[pt].y;
  61766. this._vertex.z = this._shape[pt].z;
  61767. if (particle._model._vertexFunction) {
  61768. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  61769. }
  61770. this._vertex.x *= this._copy.scaling.x;
  61771. this._vertex.y *= this._copy.scaling.y;
  61772. this._vertex.z *= this._copy.scaling.z;
  61773. this._vertex.x -= this._scaledPivot.x;
  61774. this._vertex.y -= this._scaledPivot.y;
  61775. this._vertex.z -= this._scaledPivot.z;
  61776. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61777. this._rotated.addInPlace(this._pivotBackTranslation);
  61778. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  61779. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  61780. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  61781. }
  61782. particle.position.x = 0.0;
  61783. particle.position.y = 0.0;
  61784. particle.position.z = 0.0;
  61785. particle.rotation.x = 0.0;
  61786. particle.rotation.y = 0.0;
  61787. particle.rotation.z = 0.0;
  61788. particle.rotationQuaternion = null;
  61789. particle.scaling.x = 1.0;
  61790. particle.scaling.y = 1.0;
  61791. particle.scaling.z = 1.0;
  61792. particle.uvs.x = 0.0;
  61793. particle.uvs.y = 0.0;
  61794. particle.uvs.z = 1.0;
  61795. particle.uvs.w = 1.0;
  61796. particle.pivot.x = 0.0;
  61797. particle.pivot.y = 0.0;
  61798. particle.pivot.z = 0.0;
  61799. particle.translateFromPivot = false;
  61800. particle.parentId = null;
  61801. };
  61802. /**
  61803. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  61804. * @returns the SPS.
  61805. */
  61806. SolidParticleSystem.prototype.rebuildMesh = function () {
  61807. for (var p = 0; p < this.particles.length; p++) {
  61808. this._rebuildParticle(this.particles[p]);
  61809. }
  61810. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61811. return this;
  61812. };
  61813. /**
  61814. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  61815. * This method calls `updateParticle()` for each particle of the SPS.
  61816. * For an animated SPS, it is usually called within the render loop.
  61817. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  61818. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  61819. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  61820. * @returns the SPS.
  61821. */
  61822. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  61823. if (start === void 0) { start = 0; }
  61824. if (end === void 0) { end = this.nbParticles - 1; }
  61825. if (update === void 0) { update = true; }
  61826. if (!this._updatable) {
  61827. return this;
  61828. }
  61829. // custom beforeUpdate
  61830. this.beforeUpdateParticles(start, end, update);
  61831. this._cam_axisX.x = 1.0;
  61832. this._cam_axisX.y = 0.0;
  61833. this._cam_axisX.z = 0.0;
  61834. this._cam_axisY.x = 0.0;
  61835. this._cam_axisY.y = 1.0;
  61836. this._cam_axisY.z = 0.0;
  61837. this._cam_axisZ.x = 0.0;
  61838. this._cam_axisZ.y = 0.0;
  61839. this._cam_axisZ.z = 1.0;
  61840. // cases when the World Matrix is to be computed first
  61841. if (this.billboard || this._depthSort) {
  61842. this.mesh.computeWorldMatrix(true);
  61843. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  61844. }
  61845. // if the particles will always face the camera
  61846. if (this.billboard) {
  61847. // compute the camera position and un-rotate it by the current mesh rotation
  61848. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  61849. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  61850. this._cam_axisZ.normalize();
  61851. // same for camera up vector extracted from the cam view matrix
  61852. var view = this._camera.getViewMatrix(true);
  61853. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  61854. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  61855. this._cam_axisY.normalize();
  61856. this._cam_axisX.normalize();
  61857. }
  61858. // if depthSort, compute the camera global position in the mesh local system
  61859. if (this._depthSort) {
  61860. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  61861. }
  61862. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  61863. var idx = 0; // current position index in the global array positions32
  61864. var index = 0; // position start index in the global array positions32 of the current particle
  61865. var colidx = 0; // current color index in the global array colors32
  61866. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  61867. var uvidx = 0; // current uv index in the global array uvs32
  61868. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  61869. var pt = 0; // current index in the particle model shape
  61870. if (this.mesh.isFacetDataEnabled) {
  61871. this._computeBoundingBox = true;
  61872. }
  61873. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  61874. if (this._computeBoundingBox) {
  61875. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  61876. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  61877. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  61878. }
  61879. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  61880. if (this.mesh._boundingInfo) {
  61881. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  61882. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  61883. }
  61884. }
  61885. }
  61886. // particle loop
  61887. index = this.particles[start]._pos;
  61888. var vpos = (index / 3) | 0;
  61889. colorIndex = vpos * 4;
  61890. uvIndex = vpos * 2;
  61891. for (var p = start; p <= end; p++) {
  61892. this._particle = this.particles[p];
  61893. this._shape = this._particle._model._shape;
  61894. this._shapeUV = this._particle._model._shapeUV;
  61895. // call to custom user function to update the particle properties
  61896. this.updateParticle(this._particle);
  61897. // camera-particle distance for depth sorting
  61898. if (this._depthSort && this._depthSortParticles) {
  61899. var dsp = this.depthSortedParticles[p];
  61900. dsp.ind = this._particle._ind;
  61901. dsp.indicesLength = this._particle._model._indicesLength;
  61902. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  61903. }
  61904. // skip the computations for inactive or already invisible particles
  61905. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  61906. // increment indexes for the next particle
  61907. pt = this._shape.length;
  61908. index += pt * 3;
  61909. colorIndex += pt * 4;
  61910. uvIndex += pt * 2;
  61911. continue;
  61912. }
  61913. if (this._particle.isVisible) {
  61914. this._particle._stillInvisible = false; // un-mark permanent invisibility
  61915. this._particleHasParent = (this._particle.parentId !== null);
  61916. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61917. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61918. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61919. // particle rotation matrix
  61920. if (this.billboard) {
  61921. this._particle.rotation.x = 0.0;
  61922. this._particle.rotation.y = 0.0;
  61923. }
  61924. if (this._computeParticleRotation || this.billboard) {
  61925. if (this._particle.rotationQuaternion) {
  61926. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61927. }
  61928. else {
  61929. this._yaw = this._particle.rotation.y;
  61930. this._pitch = this._particle.rotation.x;
  61931. this._roll = this._particle.rotation.z;
  61932. this._quaternionRotationYPR();
  61933. }
  61934. this._quaternionToRotationMatrix();
  61935. }
  61936. if (this._particleHasParent) {
  61937. this._parent = this.particles[this._particle.parentId];
  61938. 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];
  61939. 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];
  61940. 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];
  61941. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  61942. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  61943. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  61944. if (this._computeParticleRotation || this.billboard) {
  61945. 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];
  61946. 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];
  61947. 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];
  61948. 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];
  61949. 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];
  61950. 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];
  61951. 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];
  61952. 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];
  61953. 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];
  61954. }
  61955. }
  61956. else {
  61957. this._particle._globalPosition.x = this._particle.position.x;
  61958. this._particle._globalPosition.y = this._particle.position.y;
  61959. this._particle._globalPosition.z = this._particle.position.z;
  61960. if (this._computeParticleRotation || this.billboard) {
  61961. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  61962. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  61963. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  61964. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  61965. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  61966. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  61967. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  61968. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  61969. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  61970. }
  61971. }
  61972. if (this._particle.translateFromPivot) {
  61973. this._pivotBackTranslation.x = 0.0;
  61974. this._pivotBackTranslation.y = 0.0;
  61975. this._pivotBackTranslation.z = 0.0;
  61976. }
  61977. else {
  61978. this._pivotBackTranslation.x = this._scaledPivot.x;
  61979. this._pivotBackTranslation.y = this._scaledPivot.y;
  61980. this._pivotBackTranslation.z = this._scaledPivot.z;
  61981. }
  61982. // particle vertex loop
  61983. for (pt = 0; pt < this._shape.length; pt++) {
  61984. idx = index + pt * 3;
  61985. colidx = colorIndex + pt * 4;
  61986. uvidx = uvIndex + pt * 2;
  61987. this._vertex.x = this._shape[pt].x;
  61988. this._vertex.y = this._shape[pt].y;
  61989. this._vertex.z = this._shape[pt].z;
  61990. if (this._computeParticleVertex) {
  61991. this.updateParticleVertex(this._particle, this._vertex, pt);
  61992. }
  61993. // positions
  61994. this._vertex.x *= this._particle.scaling.x;
  61995. this._vertex.y *= this._particle.scaling.y;
  61996. this._vertex.z *= this._particle.scaling.z;
  61997. this._vertex.x -= this._scaledPivot.x;
  61998. this._vertex.y -= this._scaledPivot.y;
  61999. this._vertex.z -= this._scaledPivot.z;
  62000. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62001. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62002. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62003. this._rotated.x += this._pivotBackTranslation.x;
  62004. this._rotated.y += this._pivotBackTranslation.y;
  62005. this._rotated.z += this._pivotBackTranslation.z;
  62006. 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;
  62007. 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;
  62008. 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;
  62009. if (this._computeBoundingBox) {
  62010. if (this._positions32[idx] < this._minimum.x) {
  62011. this._minimum.x = this._positions32[idx];
  62012. }
  62013. if (this._positions32[idx] > this._maximum.x) {
  62014. this._maximum.x = this._positions32[idx];
  62015. }
  62016. if (this._positions32[idx + 1] < this._minimum.y) {
  62017. this._minimum.y = this._positions32[idx + 1];
  62018. }
  62019. if (this._positions32[idx + 1] > this._maximum.y) {
  62020. this._maximum.y = this._positions32[idx + 1];
  62021. }
  62022. if (this._positions32[idx + 2] < this._minimum.z) {
  62023. this._minimum.z = this._positions32[idx + 2];
  62024. }
  62025. if (this._positions32[idx + 2] > this._maximum.z) {
  62026. this._maximum.z = this._positions32[idx + 2];
  62027. }
  62028. }
  62029. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  62030. if (!this._computeParticleVertex) {
  62031. this._normal.x = this._fixedNormal32[idx];
  62032. this._normal.y = this._fixedNormal32[idx + 1];
  62033. this._normal.z = this._fixedNormal32[idx + 2];
  62034. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  62035. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  62036. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  62037. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  62038. 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;
  62039. 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;
  62040. }
  62041. if (this._computeParticleColor && this._particle.color) {
  62042. this._colors32[colidx] = this._particle.color.r;
  62043. this._colors32[colidx + 1] = this._particle.color.g;
  62044. this._colors32[colidx + 2] = this._particle.color.b;
  62045. this._colors32[colidx + 3] = this._particle.color.a;
  62046. }
  62047. if (this._computeParticleTexture) {
  62048. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62049. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62050. }
  62051. }
  62052. }
  62053. // particle just set invisible : scaled to zero and positioned at the origin
  62054. else {
  62055. this._particle._stillInvisible = true; // mark the particle as invisible
  62056. for (pt = 0; pt < this._shape.length; pt++) {
  62057. idx = index + pt * 3;
  62058. colidx = colorIndex + pt * 4;
  62059. uvidx = uvIndex + pt * 2;
  62060. this._positions32[idx] = 0.0;
  62061. this._positions32[idx + 1] = 0.0;
  62062. this._positions32[idx + 2] = 0.0;
  62063. this._normals32[idx] = 0.0;
  62064. this._normals32[idx + 1] = 0.0;
  62065. this._normals32[idx + 2] = 0.0;
  62066. if (this._computeParticleColor && this._particle.color) {
  62067. this._colors32[colidx] = this._particle.color.r;
  62068. this._colors32[colidx + 1] = this._particle.color.g;
  62069. this._colors32[colidx + 2] = this._particle.color.b;
  62070. this._colors32[colidx + 3] = this._particle.color.a;
  62071. }
  62072. if (this._computeParticleTexture) {
  62073. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62074. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62075. }
  62076. }
  62077. }
  62078. // if the particle intersections must be computed : update the bbInfo
  62079. if (this._particlesIntersect) {
  62080. var bInfo = this._particle._boundingInfo;
  62081. var bBox = bInfo.boundingBox;
  62082. var bSphere = bInfo.boundingSphere;
  62083. if (!this._bSphereOnly) {
  62084. // place, scale and rotate the particle bbox within the SPS local system, then update it
  62085. for (var b = 0; b < bBox.vectors.length; b++) {
  62086. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  62087. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  62088. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  62089. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62090. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62091. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62092. 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;
  62093. 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;
  62094. 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;
  62095. }
  62096. bBox._update(this.mesh._worldMatrix);
  62097. }
  62098. // place and scale the particle bouding sphere in the SPS local system, then update it
  62099. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  62100. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  62101. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  62102. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  62103. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  62104. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  62105. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  62106. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  62107. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  62108. 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));
  62109. bSphere._update(this.mesh._worldMatrix);
  62110. }
  62111. // increment indexes for the next particle
  62112. index = idx + 3;
  62113. colorIndex = colidx + 4;
  62114. uvIndex = uvidx + 2;
  62115. }
  62116. // if the VBO must be updated
  62117. if (update) {
  62118. if (this._computeParticleColor) {
  62119. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  62120. }
  62121. if (this._computeParticleTexture) {
  62122. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  62123. }
  62124. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62125. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  62126. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  62127. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  62128. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  62129. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  62130. for (var i = 0; i < this._normals32.length; i++) {
  62131. this._fixedNormal32[i] = this._normals32[i];
  62132. }
  62133. }
  62134. if (!this.mesh.areNormalsFrozen) {
  62135. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  62136. }
  62137. }
  62138. if (this._depthSort && this._depthSortParticles) {
  62139. this.depthSortedParticles.sort(this._depthSortFunction);
  62140. var dspl = this.depthSortedParticles.length;
  62141. var sorted = 0;
  62142. var lind = 0;
  62143. var sind = 0;
  62144. var sid = 0;
  62145. for (sorted = 0; sorted < dspl; sorted++) {
  62146. lind = this.depthSortedParticles[sorted].indicesLength;
  62147. sind = this.depthSortedParticles[sorted].ind;
  62148. for (var i = 0; i < lind; i++) {
  62149. this._indices32[sid] = this._indices[sind + i];
  62150. sid++;
  62151. }
  62152. }
  62153. this.mesh.updateIndices(this._indices32);
  62154. }
  62155. }
  62156. if (this._computeBoundingBox) {
  62157. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  62158. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  62159. }
  62160. this.afterUpdateParticles(start, end, update);
  62161. return this;
  62162. };
  62163. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  62164. this._halfroll = this._roll * 0.5;
  62165. this._halfpitch = this._pitch * 0.5;
  62166. this._halfyaw = this._yaw * 0.5;
  62167. this._sinRoll = Math.sin(this._halfroll);
  62168. this._cosRoll = Math.cos(this._halfroll);
  62169. this._sinPitch = Math.sin(this._halfpitch);
  62170. this._cosPitch = Math.cos(this._halfpitch);
  62171. this._sinYaw = Math.sin(this._halfyaw);
  62172. this._cosYaw = Math.cos(this._halfyaw);
  62173. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  62174. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  62175. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  62176. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  62177. };
  62178. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  62179. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  62180. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  62181. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  62182. this._rotMatrix.m[3] = 0;
  62183. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  62184. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  62185. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  62186. this._rotMatrix.m[7] = 0;
  62187. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  62188. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  62189. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  62190. this._rotMatrix.m[11] = 0;
  62191. this._rotMatrix.m[12] = 0;
  62192. this._rotMatrix.m[13] = 0;
  62193. this._rotMatrix.m[14] = 0;
  62194. this._rotMatrix.m[15] = 1.0;
  62195. };
  62196. /**
  62197. * Disposes the SPS.
  62198. */
  62199. SolidParticleSystem.prototype.dispose = function () {
  62200. this.mesh.dispose();
  62201. this.vars = null;
  62202. // drop references to internal big arrays for the GC
  62203. this._positions = null;
  62204. this._indices = null;
  62205. this._normals = null;
  62206. this._uvs = null;
  62207. this._colors = null;
  62208. this._indices32 = null;
  62209. this._positions32 = null;
  62210. this._normals32 = null;
  62211. this._fixedNormal32 = null;
  62212. this._uvs32 = null;
  62213. this._colors32 = null;
  62214. this.pickedParticles = null;
  62215. };
  62216. /**
  62217. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  62218. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62219. * @returns the SPS.
  62220. */
  62221. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  62222. if (!this._isVisibilityBoxLocked) {
  62223. this.mesh.refreshBoundingInfo();
  62224. }
  62225. return this;
  62226. };
  62227. /**
  62228. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  62229. * @param size the size (float) of the visibility box
  62230. * note : this doesn't lock the SPS mesh bounding box.
  62231. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62232. */
  62233. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  62234. var vis = size / 2;
  62235. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  62236. };
  62237. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  62238. /**
  62239. * Gets whether the SPS as always visible or not
  62240. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62241. */
  62242. get: function () {
  62243. return this._alwaysVisible;
  62244. },
  62245. /**
  62246. * Sets the SPS as always visible or not
  62247. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62248. */
  62249. set: function (val) {
  62250. this._alwaysVisible = val;
  62251. this.mesh.alwaysSelectAsActiveMesh = val;
  62252. },
  62253. enumerable: true,
  62254. configurable: true
  62255. });
  62256. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  62257. /**
  62258. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62259. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62260. */
  62261. get: function () {
  62262. return this._isVisibilityBoxLocked;
  62263. },
  62264. /**
  62265. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62266. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62267. */
  62268. set: function (val) {
  62269. this._isVisibilityBoxLocked = val;
  62270. var boundingInfo = this.mesh.getBoundingInfo();
  62271. boundingInfo.isLocked = val;
  62272. },
  62273. enumerable: true,
  62274. configurable: true
  62275. });
  62276. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  62277. /**
  62278. * Gets if `setParticles()` computes the particle rotations or not.
  62279. * Default value : true. The SPS is faster when it's set to false.
  62280. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62281. */
  62282. get: function () {
  62283. return this._computeParticleRotation;
  62284. },
  62285. /**
  62286. * Tells to `setParticles()` to compute the particle rotations or not.
  62287. * Default value : true. The SPS is faster when it's set to false.
  62288. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62289. */
  62290. set: function (val) {
  62291. this._computeParticleRotation = val;
  62292. },
  62293. enumerable: true,
  62294. configurable: true
  62295. });
  62296. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  62297. /**
  62298. * Gets if `setParticles()` computes the particle colors or not.
  62299. * Default value : true. The SPS is faster when it's set to false.
  62300. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  62301. */
  62302. get: function () {
  62303. return this._computeParticleColor;
  62304. },
  62305. /**
  62306. * Tells to `setParticles()` to compute the particle colors or not.
  62307. * Default value : true. The SPS is faster when it's set to false.
  62308. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  62309. */
  62310. set: function (val) {
  62311. this._computeParticleColor = val;
  62312. },
  62313. enumerable: true,
  62314. configurable: true
  62315. });
  62316. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  62317. /**
  62318. * Gets if `setParticles()` computes the particle textures or not.
  62319. * Default value : true. The SPS is faster when it's set to false.
  62320. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  62321. */
  62322. get: function () {
  62323. return this._computeParticleTexture;
  62324. },
  62325. set: function (val) {
  62326. this._computeParticleTexture = val;
  62327. },
  62328. enumerable: true,
  62329. configurable: true
  62330. });
  62331. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  62332. /**
  62333. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  62334. * Default value : false. The SPS is faster when it's set to false.
  62335. * Note : the particle custom vertex positions aren't stored values.
  62336. */
  62337. get: function () {
  62338. return this._computeParticleVertex;
  62339. },
  62340. /**
  62341. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  62342. * Default value : false. The SPS is faster when it's set to false.
  62343. * Note : the particle custom vertex positions aren't stored values.
  62344. */
  62345. set: function (val) {
  62346. this._computeParticleVertex = val;
  62347. },
  62348. enumerable: true,
  62349. configurable: true
  62350. });
  62351. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  62352. /**
  62353. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  62354. */
  62355. get: function () {
  62356. return this._computeBoundingBox;
  62357. },
  62358. /**
  62359. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  62360. */
  62361. set: function (val) {
  62362. this._computeBoundingBox = val;
  62363. },
  62364. enumerable: true,
  62365. configurable: true
  62366. });
  62367. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  62368. /**
  62369. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  62370. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62371. * Default : `true`
  62372. */
  62373. get: function () {
  62374. return this._depthSortParticles;
  62375. },
  62376. /**
  62377. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  62378. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62379. * Default : `true`
  62380. */
  62381. set: function (val) {
  62382. this._depthSortParticles = val;
  62383. },
  62384. enumerable: true,
  62385. configurable: true
  62386. });
  62387. // =======================================================================
  62388. // Particle behavior logic
  62389. // these following methods may be overwritten by the user to fit his needs
  62390. /**
  62391. * This function does nothing. It may be overwritten to set all the particle first values.
  62392. * The SPS doesn't call this function, you may have to call it by your own.
  62393. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62394. */
  62395. SolidParticleSystem.prototype.initParticles = function () {
  62396. };
  62397. /**
  62398. * This function does nothing. It may be overwritten to recycle a particle.
  62399. * The SPS doesn't call this function, you may have to call it by your own.
  62400. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62401. * @param particle The particle to recycle
  62402. * @returns the recycled particle
  62403. */
  62404. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  62405. return particle;
  62406. };
  62407. /**
  62408. * Updates a particle : this function should be overwritten by the user.
  62409. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  62410. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62411. * @example : just set a particle position or velocity and recycle conditions
  62412. * @param particle The particle to update
  62413. * @returns the updated particle
  62414. */
  62415. SolidParticleSystem.prototype.updateParticle = function (particle) {
  62416. return particle;
  62417. };
  62418. /**
  62419. * Updates a vertex of a particle : it can be overwritten by the user.
  62420. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  62421. * @param particle the current particle
  62422. * @param vertex the current index of the current particle
  62423. * @param pt the index of the current vertex in the particle shape
  62424. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  62425. * @example : just set a vertex particle position
  62426. * @returns the updated vertex
  62427. */
  62428. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  62429. return vertex;
  62430. };
  62431. /**
  62432. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  62433. * This does nothing and may be overwritten by the user.
  62434. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62435. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62436. * @param update the boolean update value actually passed to setParticles()
  62437. */
  62438. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  62439. };
  62440. /**
  62441. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  62442. * This will be passed three parameters.
  62443. * This does nothing and may be overwritten by the user.
  62444. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62445. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62446. * @param update the boolean update value actually passed to setParticles()
  62447. */
  62448. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  62449. };
  62450. return SolidParticleSystem;
  62451. }());
  62452. BABYLON.SolidParticleSystem = SolidParticleSystem;
  62453. })(BABYLON || (BABYLON = {}));
  62454. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  62455. var BABYLON;
  62456. (function (BABYLON) {
  62457. /**
  62458. * Class containing static functions to help procedurally build meshes
  62459. */
  62460. var MeshBuilder = /** @class */ (function () {
  62461. function MeshBuilder() {
  62462. }
  62463. MeshBuilder.updateSideOrientation = function (orientation) {
  62464. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  62465. return BABYLON.Mesh.DOUBLESIDE;
  62466. }
  62467. if (orientation === undefined || orientation === null) {
  62468. return BABYLON.Mesh.FRONTSIDE;
  62469. }
  62470. return orientation;
  62471. };
  62472. /**
  62473. * Creates a box mesh
  62474. * * The parameter `size` sets the size (float) of each box side (default 1)
  62475. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  62476. * * 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)
  62477. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62478. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62479. * * 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
  62480. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62481. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  62482. * @param name defines the name of the mesh
  62483. * @param options defines the options used to create the mesh
  62484. * @param scene defines the hosting scene
  62485. * @returns the box mesh
  62486. */
  62487. MeshBuilder.CreateBox = function (name, options, scene) {
  62488. if (scene === void 0) { scene = null; }
  62489. var box = new BABYLON.Mesh(name, scene);
  62490. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62491. box._originalBuilderSideOrientation = options.sideOrientation;
  62492. var vertexData = BABYLON.VertexData.CreateBox(options);
  62493. vertexData.applyToMesh(box, options.updatable);
  62494. return box;
  62495. };
  62496. /**
  62497. * Creates a sphere mesh
  62498. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  62499. * * 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`)
  62500. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  62501. * * 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
  62502. * * 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)
  62503. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62504. * * 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
  62505. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62506. * @param name defines the name of the mesh
  62507. * @param options defines the options used to create the mesh
  62508. * @param scene defines the hosting scene
  62509. * @returns the sphere mesh
  62510. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  62511. */
  62512. MeshBuilder.CreateSphere = function (name, options, scene) {
  62513. var sphere = new BABYLON.Mesh(name, scene);
  62514. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62515. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62516. var vertexData = BABYLON.VertexData.CreateSphere(options);
  62517. vertexData.applyToMesh(sphere, options.updatable);
  62518. return sphere;
  62519. };
  62520. /**
  62521. * Creates a plane polygonal mesh. By default, this is a disc
  62522. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  62523. * * 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
  62524. * * 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
  62525. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62526. * * 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
  62527. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62528. * @param name defines the name of the mesh
  62529. * @param options defines the options used to create the mesh
  62530. * @param scene defines the hosting scene
  62531. * @returns the plane polygonal mesh
  62532. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  62533. */
  62534. MeshBuilder.CreateDisc = function (name, options, scene) {
  62535. if (scene === void 0) { scene = null; }
  62536. var disc = new BABYLON.Mesh(name, scene);
  62537. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62538. disc._originalBuilderSideOrientation = options.sideOrientation;
  62539. var vertexData = BABYLON.VertexData.CreateDisc(options);
  62540. vertexData.applyToMesh(disc, options.updatable);
  62541. return disc;
  62542. };
  62543. /**
  62544. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  62545. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  62546. * * 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`)
  62547. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  62548. * * 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
  62549. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62550. * * 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
  62551. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62552. * @param name defines the name of the mesh
  62553. * @param options defines the options used to create the mesh
  62554. * @param scene defines the hosting scene
  62555. * @returns the icosahedron mesh
  62556. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  62557. */
  62558. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  62559. var sphere = new BABYLON.Mesh(name, scene);
  62560. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62561. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62562. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  62563. vertexData.applyToMesh(sphere, options.updatable);
  62564. return sphere;
  62565. };
  62566. ;
  62567. /**
  62568. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62569. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  62570. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  62571. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  62572. * * 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
  62573. * * 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
  62574. * * 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
  62575. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62576. * * 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
  62577. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62578. * * 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
  62579. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  62580. * * 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
  62581. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  62582. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62583. * @param name defines the name of the mesh
  62584. * @param options defines the options used to create the mesh
  62585. * @param scene defines the hosting scene
  62586. * @returns the ribbon mesh
  62587. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  62588. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62589. */
  62590. MeshBuilder.CreateRibbon = function (name, options, scene) {
  62591. if (scene === void 0) { scene = null; }
  62592. var pathArray = options.pathArray;
  62593. var closeArray = options.closeArray;
  62594. var closePath = options.closePath;
  62595. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62596. var instance = options.instance;
  62597. var updatable = options.updatable;
  62598. if (instance) { // existing ribbon instance update
  62599. // positionFunction : ribbon case
  62600. // only pathArray and sideOrientation parameters are taken into account for positions update
  62601. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  62602. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  62603. var positionFunction = function (positions) {
  62604. var minlg = pathArray[0].length;
  62605. var i = 0;
  62606. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  62607. for (var si = 1; si <= ns; si++) {
  62608. for (var p = 0; p < pathArray.length; p++) {
  62609. var path = pathArray[p];
  62610. var l = path.length;
  62611. minlg = (minlg < l) ? minlg : l;
  62612. var j = 0;
  62613. while (j < minlg) {
  62614. positions[i] = path[j].x;
  62615. positions[i + 1] = path[j].y;
  62616. positions[i + 2] = path[j].z;
  62617. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  62618. BABYLON.Tmp.Vector3[0].x = path[j].x;
  62619. }
  62620. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  62621. BABYLON.Tmp.Vector3[1].x = path[j].x;
  62622. }
  62623. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  62624. BABYLON.Tmp.Vector3[0].y = path[j].y;
  62625. }
  62626. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  62627. BABYLON.Tmp.Vector3[1].y = path[j].y;
  62628. }
  62629. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  62630. BABYLON.Tmp.Vector3[0].z = path[j].z;
  62631. }
  62632. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  62633. BABYLON.Tmp.Vector3[1].z = path[j].z;
  62634. }
  62635. j++;
  62636. i += 3;
  62637. }
  62638. if (instance._closePath) {
  62639. positions[i] = path[0].x;
  62640. positions[i + 1] = path[0].y;
  62641. positions[i + 2] = path[0].z;
  62642. i += 3;
  62643. }
  62644. }
  62645. }
  62646. };
  62647. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62648. positionFunction(positions);
  62649. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  62650. instance._boundingInfo.update(instance._worldMatrix);
  62651. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62652. if (options.colors) {
  62653. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62654. for (var c = 0; c < options.colors.length; c++) {
  62655. colors[c * 4] = options.colors[c].r;
  62656. colors[c * 4 + 1] = options.colors[c].g;
  62657. colors[c * 4 + 2] = options.colors[c].b;
  62658. colors[c * 4 + 3] = options.colors[c].a;
  62659. }
  62660. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  62661. }
  62662. if (options.uvs) {
  62663. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62664. for (var i = 0; i < options.uvs.length; i++) {
  62665. uvs[i * 2] = options.uvs[i].x;
  62666. uvs[i * 2 + 1] = options.uvs[i].y;
  62667. }
  62668. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  62669. }
  62670. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  62671. var indices = instance.getIndices();
  62672. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62673. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  62674. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  62675. if (instance._closePath) {
  62676. var indexFirst = 0;
  62677. var indexLast = 0;
  62678. for (var p = 0; p < pathArray.length; p++) {
  62679. indexFirst = instance._idx[p] * 3;
  62680. if (p + 1 < pathArray.length) {
  62681. indexLast = (instance._idx[p + 1] - 1) * 3;
  62682. }
  62683. else {
  62684. indexLast = normals.length - 3;
  62685. }
  62686. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  62687. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  62688. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  62689. normals[indexLast] = normals[indexFirst];
  62690. normals[indexLast + 1] = normals[indexFirst + 1];
  62691. normals[indexLast + 2] = normals[indexFirst + 2];
  62692. }
  62693. }
  62694. if (!(instance.areNormalsFrozen)) {
  62695. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  62696. }
  62697. }
  62698. return instance;
  62699. }
  62700. else { // new ribbon creation
  62701. var ribbon = new BABYLON.Mesh(name, scene);
  62702. ribbon._originalBuilderSideOrientation = sideOrientation;
  62703. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  62704. if (closePath) {
  62705. ribbon._idx = vertexData._idx;
  62706. }
  62707. ribbon._closePath = closePath;
  62708. ribbon._closeArray = closeArray;
  62709. vertexData.applyToMesh(ribbon, updatable);
  62710. return ribbon;
  62711. }
  62712. };
  62713. /**
  62714. * Creates a cylinder or a cone mesh
  62715. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  62716. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  62717. * * 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.
  62718. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  62719. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  62720. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  62721. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  62722. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  62723. * * 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).
  62724. * * 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
  62725. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  62726. * * 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
  62727. * * 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.
  62728. * * If `enclose` is false, a ring surface is one element.
  62729. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  62730. * * 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
  62731. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62732. * * 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
  62733. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62734. * @param name defines the name of the mesh
  62735. * @param options defines the options used to create the mesh
  62736. * @param scene defines the hosting scene
  62737. * @returns the cylinder mesh
  62738. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  62739. */
  62740. MeshBuilder.CreateCylinder = function (name, options, scene) {
  62741. var cylinder = new BABYLON.Mesh(name, scene);
  62742. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62743. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  62744. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  62745. vertexData.applyToMesh(cylinder, options.updatable);
  62746. return cylinder;
  62747. };
  62748. /**
  62749. * Creates a torus mesh
  62750. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  62751. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  62752. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  62753. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62754. * * 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
  62755. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62756. * @param name defines the name of the mesh
  62757. * @param options defines the options used to create the mesh
  62758. * @param scene defines the hosting scene
  62759. * @returns the torus mesh
  62760. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  62761. */
  62762. MeshBuilder.CreateTorus = function (name, options, scene) {
  62763. var torus = new BABYLON.Mesh(name, scene);
  62764. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62765. torus._originalBuilderSideOrientation = options.sideOrientation;
  62766. var vertexData = BABYLON.VertexData.CreateTorus(options);
  62767. vertexData.applyToMesh(torus, options.updatable);
  62768. return torus;
  62769. };
  62770. /**
  62771. * Creates a torus knot mesh
  62772. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  62773. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  62774. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  62775. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  62776. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62777. * * 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
  62778. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62779. * @param name defines the name of the mesh
  62780. * @param options defines the options used to create the mesh
  62781. * @param scene defines the hosting scene
  62782. * @returns the torus knot mesh
  62783. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  62784. */
  62785. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  62786. var torusKnot = new BABYLON.Mesh(name, scene);
  62787. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62788. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  62789. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  62790. vertexData.applyToMesh(torusKnot, options.updatable);
  62791. return torusKnot;
  62792. };
  62793. /**
  62794. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  62795. * * 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
  62796. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  62797. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  62798. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  62799. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  62800. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  62801. * * 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
  62802. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  62803. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62804. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  62805. * @param name defines the name of the new line system
  62806. * @param options defines the options used to create the line system
  62807. * @param scene defines the hosting scene
  62808. * @returns a new line system mesh
  62809. */
  62810. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  62811. var instance = options.instance;
  62812. var lines = options.lines;
  62813. var colors = options.colors;
  62814. if (instance) { // lines update
  62815. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62816. var vertexColor;
  62817. var lineColors;
  62818. if (colors) {
  62819. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62820. }
  62821. var i = 0;
  62822. var c = 0;
  62823. for (var l = 0; l < lines.length; l++) {
  62824. var points = lines[l];
  62825. for (var p = 0; p < points.length; p++) {
  62826. positions[i] = points[p].x;
  62827. positions[i + 1] = points[p].y;
  62828. positions[i + 2] = points[p].z;
  62829. if (colors && vertexColor) {
  62830. lineColors = colors[l];
  62831. vertexColor[c] = lineColors[p].r;
  62832. vertexColor[c + 1] = lineColors[p].g;
  62833. vertexColor[c + 2] = lineColors[p].b;
  62834. vertexColor[c + 3] = lineColors[p].a;
  62835. c += 4;
  62836. }
  62837. i += 3;
  62838. }
  62839. }
  62840. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62841. if (colors && vertexColor) {
  62842. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  62843. }
  62844. return instance;
  62845. }
  62846. // line system creation
  62847. var useVertexColor = (colors) ? true : false;
  62848. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  62849. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  62850. vertexData.applyToMesh(lineSystem, options.updatable);
  62851. return lineSystem;
  62852. };
  62853. /**
  62854. * Creates a line mesh
  62855. * 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
  62856. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62857. * * The parameter `points` is an array successive Vector3
  62858. * * 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
  62859. * * The optional parameter `colors` is an array of successive Color4, one per line point
  62860. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  62861. * * When updating an instance, remember that only point positions can change, not the number of points
  62862. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62863. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  62864. * @param name defines the name of the new line system
  62865. * @param options defines the options used to create the line system
  62866. * @param scene defines the hosting scene
  62867. * @returns a new line mesh
  62868. */
  62869. MeshBuilder.CreateLines = function (name, options, scene) {
  62870. if (scene === void 0) { scene = null; }
  62871. var colors = (options.colors) ? [options.colors] : null;
  62872. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  62873. return lines;
  62874. };
  62875. /**
  62876. * Creates a dashed line mesh
  62877. * * 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
  62878. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62879. * * The parameter `points` is an array successive Vector3
  62880. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  62881. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  62882. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  62883. * * 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
  62884. * * When updating an instance, remember that only point positions can change, not the number of points
  62885. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62886. * @param name defines the name of the mesh
  62887. * @param options defines the options used to create the mesh
  62888. * @param scene defines the hosting scene
  62889. * @returns the dashed line mesh
  62890. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  62891. */
  62892. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  62893. if (scene === void 0) { scene = null; }
  62894. var points = options.points;
  62895. var instance = options.instance;
  62896. var gapSize = options.gapSize || 1;
  62897. var dashSize = options.dashSize || 3;
  62898. if (instance) { // dashed lines update
  62899. var positionFunction = function (positions) {
  62900. var curvect = BABYLON.Vector3.Zero();
  62901. var nbSeg = positions.length / 6;
  62902. var lg = 0;
  62903. var nb = 0;
  62904. var shft = 0;
  62905. var dashshft = 0;
  62906. var curshft = 0;
  62907. var p = 0;
  62908. var i = 0;
  62909. var j = 0;
  62910. for (i = 0; i < points.length - 1; i++) {
  62911. points[i + 1].subtractToRef(points[i], curvect);
  62912. lg += curvect.length();
  62913. }
  62914. shft = lg / nbSeg;
  62915. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  62916. for (i = 0; i < points.length - 1; i++) {
  62917. points[i + 1].subtractToRef(points[i], curvect);
  62918. nb = Math.floor(curvect.length() / shft);
  62919. curvect.normalize();
  62920. j = 0;
  62921. while (j < nb && p < positions.length) {
  62922. curshft = shft * j;
  62923. positions[p] = points[i].x + curshft * curvect.x;
  62924. positions[p + 1] = points[i].y + curshft * curvect.y;
  62925. positions[p + 2] = points[i].z + curshft * curvect.z;
  62926. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  62927. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  62928. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  62929. p += 6;
  62930. j++;
  62931. }
  62932. }
  62933. while (p < positions.length) {
  62934. positions[p] = points[i].x;
  62935. positions[p + 1] = points[i].y;
  62936. positions[p + 2] = points[i].z;
  62937. p += 3;
  62938. }
  62939. };
  62940. instance.updateMeshPositions(positionFunction, false);
  62941. return instance;
  62942. }
  62943. // dashed lines creation
  62944. var dashedLines = new BABYLON.LinesMesh(name, scene);
  62945. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  62946. vertexData.applyToMesh(dashedLines, options.updatable);
  62947. dashedLines.dashSize = dashSize;
  62948. dashedLines.gapSize = gapSize;
  62949. return dashedLines;
  62950. };
  62951. /**
  62952. * 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.
  62953. * * 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.
  62954. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62955. * * 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.
  62956. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  62957. * * 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
  62958. * * 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
  62959. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  62960. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62961. * * 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
  62962. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  62963. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62964. * @param name defines the name of the mesh
  62965. * @param options defines the options used to create the mesh
  62966. * @param scene defines the hosting scene
  62967. * @returns the extruded shape mesh
  62968. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62969. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62970. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62971. */
  62972. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  62973. if (scene === void 0) { scene = null; }
  62974. var path = options.path;
  62975. var shape = options.shape;
  62976. var scale = options.scale || 1;
  62977. var rotation = options.rotation || 0;
  62978. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62979. var updatable = options.updatable;
  62980. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62981. var instance = options.instance || null;
  62982. var invertUV = options.invertUV || false;
  62983. 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);
  62984. };
  62985. /**
  62986. * Creates an custom extruded shape mesh.
  62987. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  62988. * * 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.
  62989. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62990. * * 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
  62991. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  62992. * * 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
  62993. * * It must returns a float value that will be the scale value applied to the shape on each path point
  62994. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  62995. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  62996. * * 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
  62997. * * 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
  62998. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  62999. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63000. * * 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
  63001. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63002. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63003. * @param name defines the name of the mesh
  63004. * @param options defines the options used to create the mesh
  63005. * @param scene defines the hosting scene
  63006. * @returns the custom extruded shape mesh
  63007. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  63008. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63009. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63010. */
  63011. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  63012. var path = options.path;
  63013. var shape = options.shape;
  63014. var scaleFunction = options.scaleFunction || (function () { return 1; });
  63015. var rotationFunction = options.rotationFunction || (function () { return 0; });
  63016. var ribbonCloseArray = options.ribbonCloseArray || false;
  63017. var ribbonClosePath = options.ribbonClosePath || false;
  63018. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63019. var updatable = options.updatable;
  63020. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63021. var instance = options.instance;
  63022. var invertUV = options.invertUV || false;
  63023. 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);
  63024. };
  63025. /**
  63026. * Creates lathe mesh.
  63027. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  63028. * * 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
  63029. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  63030. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  63031. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  63032. * * 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
  63033. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  63034. * * 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
  63035. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63036. * * 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
  63037. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63038. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63039. * @param name defines the name of the mesh
  63040. * @param options defines the options used to create the mesh
  63041. * @param scene defines the hosting scene
  63042. * @returns the lathe mesh
  63043. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  63044. */
  63045. MeshBuilder.CreateLathe = function (name, options, scene) {
  63046. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  63047. var closed = (options.closed === undefined) ? true : options.closed;
  63048. var shape = options.shape;
  63049. var radius = options.radius || 1;
  63050. var tessellation = options.tessellation || 64;
  63051. var clip = options.clip || 0;
  63052. var updatable = options.updatable;
  63053. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63054. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63055. var pi2 = Math.PI * 2;
  63056. var paths = new Array();
  63057. var invertUV = options.invertUV || false;
  63058. var i = 0;
  63059. var p = 0;
  63060. var step = pi2 / tessellation * arc;
  63061. var rotated;
  63062. var path = new Array();
  63063. for (i = 0; i <= tessellation - clip; i++) {
  63064. var path = [];
  63065. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  63066. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  63067. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  63068. }
  63069. for (p = 0; p < shape.length; p++) {
  63070. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  63071. path.push(rotated);
  63072. }
  63073. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  63074. 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));
  63075. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  63076. }
  63077. paths.push(path);
  63078. }
  63079. // lathe ribbon
  63080. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63081. return lathe;
  63082. };
  63083. /**
  63084. * Creates a plane mesh
  63085. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  63086. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  63087. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  63088. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63089. * * 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
  63090. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63091. * @param name defines the name of the mesh
  63092. * @param options defines the options used to create the mesh
  63093. * @param scene defines the hosting scene
  63094. * @returns the plane mesh
  63095. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63096. */
  63097. MeshBuilder.CreatePlane = function (name, options, scene) {
  63098. var plane = new BABYLON.Mesh(name, scene);
  63099. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63100. plane._originalBuilderSideOrientation = options.sideOrientation;
  63101. var vertexData = BABYLON.VertexData.CreatePlane(options);
  63102. vertexData.applyToMesh(plane, options.updatable);
  63103. if (options.sourcePlane) {
  63104. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  63105. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  63106. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  63107. plane.rotate(vectorProduct, product);
  63108. }
  63109. return plane;
  63110. };
  63111. /**
  63112. * Creates a ground mesh
  63113. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  63114. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  63115. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63116. * @param name defines the name of the mesh
  63117. * @param options defines the options used to create the mesh
  63118. * @param scene defines the hosting scene
  63119. * @returns the ground mesh
  63120. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63121. */
  63122. MeshBuilder.CreateGround = function (name, options, scene) {
  63123. var ground = new BABYLON.GroundMesh(name, scene);
  63124. ground._setReady(false);
  63125. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  63126. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  63127. ground._width = options.width || 1;
  63128. ground._height = options.height || 1;
  63129. ground._maxX = ground._width / 2;
  63130. ground._maxZ = ground._height / 2;
  63131. ground._minX = -ground._maxX;
  63132. ground._minZ = -ground._maxZ;
  63133. var vertexData = BABYLON.VertexData.CreateGround(options);
  63134. vertexData.applyToMesh(ground, options.updatable);
  63135. ground._setReady(true);
  63136. return ground;
  63137. };
  63138. /**
  63139. * Creates a tiled ground mesh
  63140. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  63141. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  63142. * * 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
  63143. * * 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
  63144. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63145. * @param name defines the name of the mesh
  63146. * @param options defines the options used to create the mesh
  63147. * @param scene defines the hosting scene
  63148. * @returns the tiled ground mesh
  63149. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  63150. */
  63151. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  63152. var tiledGround = new BABYLON.Mesh(name, scene);
  63153. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  63154. vertexData.applyToMesh(tiledGround, options.updatable);
  63155. return tiledGround;
  63156. };
  63157. /**
  63158. * Creates a ground mesh from a height map
  63159. * * The parameter `url` sets the URL of the height map image resource.
  63160. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  63161. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  63162. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  63163. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  63164. * * 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.
  63165. * * 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).
  63166. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63167. * @param name defines the name of the mesh
  63168. * @param url defines the url to the height map
  63169. * @param options defines the options used to create the mesh
  63170. * @param scene defines the hosting scene
  63171. * @returns the ground mesh
  63172. * @see http://doc.babylonjs.com/babylon101/height_map
  63173. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  63174. */
  63175. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  63176. var width = options.width || 10.0;
  63177. var height = options.height || 10.0;
  63178. var subdivisions = options.subdivisions || 1 | 0;
  63179. var minHeight = options.minHeight || 0.0;
  63180. var maxHeight = options.maxHeight || 1.0;
  63181. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  63182. var updatable = options.updatable;
  63183. var onReady = options.onReady;
  63184. var ground = new BABYLON.GroundMesh(name, scene);
  63185. ground._subdivisionsX = subdivisions;
  63186. ground._subdivisionsY = subdivisions;
  63187. ground._width = width;
  63188. ground._height = height;
  63189. ground._maxX = ground._width / 2.0;
  63190. ground._maxZ = ground._height / 2.0;
  63191. ground._minX = -ground._maxX;
  63192. ground._minZ = -ground._maxZ;
  63193. ground._setReady(false);
  63194. var onload = function (img) {
  63195. // Getting height map data
  63196. var canvas = document.createElement("canvas");
  63197. var context = canvas.getContext("2d");
  63198. if (!context) {
  63199. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  63200. }
  63201. if (scene.isDisposed) {
  63202. return;
  63203. }
  63204. var bufferWidth = img.width;
  63205. var bufferHeight = img.height;
  63206. canvas.width = bufferWidth;
  63207. canvas.height = bufferHeight;
  63208. context.drawImage(img, 0, 0);
  63209. // Create VertexData from map data
  63210. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  63211. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  63212. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  63213. width: width, height: height,
  63214. subdivisions: subdivisions,
  63215. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  63216. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  63217. });
  63218. vertexData.applyToMesh(ground, updatable);
  63219. //execute ready callback, if set
  63220. if (onReady) {
  63221. onReady(ground);
  63222. }
  63223. ground._setReady(true);
  63224. };
  63225. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  63226. return ground;
  63227. };
  63228. /**
  63229. * Creates a polygon mesh
  63230. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  63231. * * 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
  63232. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63233. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63234. * * 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)
  63235. * * Remember you can only change the shape positions, not their number when updating a polygon
  63236. * @param name defines the name of the mesh
  63237. * @param options defines the options used to create the mesh
  63238. * @param scene defines the hosting scene
  63239. * @returns the polygon mesh
  63240. */
  63241. MeshBuilder.CreatePolygon = function (name, options, scene) {
  63242. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63243. var shape = options.shape;
  63244. var holes = options.holes || [];
  63245. var depth = options.depth || 0;
  63246. var contours = [];
  63247. var hole = [];
  63248. for (var i = 0; i < shape.length; i++) {
  63249. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  63250. }
  63251. var epsilon = 0.00000001;
  63252. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  63253. contours.pop();
  63254. }
  63255. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  63256. for (var hNb = 0; hNb < holes.length; hNb++) {
  63257. hole = [];
  63258. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  63259. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  63260. }
  63261. polygonTriangulation.addHole(hole);
  63262. }
  63263. var polygon = polygonTriangulation.build(options.updatable, depth);
  63264. polygon._originalBuilderSideOrientation = options.sideOrientation;
  63265. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  63266. vertexData.applyToMesh(polygon, options.updatable);
  63267. return polygon;
  63268. };
  63269. ;
  63270. /**
  63271. * Creates an extruded polygon mesh, with depth in the Y direction.
  63272. * * 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)
  63273. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63274. * @param name defines the name of the mesh
  63275. * @param options defines the options used to create the mesh
  63276. * @param scene defines the hosting scene
  63277. * @returns the polygon mesh
  63278. */
  63279. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  63280. return MeshBuilder.CreatePolygon(name, options, scene);
  63281. };
  63282. ;
  63283. /**
  63284. * Creates a tube mesh.
  63285. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63286. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  63287. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  63288. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  63289. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  63290. * * 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)
  63291. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  63292. * * 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
  63293. * * 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
  63294. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63295. * * 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
  63296. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63297. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63298. * @param name defines the name of the mesh
  63299. * @param options defines the options used to create the mesh
  63300. * @param scene defines the hosting scene
  63301. * @returns the tube mesh
  63302. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63303. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  63304. */
  63305. MeshBuilder.CreateTube = function (name, options, scene) {
  63306. var path = options.path;
  63307. var instance = options.instance;
  63308. var radius = 1.0;
  63309. if (instance) {
  63310. radius = instance.radius;
  63311. }
  63312. if (options.radius !== undefined) {
  63313. radius = options.radius;
  63314. }
  63315. ;
  63316. var tessellation = options.tessellation || 64 | 0;
  63317. var radiusFunction = options.radiusFunction || null;
  63318. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63319. var invertUV = options.invertUV || false;
  63320. var updatable = options.updatable;
  63321. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63322. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  63323. // tube geometry
  63324. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  63325. var tangents = path3D.getTangents();
  63326. var normals = path3D.getNormals();
  63327. var distances = path3D.getDistances();
  63328. var pi2 = Math.PI * 2;
  63329. var step = pi2 / tessellation * arc;
  63330. var returnRadius = function () { return radius; };
  63331. var radiusFunctionFinal = radiusFunction || returnRadius;
  63332. var circlePath;
  63333. var rad;
  63334. var normal;
  63335. var rotated;
  63336. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63337. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63338. for (var i = 0; i < path.length; i++) {
  63339. rad = radiusFunctionFinal(i, distances[i]); // current radius
  63340. circlePath = Array(); // current circle array
  63341. normal = normals[i]; // current normal
  63342. for (var t = 0; t < tessellation; t++) {
  63343. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  63344. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  63345. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  63346. rotated.scaleInPlace(rad).addInPlace(path[i]);
  63347. circlePath[t] = rotated;
  63348. }
  63349. circlePaths[index] = circlePath;
  63350. index++;
  63351. }
  63352. // cap
  63353. var capPath = function (nbPoints, pathIndex) {
  63354. var pointCap = Array();
  63355. for (var i = 0; i < nbPoints; i++) {
  63356. pointCap.push(path[pathIndex]);
  63357. }
  63358. return pointCap;
  63359. };
  63360. switch (cap) {
  63361. case BABYLON.Mesh.NO_CAP:
  63362. break;
  63363. case BABYLON.Mesh.CAP_START:
  63364. circlePaths[0] = capPath(tessellation, 0);
  63365. circlePaths[1] = circlePaths[2].slice(0);
  63366. break;
  63367. case BABYLON.Mesh.CAP_END:
  63368. circlePaths[index] = circlePaths[index - 1].slice(0);
  63369. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63370. break;
  63371. case BABYLON.Mesh.CAP_ALL:
  63372. circlePaths[0] = capPath(tessellation, 0);
  63373. circlePaths[1] = circlePaths[2].slice(0);
  63374. circlePaths[index] = circlePaths[index - 1].slice(0);
  63375. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63376. break;
  63377. default:
  63378. break;
  63379. }
  63380. return circlePaths;
  63381. };
  63382. var path3D;
  63383. var pathArray;
  63384. if (instance) { // tube update
  63385. var arc = options.arc || instance.arc;
  63386. path3D = (instance.path3D).update(path);
  63387. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  63388. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  63389. instance.path3D = path3D;
  63390. instance.pathArray = pathArray;
  63391. instance.arc = arc;
  63392. instance.radius = radius;
  63393. return instance;
  63394. }
  63395. // tube creation
  63396. path3D = new BABYLON.Path3D(path);
  63397. var newPathArray = new Array();
  63398. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63399. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  63400. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63401. tube.pathArray = pathArray;
  63402. tube.path3D = path3D;
  63403. tube.tessellation = tessellation;
  63404. tube.cap = cap;
  63405. tube.arc = options.arc;
  63406. tube.radius = radius;
  63407. return tube;
  63408. };
  63409. /**
  63410. * Creates a polyhedron mesh
  63411. * * 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
  63412. * * The parameter `size` (positive float, default 1) sets the polygon size
  63413. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  63414. * * 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`
  63415. * * 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
  63416. * * 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)`)
  63417. * * 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
  63418. * * 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
  63419. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63420. * * 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
  63421. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63422. * @param name defines the name of the mesh
  63423. * @param options defines the options used to create the mesh
  63424. * @param scene defines the hosting scene
  63425. * @returns the polyhedron mesh
  63426. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  63427. */
  63428. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  63429. var polyhedron = new BABYLON.Mesh(name, scene);
  63430. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63431. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  63432. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  63433. vertexData.applyToMesh(polyhedron, options.updatable);
  63434. return polyhedron;
  63435. };
  63436. /**
  63437. * Creates a decal mesh.
  63438. * 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
  63439. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  63440. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  63441. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  63442. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  63443. * @param name defines the name of the mesh
  63444. * @param sourceMesh defines the mesh where the decal must be applied
  63445. * @param options defines the options used to create the mesh
  63446. * @param scene defines the hosting scene
  63447. * @returns the decal mesh
  63448. * @see http://doc.babylonjs.com/how_to/decals
  63449. */
  63450. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  63451. var indices = sourceMesh.getIndices();
  63452. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63453. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63454. var position = options.position || BABYLON.Vector3.Zero();
  63455. var normal = options.normal || BABYLON.Vector3.Up();
  63456. var size = options.size || BABYLON.Vector3.One();
  63457. var angle = options.angle || 0;
  63458. // Getting correct rotation
  63459. if (!normal) {
  63460. var target = new BABYLON.Vector3(0, 0, 1);
  63461. var camera = sourceMesh.getScene().activeCamera;
  63462. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  63463. normal = camera.globalPosition.subtract(cameraWorldTarget);
  63464. }
  63465. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  63466. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  63467. var pitch = Math.atan2(normal.y, len);
  63468. // Matrix
  63469. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  63470. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  63471. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  63472. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  63473. var vertexData = new BABYLON.VertexData();
  63474. vertexData.indices = [];
  63475. vertexData.positions = [];
  63476. vertexData.normals = [];
  63477. vertexData.uvs = [];
  63478. var currentVertexDataIndex = 0;
  63479. var extractDecalVector3 = function (indexId) {
  63480. var result = new BABYLON.PositionNormalVertex();
  63481. if (!indices || !positions || !normals) {
  63482. return result;
  63483. }
  63484. var vertexId = indices[indexId];
  63485. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  63486. // Send vector to decal local world
  63487. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  63488. // Get normal
  63489. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  63490. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  63491. return result;
  63492. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  63493. var clip = function (vertices, axis) {
  63494. if (vertices.length === 0) {
  63495. return vertices;
  63496. }
  63497. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  63498. var clipVertices = function (v0, v1) {
  63499. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  63500. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  63501. };
  63502. var result = new Array();
  63503. for (var index = 0; index < vertices.length; index += 3) {
  63504. var v1Out;
  63505. var v2Out;
  63506. var v3Out;
  63507. var total = 0;
  63508. var nV1 = null;
  63509. var nV2 = null;
  63510. var nV3 = null;
  63511. var nV4 = null;
  63512. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  63513. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  63514. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  63515. v1Out = d1 > 0;
  63516. v2Out = d2 > 0;
  63517. v3Out = d3 > 0;
  63518. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  63519. switch (total) {
  63520. case 0:
  63521. result.push(vertices[index]);
  63522. result.push(vertices[index + 1]);
  63523. result.push(vertices[index + 2]);
  63524. break;
  63525. case 1:
  63526. if (v1Out) {
  63527. nV1 = vertices[index + 1];
  63528. nV2 = vertices[index + 2];
  63529. nV3 = clipVertices(vertices[index], nV1);
  63530. nV4 = clipVertices(vertices[index], nV2);
  63531. }
  63532. if (v2Out) {
  63533. nV1 = vertices[index];
  63534. nV2 = vertices[index + 2];
  63535. nV3 = clipVertices(vertices[index + 1], nV1);
  63536. nV4 = clipVertices(vertices[index + 1], nV2);
  63537. result.push(nV3);
  63538. result.push(nV2.clone());
  63539. result.push(nV1.clone());
  63540. result.push(nV2.clone());
  63541. result.push(nV3.clone());
  63542. result.push(nV4);
  63543. break;
  63544. }
  63545. if (v3Out) {
  63546. nV1 = vertices[index];
  63547. nV2 = vertices[index + 1];
  63548. nV3 = clipVertices(vertices[index + 2], nV1);
  63549. nV4 = clipVertices(vertices[index + 2], nV2);
  63550. }
  63551. if (nV1 && nV2 && nV3 && nV4) {
  63552. result.push(nV1.clone());
  63553. result.push(nV2.clone());
  63554. result.push(nV3);
  63555. result.push(nV4);
  63556. result.push(nV3.clone());
  63557. result.push(nV2.clone());
  63558. }
  63559. break;
  63560. case 2:
  63561. if (!v1Out) {
  63562. nV1 = vertices[index].clone();
  63563. nV2 = clipVertices(nV1, vertices[index + 1]);
  63564. nV3 = clipVertices(nV1, vertices[index + 2]);
  63565. result.push(nV1);
  63566. result.push(nV2);
  63567. result.push(nV3);
  63568. }
  63569. if (!v2Out) {
  63570. nV1 = vertices[index + 1].clone();
  63571. nV2 = clipVertices(nV1, vertices[index + 2]);
  63572. nV3 = clipVertices(nV1, vertices[index]);
  63573. result.push(nV1);
  63574. result.push(nV2);
  63575. result.push(nV3);
  63576. }
  63577. if (!v3Out) {
  63578. nV1 = vertices[index + 2].clone();
  63579. nV2 = clipVertices(nV1, vertices[index]);
  63580. nV3 = clipVertices(nV1, vertices[index + 1]);
  63581. result.push(nV1);
  63582. result.push(nV2);
  63583. result.push(nV3);
  63584. }
  63585. break;
  63586. case 3:
  63587. break;
  63588. }
  63589. }
  63590. return result;
  63591. };
  63592. for (var index = 0; index < indices.length; index += 3) {
  63593. var faceVertices = new Array();
  63594. faceVertices.push(extractDecalVector3(index));
  63595. faceVertices.push(extractDecalVector3(index + 1));
  63596. faceVertices.push(extractDecalVector3(index + 2));
  63597. // Clip
  63598. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  63599. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  63600. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  63601. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  63602. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  63603. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  63604. if (faceVertices.length === 0) {
  63605. continue;
  63606. }
  63607. // Add UVs and get back to world
  63608. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  63609. var vertex = faceVertices[vIndex];
  63610. //TODO check for Int32Array | Uint32Array | Uint16Array
  63611. vertexData.indices.push(currentVertexDataIndex);
  63612. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  63613. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  63614. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  63615. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  63616. currentVertexDataIndex++;
  63617. }
  63618. }
  63619. // Return mesh
  63620. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  63621. vertexData.applyToMesh(decal);
  63622. decal.position = position.clone();
  63623. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  63624. return decal;
  63625. };
  63626. // Privates
  63627. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  63628. // extrusion geometry
  63629. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  63630. var tangents = path3D.getTangents();
  63631. var normals = path3D.getNormals();
  63632. var binormals = path3D.getBinormals();
  63633. var distances = path3D.getDistances();
  63634. var angle = 0;
  63635. var returnScale = function () { return scale !== null ? scale : 1; };
  63636. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  63637. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  63638. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  63639. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63640. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63641. for (var i = 0; i < curve.length; i++) {
  63642. var shapePath = new Array();
  63643. var angleStep = rotate(i, distances[i]);
  63644. var scaleRatio = scl(i, distances[i]);
  63645. for (var p = 0; p < shape.length; p++) {
  63646. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  63647. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  63648. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  63649. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  63650. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  63651. shapePath[p] = rotated;
  63652. }
  63653. shapePaths[index] = shapePath;
  63654. angle += angleStep;
  63655. index++;
  63656. }
  63657. // cap
  63658. var capPath = function (shapePath) {
  63659. var pointCap = Array();
  63660. var barycenter = BABYLON.Vector3.Zero();
  63661. var i;
  63662. for (i = 0; i < shapePath.length; i++) {
  63663. barycenter.addInPlace(shapePath[i]);
  63664. }
  63665. barycenter.scaleInPlace(1.0 / shapePath.length);
  63666. for (i = 0; i < shapePath.length; i++) {
  63667. pointCap.push(barycenter);
  63668. }
  63669. return pointCap;
  63670. };
  63671. switch (cap) {
  63672. case BABYLON.Mesh.NO_CAP:
  63673. break;
  63674. case BABYLON.Mesh.CAP_START:
  63675. shapePaths[0] = capPath(shapePaths[2]);
  63676. shapePaths[1] = shapePaths[2];
  63677. break;
  63678. case BABYLON.Mesh.CAP_END:
  63679. shapePaths[index] = shapePaths[index - 1];
  63680. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63681. break;
  63682. case BABYLON.Mesh.CAP_ALL:
  63683. shapePaths[0] = capPath(shapePaths[2]);
  63684. shapePaths[1] = shapePaths[2];
  63685. shapePaths[index] = shapePaths[index - 1];
  63686. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63687. break;
  63688. default:
  63689. break;
  63690. }
  63691. return shapePaths;
  63692. };
  63693. var path3D;
  63694. var pathArray;
  63695. if (instance) { // instance update
  63696. path3D = (instance.path3D).update(curve);
  63697. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  63698. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  63699. return instance;
  63700. }
  63701. // extruded shape creation
  63702. path3D = new BABYLON.Path3D(curve);
  63703. var newShapePaths = new Array();
  63704. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63705. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  63706. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  63707. extrudedGeneric.pathArray = pathArray;
  63708. extrudedGeneric.path3D = path3D;
  63709. extrudedGeneric.cap = cap;
  63710. return extrudedGeneric;
  63711. };
  63712. return MeshBuilder;
  63713. }());
  63714. BABYLON.MeshBuilder = MeshBuilder;
  63715. })(BABYLON || (BABYLON = {}));
  63716. //# sourceMappingURL=babylon.meshBuilder.js.map
  63717. var BABYLON;
  63718. (function (BABYLON) {
  63719. /**
  63720. * Draco compression (https://google.github.io/draco/)
  63721. *
  63722. * This class wraps the Draco module.
  63723. *
  63724. * **Encoder**
  63725. *
  63726. * The encoder is not currently implemented.
  63727. *
  63728. * **Decoder**
  63729. *
  63730. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  63731. *
  63732. * To update the configuration, use the following code:
  63733. * ```javascript
  63734. * BABYLON.DracoCompression.Configuration = {
  63735. * decoder: {
  63736. * wasmUrl: "<url to the WebAssembly library>",
  63737. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  63738. * fallbackUrl: "<url to the fallback JavaScript library>",
  63739. * }
  63740. * };
  63741. * ```
  63742. *
  63743. * 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.
  63744. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  63745. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  63746. *
  63747. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  63748. * ```javascript
  63749. * var dracoCompression = new BABYLON.DracoCompression();
  63750. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  63751. * [BABYLON.VertexBuffer.PositionKind]: 0
  63752. * });
  63753. * ```
  63754. *
  63755. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  63756. */
  63757. var DracoCompression = /** @class */ (function () {
  63758. /**
  63759. * Constructor
  63760. */
  63761. function DracoCompression() {
  63762. }
  63763. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  63764. /**
  63765. * Returns true if the decoder is available.
  63766. */
  63767. get: function () {
  63768. if (typeof DracoDecoderModule !== "undefined") {
  63769. return true;
  63770. }
  63771. var decoder = DracoCompression.Configuration.decoder;
  63772. if (decoder) {
  63773. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63774. return true;
  63775. }
  63776. if (decoder.fallbackUrl) {
  63777. return true;
  63778. }
  63779. }
  63780. return false;
  63781. },
  63782. enumerable: true,
  63783. configurable: true
  63784. });
  63785. /**
  63786. * Stop all async operations and release resources.
  63787. */
  63788. DracoCompression.prototype.dispose = function () {
  63789. };
  63790. /**
  63791. * Decode Draco compressed mesh data to vertex data.
  63792. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  63793. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  63794. * @returns A promise that resolves with the decoded vertex data
  63795. */
  63796. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  63797. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  63798. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  63799. var module = wrappedModule.module;
  63800. var vertexData = new BABYLON.VertexData();
  63801. var buffer = new module.DecoderBuffer();
  63802. buffer.Init(dataView, dataView.byteLength);
  63803. var decoder = new module.Decoder();
  63804. var geometry;
  63805. var status;
  63806. try {
  63807. var type = decoder.GetEncodedGeometryType(buffer);
  63808. switch (type) {
  63809. case module.TRIANGULAR_MESH:
  63810. geometry = new module.Mesh();
  63811. status = decoder.DecodeBufferToMesh(buffer, geometry);
  63812. break;
  63813. case module.POINT_CLOUD:
  63814. geometry = new module.PointCloud();
  63815. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  63816. break;
  63817. default:
  63818. throw new Error("Invalid geometry type " + type);
  63819. }
  63820. if (!status.ok() || !geometry.ptr) {
  63821. throw new Error(status.error_msg());
  63822. }
  63823. var numPoints = geometry.num_points();
  63824. if (type === module.TRIANGULAR_MESH) {
  63825. var numFaces = geometry.num_faces();
  63826. var faceIndices = new module.DracoInt32Array();
  63827. try {
  63828. var indices = new Uint32Array(numFaces * 3);
  63829. for (var i = 0; i < numFaces; i++) {
  63830. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  63831. var offset = i * 3;
  63832. indices[offset + 0] = faceIndices.GetValue(0);
  63833. indices[offset + 1] = faceIndices.GetValue(1);
  63834. indices[offset + 2] = faceIndices.GetValue(2);
  63835. }
  63836. vertexData.indices = indices;
  63837. }
  63838. finally {
  63839. module.destroy(faceIndices);
  63840. }
  63841. }
  63842. for (var kind in attributes) {
  63843. var uniqueId = attributes[kind];
  63844. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  63845. var dracoData = new module.DracoFloat32Array();
  63846. try {
  63847. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  63848. var babylonData = new Float32Array(numPoints * attribute.num_components());
  63849. for (var i = 0; i < babylonData.length; i++) {
  63850. babylonData[i] = dracoData.GetValue(i);
  63851. }
  63852. vertexData.set(babylonData, kind);
  63853. }
  63854. finally {
  63855. module.destroy(dracoData);
  63856. }
  63857. }
  63858. }
  63859. finally {
  63860. if (geometry) {
  63861. module.destroy(geometry);
  63862. }
  63863. module.destroy(decoder);
  63864. module.destroy(buffer);
  63865. }
  63866. return vertexData;
  63867. });
  63868. };
  63869. DracoCompression._GetDecoderModule = function () {
  63870. if (!DracoCompression._DecoderModulePromise) {
  63871. var promise = null;
  63872. var config_1 = {};
  63873. if (typeof DracoDecoderModule !== "undefined") {
  63874. promise = Promise.resolve();
  63875. }
  63876. else {
  63877. var decoder = DracoCompression.Configuration.decoder;
  63878. if (decoder) {
  63879. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63880. promise = Promise.all([
  63881. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  63882. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  63883. config_1.wasmBinary = data;
  63884. })
  63885. ]);
  63886. }
  63887. else if (decoder.fallbackUrl) {
  63888. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  63889. }
  63890. }
  63891. }
  63892. if (!promise) {
  63893. throw new Error("Draco decoder module is not available");
  63894. }
  63895. DracoCompression._DecoderModulePromise = promise.then(function () {
  63896. return new Promise(function (resolve) {
  63897. config_1.onModuleLoaded = function (decoderModule) {
  63898. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  63899. resolve({ module: decoderModule });
  63900. };
  63901. DracoDecoderModule(config_1);
  63902. });
  63903. });
  63904. }
  63905. return DracoCompression._DecoderModulePromise;
  63906. };
  63907. DracoCompression._LoadScriptAsync = function (url) {
  63908. return new Promise(function (resolve, reject) {
  63909. BABYLON.Tools.LoadScript(url, function () {
  63910. resolve();
  63911. }, function (message) {
  63912. reject(new Error(message));
  63913. });
  63914. });
  63915. };
  63916. DracoCompression._LoadFileAsync = function (url) {
  63917. return new Promise(function (resolve, reject) {
  63918. BABYLON.Tools.LoadFile(url, function (data) {
  63919. resolve(data);
  63920. }, undefined, undefined, true, function (request, exception) {
  63921. reject(exception);
  63922. });
  63923. });
  63924. };
  63925. /**
  63926. * The configuration. Defaults to the following urls:
  63927. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  63928. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  63929. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63930. */
  63931. DracoCompression.Configuration = {
  63932. decoder: {
  63933. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  63934. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  63935. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63936. }
  63937. };
  63938. return DracoCompression;
  63939. }());
  63940. BABYLON.DracoCompression = DracoCompression;
  63941. })(BABYLON || (BABYLON = {}));
  63942. //# sourceMappingURL=babylon.dracoCompression.js.map
  63943. var BABYLON;
  63944. (function (BABYLON) {
  63945. var AudioEngine = /** @class */ (function () {
  63946. function AudioEngine() {
  63947. this._audioContext = null;
  63948. this._audioContextInitialized = false;
  63949. this.canUseWebAudio = false;
  63950. this.WarnedWebAudioUnsupported = false;
  63951. this.unlocked = false;
  63952. this.isMP3supported = false;
  63953. this.isOGGsupported = false;
  63954. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  63955. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  63956. this.canUseWebAudio = true;
  63957. }
  63958. var audioElem = document.createElement('audio');
  63959. try {
  63960. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  63961. this.isMP3supported = true;
  63962. }
  63963. }
  63964. catch (e) {
  63965. // protect error during capability check.
  63966. }
  63967. try {
  63968. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  63969. this.isOGGsupported = true;
  63970. }
  63971. }
  63972. catch (e) {
  63973. // protect error during capability check.
  63974. }
  63975. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  63976. this._unlockiOSaudio();
  63977. }
  63978. else {
  63979. this.unlocked = true;
  63980. }
  63981. }
  63982. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  63983. get: function () {
  63984. if (!this._audioContextInitialized) {
  63985. this._initializeAudioContext();
  63986. }
  63987. return this._audioContext;
  63988. },
  63989. enumerable: true,
  63990. configurable: true
  63991. });
  63992. AudioEngine.prototype._unlockiOSaudio = function () {
  63993. var _this = this;
  63994. var unlockaudio = function () {
  63995. if (!_this.audioContext) {
  63996. return;
  63997. }
  63998. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  63999. var source = _this.audioContext.createBufferSource();
  64000. source.buffer = buffer;
  64001. source.connect(_this.audioContext.destination);
  64002. source.start(0);
  64003. setTimeout(function () {
  64004. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  64005. _this.unlocked = true;
  64006. window.removeEventListener('touchend', unlockaudio, false);
  64007. if (_this.onAudioUnlocked) {
  64008. _this.onAudioUnlocked();
  64009. }
  64010. }
  64011. }, 0);
  64012. };
  64013. window.addEventListener('touchend', unlockaudio, false);
  64014. };
  64015. AudioEngine.prototype._initializeAudioContext = function () {
  64016. try {
  64017. if (this.canUseWebAudio) {
  64018. this._audioContext = new AudioContext();
  64019. // create a global volume gain node
  64020. this.masterGain = this._audioContext.createGain();
  64021. this.masterGain.gain.value = 1;
  64022. this.masterGain.connect(this._audioContext.destination);
  64023. this._audioContextInitialized = true;
  64024. }
  64025. }
  64026. catch (e) {
  64027. this.canUseWebAudio = false;
  64028. BABYLON.Tools.Error("Web Audio: " + e.message);
  64029. }
  64030. };
  64031. AudioEngine.prototype.dispose = function () {
  64032. if (this.canUseWebAudio && this._audioContextInitialized) {
  64033. if (this._connectedAnalyser && this._audioContext) {
  64034. this._connectedAnalyser.stopDebugCanvas();
  64035. this._connectedAnalyser.dispose();
  64036. this.masterGain.disconnect();
  64037. this.masterGain.connect(this._audioContext.destination);
  64038. this._connectedAnalyser = null;
  64039. }
  64040. this.masterGain.gain.value = 1;
  64041. }
  64042. this.WarnedWebAudioUnsupported = false;
  64043. };
  64044. AudioEngine.prototype.getGlobalVolume = function () {
  64045. if (this.canUseWebAudio && this._audioContextInitialized) {
  64046. return this.masterGain.gain.value;
  64047. }
  64048. else {
  64049. return -1;
  64050. }
  64051. };
  64052. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  64053. if (this.canUseWebAudio && this._audioContextInitialized) {
  64054. this.masterGain.gain.value = newVolume;
  64055. }
  64056. };
  64057. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  64058. if (this._connectedAnalyser) {
  64059. this._connectedAnalyser.stopDebugCanvas();
  64060. }
  64061. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  64062. this._connectedAnalyser = analyser;
  64063. this.masterGain.disconnect();
  64064. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  64065. }
  64066. };
  64067. return AudioEngine;
  64068. }());
  64069. BABYLON.AudioEngine = AudioEngine;
  64070. })(BABYLON || (BABYLON = {}));
  64071. //# sourceMappingURL=babylon.audioEngine.js.map
  64072. var BABYLON;
  64073. (function (BABYLON) {
  64074. var Sound = /** @class */ (function () {
  64075. /**
  64076. * Create a sound and attach it to a scene
  64077. * @param name Name of your sound
  64078. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  64079. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  64080. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  64081. */
  64082. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  64083. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  64084. var _this = this;
  64085. this.autoplay = false;
  64086. this.loop = false;
  64087. this.useCustomAttenuation = false;
  64088. this.spatialSound = false;
  64089. this.refDistance = 1;
  64090. this.rolloffFactor = 1;
  64091. this.maxDistance = 100;
  64092. this.distanceModel = "linear";
  64093. this._panningModel = "equalpower";
  64094. /**
  64095. * Observable event when the current playing sound finishes.
  64096. */
  64097. this.onEndedObservable = new BABYLON.Observable();
  64098. this._playbackRate = 1;
  64099. this._streaming = false;
  64100. this._startTime = 0;
  64101. this._startOffset = 0;
  64102. this._position = BABYLON.Vector3.Zero();
  64103. /** @hidden */
  64104. this._positionInEmitterSpace = false;
  64105. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  64106. this._volume = 1;
  64107. this._isReadyToPlay = false;
  64108. this.isPlaying = false;
  64109. this.isPaused = false;
  64110. this._isDirectional = false;
  64111. // Used if you'd like to create a directional sound.
  64112. // If not set, the sound will be omnidirectional
  64113. this._coneInnerAngle = 360;
  64114. this._coneOuterAngle = 360;
  64115. this._coneOuterGain = 0;
  64116. this._isOutputConnected = false;
  64117. this._urlType = "Unknown";
  64118. this.name = name;
  64119. this._scene = scene;
  64120. this._readyToPlayCallback = readyToPlayCallback;
  64121. // Default custom attenuation function is a linear attenuation
  64122. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  64123. if (currentDistance < maxDistance) {
  64124. return currentVolume * (1 - currentDistance / maxDistance);
  64125. }
  64126. else {
  64127. return 0;
  64128. }
  64129. };
  64130. if (options) {
  64131. this.autoplay = options.autoplay || false;
  64132. this.loop = options.loop || false;
  64133. // if volume === 0, we need another way to check this option
  64134. if (options.volume !== undefined) {
  64135. this._volume = options.volume;
  64136. }
  64137. this.spatialSound = options.spatialSound || false;
  64138. this.maxDistance = options.maxDistance || 100;
  64139. this.useCustomAttenuation = options.useCustomAttenuation || false;
  64140. this.rolloffFactor = options.rolloffFactor || 1;
  64141. this.refDistance = options.refDistance || 1;
  64142. this.distanceModel = options.distanceModel || "linear";
  64143. this._playbackRate = options.playbackRate || 1;
  64144. this._streaming = options.streaming || false;
  64145. }
  64146. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64147. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  64148. this._soundGain.gain.value = this._volume;
  64149. this._inputAudioNode = this._soundGain;
  64150. this._outputAudioNode = this._soundGain;
  64151. if (this.spatialSound) {
  64152. this._createSpatialParameters();
  64153. }
  64154. this._scene.mainSoundTrack.AddSound(this);
  64155. var validParameter = true;
  64156. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  64157. if (urlOrArrayBuffer) {
  64158. try {
  64159. if (typeof (urlOrArrayBuffer) === "string") {
  64160. this._urlType = "String";
  64161. }
  64162. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  64163. this._urlType = "ArrayBuffer";
  64164. }
  64165. else if (urlOrArrayBuffer instanceof MediaStream) {
  64166. this._urlType = "MediaStream";
  64167. }
  64168. else if (Array.isArray(urlOrArrayBuffer)) {
  64169. this._urlType = "Array";
  64170. }
  64171. var urls = [];
  64172. var codecSupportedFound = false;
  64173. switch (this._urlType) {
  64174. case "MediaStream":
  64175. this._streaming = true;
  64176. this._isReadyToPlay = true;
  64177. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  64178. if (this.autoplay) {
  64179. this.play();
  64180. }
  64181. if (this._readyToPlayCallback) {
  64182. this._readyToPlayCallback();
  64183. }
  64184. break;
  64185. case "ArrayBuffer":
  64186. if (urlOrArrayBuffer.byteLength > 0) {
  64187. codecSupportedFound = true;
  64188. this._soundLoaded(urlOrArrayBuffer);
  64189. }
  64190. break;
  64191. case "String":
  64192. urls.push(urlOrArrayBuffer);
  64193. case "Array":
  64194. if (urls.length === 0)
  64195. urls = urlOrArrayBuffer;
  64196. // If we found a supported format, we load it immediately and stop the loop
  64197. for (var i = 0; i < urls.length; i++) {
  64198. var url = urls[i];
  64199. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  64200. codecSupportedFound = true;
  64201. }
  64202. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  64203. codecSupportedFound = true;
  64204. }
  64205. if (url.indexOf(".wav", url.length - 4) !== -1) {
  64206. codecSupportedFound = true;
  64207. }
  64208. if (url.indexOf("blob:") !== -1) {
  64209. codecSupportedFound = true;
  64210. }
  64211. if (codecSupportedFound) {
  64212. // Loading sound using XHR2
  64213. if (!this._streaming) {
  64214. this._scene._loadFile(url, function (data) {
  64215. _this._soundLoaded(data);
  64216. }, undefined, true, true, function (exception) {
  64217. if (exception) {
  64218. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  64219. }
  64220. BABYLON.Tools.Error("Sound creation aborted.");
  64221. _this._scene.mainSoundTrack.RemoveSound(_this);
  64222. });
  64223. }
  64224. // Streaming sound using HTML5 Audio tag
  64225. else {
  64226. this._htmlAudioElement = new Audio(url);
  64227. this._htmlAudioElement.controls = false;
  64228. this._htmlAudioElement.loop = this.loop;
  64229. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  64230. this._htmlAudioElement.preload = "auto";
  64231. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  64232. _this._isReadyToPlay = true;
  64233. if (_this.autoplay) {
  64234. _this.play();
  64235. }
  64236. if (_this._readyToPlayCallback) {
  64237. _this._readyToPlayCallback();
  64238. }
  64239. });
  64240. document.body.appendChild(this._htmlAudioElement);
  64241. }
  64242. break;
  64243. }
  64244. }
  64245. break;
  64246. default:
  64247. validParameter = false;
  64248. break;
  64249. }
  64250. if (!validParameter) {
  64251. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  64252. }
  64253. else {
  64254. if (!codecSupportedFound) {
  64255. this._isReadyToPlay = true;
  64256. // Simulating a ready to play event to avoid breaking code path
  64257. if (this._readyToPlayCallback) {
  64258. window.setTimeout(function () {
  64259. if (_this._readyToPlayCallback) {
  64260. _this._readyToPlayCallback();
  64261. }
  64262. }, 1000);
  64263. }
  64264. }
  64265. }
  64266. }
  64267. catch (ex) {
  64268. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  64269. this._scene.mainSoundTrack.RemoveSound(this);
  64270. }
  64271. }
  64272. }
  64273. else {
  64274. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  64275. this._scene.mainSoundTrack.AddSound(this);
  64276. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  64277. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  64278. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  64279. }
  64280. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  64281. if (this._readyToPlayCallback) {
  64282. window.setTimeout(function () {
  64283. if (_this._readyToPlayCallback) {
  64284. _this._readyToPlayCallback();
  64285. }
  64286. }, 1000);
  64287. }
  64288. }
  64289. }
  64290. Sound.prototype.dispose = function () {
  64291. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64292. if (this.isPlaying) {
  64293. this.stop();
  64294. }
  64295. this._isReadyToPlay = false;
  64296. if (this.soundTrackId === -1) {
  64297. this._scene.mainSoundTrack.RemoveSound(this);
  64298. }
  64299. else {
  64300. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  64301. }
  64302. if (this._soundGain) {
  64303. this._soundGain.disconnect();
  64304. this._soundGain = null;
  64305. }
  64306. if (this._soundPanner) {
  64307. this._soundPanner.disconnect();
  64308. this._soundPanner = null;
  64309. }
  64310. if (this._soundSource) {
  64311. this._soundSource.disconnect();
  64312. this._soundSource = null;
  64313. }
  64314. this._audioBuffer = null;
  64315. if (this._htmlAudioElement) {
  64316. this._htmlAudioElement.pause();
  64317. this._htmlAudioElement.src = "";
  64318. document.body.removeChild(this._htmlAudioElement);
  64319. }
  64320. if (this._streamingSource) {
  64321. this._streamingSource.disconnect();
  64322. }
  64323. if (this._connectedMesh && this._registerFunc) {
  64324. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64325. this._connectedMesh = null;
  64326. }
  64327. }
  64328. };
  64329. Sound.prototype.isReady = function () {
  64330. return this._isReadyToPlay;
  64331. };
  64332. Sound.prototype._soundLoaded = function (audioData) {
  64333. var _this = this;
  64334. if (!BABYLON.Engine.audioEngine.audioContext) {
  64335. return;
  64336. }
  64337. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  64338. _this._audioBuffer = buffer;
  64339. _this._isReadyToPlay = true;
  64340. if (_this.autoplay) {
  64341. _this.play();
  64342. }
  64343. if (_this._readyToPlayCallback) {
  64344. _this._readyToPlayCallback();
  64345. }
  64346. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  64347. };
  64348. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  64349. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64350. this._audioBuffer = audioBuffer;
  64351. this._isReadyToPlay = true;
  64352. }
  64353. };
  64354. Sound.prototype.updateOptions = function (options) {
  64355. if (options) {
  64356. this.loop = options.loop || this.loop;
  64357. this.maxDistance = options.maxDistance || this.maxDistance;
  64358. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  64359. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  64360. this.refDistance = options.refDistance || this.refDistance;
  64361. this.distanceModel = options.distanceModel || this.distanceModel;
  64362. this._playbackRate = options.playbackRate || this._playbackRate;
  64363. this._updateSpatialParameters();
  64364. if (this.isPlaying) {
  64365. if (this._streaming && this._htmlAudioElement) {
  64366. this._htmlAudioElement.playbackRate = this._playbackRate;
  64367. }
  64368. else {
  64369. if (this._soundSource) {
  64370. this._soundSource.playbackRate.value = this._playbackRate;
  64371. }
  64372. }
  64373. }
  64374. }
  64375. };
  64376. Sound.prototype._createSpatialParameters = function () {
  64377. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64378. if (this._scene.headphone) {
  64379. this._panningModel = "HRTF";
  64380. }
  64381. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  64382. this._updateSpatialParameters();
  64383. this._soundPanner.connect(this._outputAudioNode);
  64384. this._inputAudioNode = this._soundPanner;
  64385. }
  64386. };
  64387. Sound.prototype._updateSpatialParameters = function () {
  64388. if (this.spatialSound && this._soundPanner) {
  64389. if (this.useCustomAttenuation) {
  64390. // Tricks to disable in a way embedded Web Audio attenuation
  64391. this._soundPanner.distanceModel = "linear";
  64392. this._soundPanner.maxDistance = Number.MAX_VALUE;
  64393. this._soundPanner.refDistance = 1;
  64394. this._soundPanner.rolloffFactor = 1;
  64395. this._soundPanner.panningModel = this._panningModel;
  64396. }
  64397. else {
  64398. this._soundPanner.distanceModel = this.distanceModel;
  64399. this._soundPanner.maxDistance = this.maxDistance;
  64400. this._soundPanner.refDistance = this.refDistance;
  64401. this._soundPanner.rolloffFactor = this.rolloffFactor;
  64402. this._soundPanner.panningModel = this._panningModel;
  64403. }
  64404. }
  64405. };
  64406. Sound.prototype.switchPanningModelToHRTF = function () {
  64407. this._panningModel = "HRTF";
  64408. this._switchPanningModel();
  64409. };
  64410. Sound.prototype.switchPanningModelToEqualPower = function () {
  64411. this._panningModel = "equalpower";
  64412. this._switchPanningModel();
  64413. };
  64414. Sound.prototype._switchPanningModel = function () {
  64415. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64416. this._soundPanner.panningModel = this._panningModel;
  64417. }
  64418. };
  64419. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  64420. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64421. if (this._isOutputConnected) {
  64422. this._outputAudioNode.disconnect();
  64423. }
  64424. this._outputAudioNode.connect(soundTrackAudioNode);
  64425. this._isOutputConnected = true;
  64426. }
  64427. };
  64428. /**
  64429. * Transform this sound into a directional source
  64430. * @param coneInnerAngle Size of the inner cone in degree
  64431. * @param coneOuterAngle Size of the outer cone in degree
  64432. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  64433. */
  64434. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  64435. if (coneOuterAngle < coneInnerAngle) {
  64436. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  64437. return;
  64438. }
  64439. this._coneInnerAngle = coneInnerAngle;
  64440. this._coneOuterAngle = coneOuterAngle;
  64441. this._coneOuterGain = coneOuterGain;
  64442. this._isDirectional = true;
  64443. if (this.isPlaying && this.loop) {
  64444. this.stop();
  64445. this.play();
  64446. }
  64447. };
  64448. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  64449. /**
  64450. * Gets or sets the inner angle for the directional cone.
  64451. */
  64452. get: function () {
  64453. return this._coneInnerAngle;
  64454. },
  64455. /**
  64456. * Gets or sets the inner angle for the directional cone.
  64457. */
  64458. set: function (value) {
  64459. if (value != this._coneInnerAngle) {
  64460. if (this._coneOuterAngle < value) {
  64461. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  64462. return;
  64463. }
  64464. this._coneInnerAngle = value;
  64465. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64466. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64467. }
  64468. }
  64469. },
  64470. enumerable: true,
  64471. configurable: true
  64472. });
  64473. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  64474. /**
  64475. * Gets or sets the outer angle for the directional cone.
  64476. */
  64477. get: function () {
  64478. return this._coneOuterAngle;
  64479. },
  64480. /**
  64481. * Gets or sets the outer angle for the directional cone.
  64482. */
  64483. set: function (value) {
  64484. if (value != this._coneOuterAngle) {
  64485. if (value < this._coneInnerAngle) {
  64486. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  64487. return;
  64488. }
  64489. this._coneOuterAngle = value;
  64490. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64491. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  64492. }
  64493. }
  64494. },
  64495. enumerable: true,
  64496. configurable: true
  64497. });
  64498. Sound.prototype.setPosition = function (newPosition) {
  64499. this._position = newPosition;
  64500. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  64501. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64502. }
  64503. };
  64504. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  64505. this._localDirection = newLocalDirection;
  64506. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  64507. this._updateDirection();
  64508. }
  64509. };
  64510. Sound.prototype._updateDirection = function () {
  64511. if (!this._connectedMesh || !this._soundPanner) {
  64512. return;
  64513. }
  64514. var mat = this._connectedMesh.getWorldMatrix();
  64515. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  64516. direction.normalize();
  64517. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  64518. };
  64519. Sound.prototype.updateDistanceFromListener = function () {
  64520. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  64521. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  64522. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  64523. }
  64524. };
  64525. Sound.prototype.setAttenuationFunction = function (callback) {
  64526. this._customAttenuationFunction = callback;
  64527. };
  64528. /**
  64529. * Play the sound
  64530. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  64531. * @param offset (optional) Start the sound setting it at a specific time
  64532. */
  64533. Sound.prototype.play = function (time, offset) {
  64534. var _this = this;
  64535. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  64536. try {
  64537. if (this._startOffset < 0) {
  64538. time = -this._startOffset;
  64539. this._startOffset = 0;
  64540. }
  64541. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64542. if (!this._soundSource || !this._streamingSource) {
  64543. if (this.spatialSound && this._soundPanner) {
  64544. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  64545. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64546. }
  64547. if (this._isDirectional) {
  64548. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64549. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  64550. this._soundPanner.coneOuterGain = this._coneOuterGain;
  64551. if (this._connectedMesh) {
  64552. this._updateDirection();
  64553. }
  64554. else {
  64555. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  64556. }
  64557. }
  64558. }
  64559. }
  64560. if (this._streaming) {
  64561. if (!this._streamingSource) {
  64562. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  64563. this._htmlAudioElement.onended = function () { _this._onended(); };
  64564. this._htmlAudioElement.playbackRate = this._playbackRate;
  64565. }
  64566. this._streamingSource.disconnect();
  64567. this._streamingSource.connect(this._inputAudioNode);
  64568. if (this._htmlAudioElement) {
  64569. this._htmlAudioElement.play();
  64570. }
  64571. }
  64572. else {
  64573. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  64574. this._soundSource.buffer = this._audioBuffer;
  64575. this._soundSource.connect(this._inputAudioNode);
  64576. this._soundSource.loop = this.loop;
  64577. this._soundSource.playbackRate.value = this._playbackRate;
  64578. this._soundSource.onended = function () { _this._onended(); };
  64579. if (this._soundSource.buffer) {
  64580. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  64581. }
  64582. }
  64583. this._startTime = startTime;
  64584. this.isPlaying = true;
  64585. this.isPaused = false;
  64586. }
  64587. catch (ex) {
  64588. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  64589. }
  64590. }
  64591. };
  64592. Sound.prototype._onended = function () {
  64593. this.isPlaying = false;
  64594. if (this.onended) {
  64595. this.onended();
  64596. }
  64597. this.onEndedObservable.notifyObservers(this);
  64598. };
  64599. /**
  64600. * Stop the sound
  64601. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  64602. */
  64603. Sound.prototype.stop = function (time) {
  64604. if (this.isPlaying) {
  64605. if (this._streaming) {
  64606. if (this._htmlAudioElement) {
  64607. this._htmlAudioElement.pause();
  64608. // Test needed for Firefox or it will generate an Invalid State Error
  64609. if (this._htmlAudioElement.currentTime > 0) {
  64610. this._htmlAudioElement.currentTime = 0;
  64611. }
  64612. }
  64613. else {
  64614. this._streamingSource.disconnect();
  64615. }
  64616. }
  64617. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  64618. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64619. this._soundSource.stop(stopTime);
  64620. this._soundSource.onended = function () { };
  64621. if (!this.isPaused) {
  64622. this._startOffset = 0;
  64623. }
  64624. }
  64625. this.isPlaying = false;
  64626. }
  64627. };
  64628. Sound.prototype.pause = function () {
  64629. if (this.isPlaying) {
  64630. this.isPaused = true;
  64631. if (this._streaming) {
  64632. if (this._htmlAudioElement) {
  64633. this._htmlAudioElement.pause();
  64634. }
  64635. else {
  64636. this._streamingSource.disconnect();
  64637. }
  64638. }
  64639. else if (BABYLON.Engine.audioEngine.audioContext) {
  64640. this.stop(0);
  64641. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  64642. }
  64643. }
  64644. };
  64645. Sound.prototype.setVolume = function (newVolume, time) {
  64646. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  64647. if (time && BABYLON.Engine.audioEngine.audioContext) {
  64648. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  64649. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  64650. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  64651. }
  64652. else {
  64653. this._soundGain.gain.value = newVolume;
  64654. }
  64655. }
  64656. this._volume = newVolume;
  64657. };
  64658. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  64659. this._playbackRate = newPlaybackRate;
  64660. if (this.isPlaying) {
  64661. if (this._streaming && this._htmlAudioElement) {
  64662. this._htmlAudioElement.playbackRate = this._playbackRate;
  64663. }
  64664. else if (this._soundSource) {
  64665. this._soundSource.playbackRate.value = this._playbackRate;
  64666. }
  64667. }
  64668. };
  64669. Sound.prototype.getVolume = function () {
  64670. return this._volume;
  64671. };
  64672. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  64673. var _this = this;
  64674. if (this._connectedMesh && this._registerFunc) {
  64675. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64676. this._registerFunc = null;
  64677. }
  64678. this._connectedMesh = meshToConnectTo;
  64679. if (!this.spatialSound) {
  64680. this.spatialSound = true;
  64681. this._createSpatialParameters();
  64682. if (this.isPlaying && this.loop) {
  64683. this.stop();
  64684. this.play();
  64685. }
  64686. }
  64687. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  64688. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  64689. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  64690. };
  64691. Sound.prototype.detachFromMesh = function () {
  64692. if (this._connectedMesh && this._registerFunc) {
  64693. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64694. this._registerFunc = null;
  64695. this._connectedMesh = null;
  64696. }
  64697. };
  64698. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  64699. if (!node.getBoundingInfo) {
  64700. return;
  64701. }
  64702. var mesh = node;
  64703. if (this._positionInEmitterSpace) {
  64704. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  64705. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  64706. }
  64707. else {
  64708. var boundingInfo = mesh.getBoundingInfo();
  64709. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  64710. }
  64711. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  64712. this._updateDirection();
  64713. }
  64714. };
  64715. Sound.prototype.clone = function () {
  64716. var _this = this;
  64717. if (!this._streaming) {
  64718. var setBufferAndRun = function () {
  64719. if (_this._isReadyToPlay) {
  64720. clonedSound._audioBuffer = _this.getAudioBuffer();
  64721. clonedSound._isReadyToPlay = true;
  64722. if (clonedSound.autoplay) {
  64723. clonedSound.play();
  64724. }
  64725. }
  64726. else {
  64727. window.setTimeout(setBufferAndRun, 300);
  64728. }
  64729. };
  64730. var currentOptions = {
  64731. autoplay: this.autoplay, loop: this.loop,
  64732. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  64733. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  64734. refDistance: this.refDistance, distanceModel: this.distanceModel
  64735. };
  64736. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  64737. if (this.useCustomAttenuation) {
  64738. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  64739. }
  64740. clonedSound.setPosition(this._position);
  64741. clonedSound.setPlaybackRate(this._playbackRate);
  64742. setBufferAndRun();
  64743. return clonedSound;
  64744. }
  64745. // Can't clone a streaming sound
  64746. else {
  64747. return null;
  64748. }
  64749. };
  64750. Sound.prototype.getAudioBuffer = function () {
  64751. return this._audioBuffer;
  64752. };
  64753. Sound.prototype.serialize = function () {
  64754. var serializationObject = {
  64755. name: this.name,
  64756. url: this.name,
  64757. autoplay: this.autoplay,
  64758. loop: this.loop,
  64759. volume: this._volume,
  64760. spatialSound: this.spatialSound,
  64761. maxDistance: this.maxDistance,
  64762. rolloffFactor: this.rolloffFactor,
  64763. refDistance: this.refDistance,
  64764. distanceModel: this.distanceModel,
  64765. playbackRate: this._playbackRate,
  64766. panningModel: this._panningModel,
  64767. soundTrackId: this.soundTrackId
  64768. };
  64769. if (this.spatialSound) {
  64770. if (this._connectedMesh)
  64771. serializationObject.connectedMeshId = this._connectedMesh.id;
  64772. serializationObject.position = this._position.asArray();
  64773. serializationObject.refDistance = this.refDistance;
  64774. serializationObject.distanceModel = this.distanceModel;
  64775. serializationObject.isDirectional = this._isDirectional;
  64776. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  64777. serializationObject.coneInnerAngle = this._coneInnerAngle;
  64778. serializationObject.coneOuterAngle = this._coneOuterAngle;
  64779. serializationObject.coneOuterGain = this._coneOuterGain;
  64780. }
  64781. return serializationObject;
  64782. };
  64783. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  64784. var soundName = parsedSound.name;
  64785. var soundUrl;
  64786. if (parsedSound.url) {
  64787. soundUrl = rootUrl + parsedSound.url;
  64788. }
  64789. else {
  64790. soundUrl = rootUrl + soundName;
  64791. }
  64792. var options = {
  64793. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  64794. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  64795. rolloffFactor: parsedSound.rolloffFactor,
  64796. refDistance: parsedSound.refDistance,
  64797. distanceModel: parsedSound.distanceModel,
  64798. playbackRate: parsedSound.playbackRate
  64799. };
  64800. var newSound;
  64801. if (!sourceSound) {
  64802. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  64803. scene._addPendingData(newSound);
  64804. }
  64805. else {
  64806. var setBufferAndRun = function () {
  64807. if (sourceSound._isReadyToPlay) {
  64808. newSound._audioBuffer = sourceSound.getAudioBuffer();
  64809. newSound._isReadyToPlay = true;
  64810. if (newSound.autoplay) {
  64811. newSound.play();
  64812. }
  64813. }
  64814. else {
  64815. window.setTimeout(setBufferAndRun, 300);
  64816. }
  64817. };
  64818. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  64819. setBufferAndRun();
  64820. }
  64821. if (parsedSound.position) {
  64822. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  64823. newSound.setPosition(soundPosition);
  64824. }
  64825. if (parsedSound.isDirectional) {
  64826. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  64827. if (parsedSound.localDirectionToMesh) {
  64828. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  64829. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  64830. }
  64831. }
  64832. if (parsedSound.connectedMeshId) {
  64833. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  64834. if (connectedMesh) {
  64835. newSound.attachToMesh(connectedMesh);
  64836. }
  64837. }
  64838. return newSound;
  64839. };
  64840. return Sound;
  64841. }());
  64842. BABYLON.Sound = Sound;
  64843. })(BABYLON || (BABYLON = {}));
  64844. //# sourceMappingURL=babylon.sound.js.map
  64845. var BABYLON;
  64846. (function (BABYLON) {
  64847. var SoundTrack = /** @class */ (function () {
  64848. function SoundTrack(scene, options) {
  64849. this.id = -1;
  64850. this._isMainTrack = false;
  64851. this._isInitialized = false;
  64852. this._scene = scene;
  64853. this.soundCollection = new Array();
  64854. this._options = options;
  64855. if (!this._isMainTrack) {
  64856. this._scene.soundTracks.push(this);
  64857. this.id = this._scene.soundTracks.length - 1;
  64858. }
  64859. }
  64860. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  64861. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64862. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  64863. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  64864. if (this._options) {
  64865. if (this._options.volume) {
  64866. this._outputAudioNode.gain.value = this._options.volume;
  64867. }
  64868. if (this._options.mainTrack) {
  64869. this._isMainTrack = this._options.mainTrack;
  64870. }
  64871. }
  64872. this._isInitialized = true;
  64873. }
  64874. };
  64875. SoundTrack.prototype.dispose = function () {
  64876. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  64877. if (this._connectedAnalyser) {
  64878. this._connectedAnalyser.stopDebugCanvas();
  64879. }
  64880. while (this.soundCollection.length) {
  64881. this.soundCollection[0].dispose();
  64882. }
  64883. if (this._outputAudioNode) {
  64884. this._outputAudioNode.disconnect();
  64885. }
  64886. this._outputAudioNode = null;
  64887. }
  64888. };
  64889. SoundTrack.prototype.AddSound = function (sound) {
  64890. if (!this._isInitialized) {
  64891. this._initializeSoundTrackAudioGraph();
  64892. }
  64893. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64894. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  64895. }
  64896. if (sound.soundTrackId) {
  64897. if (sound.soundTrackId === -1) {
  64898. this._scene.mainSoundTrack.RemoveSound(sound);
  64899. }
  64900. else {
  64901. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  64902. }
  64903. }
  64904. this.soundCollection.push(sound);
  64905. sound.soundTrackId = this.id;
  64906. };
  64907. SoundTrack.prototype.RemoveSound = function (sound) {
  64908. var index = this.soundCollection.indexOf(sound);
  64909. if (index !== -1) {
  64910. this.soundCollection.splice(index, 1);
  64911. }
  64912. };
  64913. SoundTrack.prototype.setVolume = function (newVolume) {
  64914. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64915. this._outputAudioNode.gain.value = newVolume;
  64916. }
  64917. };
  64918. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  64919. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64920. for (var i = 0; i < this.soundCollection.length; i++) {
  64921. this.soundCollection[i].switchPanningModelToHRTF();
  64922. }
  64923. }
  64924. };
  64925. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  64926. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64927. for (var i = 0; i < this.soundCollection.length; i++) {
  64928. this.soundCollection[i].switchPanningModelToEqualPower();
  64929. }
  64930. }
  64931. };
  64932. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  64933. if (this._connectedAnalyser) {
  64934. this._connectedAnalyser.stopDebugCanvas();
  64935. }
  64936. this._connectedAnalyser = analyser;
  64937. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64938. this._outputAudioNode.disconnect();
  64939. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  64940. }
  64941. };
  64942. return SoundTrack;
  64943. }());
  64944. BABYLON.SoundTrack = SoundTrack;
  64945. })(BABYLON || (BABYLON = {}));
  64946. //# sourceMappingURL=babylon.soundtrack.js.map
  64947. var BABYLON;
  64948. (function (BABYLON) {
  64949. /**
  64950. * Class used to work with sound analyzer using fast fourier transform (FFT)
  64951. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  64952. */
  64953. var Analyser = /** @class */ (function () {
  64954. /**
  64955. * Creates a new analyser
  64956. * @param scene defines hosting scene
  64957. */
  64958. function Analyser(scene) {
  64959. /**
  64960. * Gets or sets the smoothing
  64961. * @ignorenaming
  64962. */
  64963. this.SMOOTHING = 0.75;
  64964. /**
  64965. * Gets or sets the FFT table size
  64966. * @ignorenaming
  64967. */
  64968. this.FFT_SIZE = 512;
  64969. /**
  64970. * Gets or sets the bar graph amplitude
  64971. * @ignorenaming
  64972. */
  64973. this.BARGRAPHAMPLITUDE = 256;
  64974. /**
  64975. * Gets or sets the position of the debug canvas
  64976. * @ignorenaming
  64977. */
  64978. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  64979. /**
  64980. * Gets or sets the debug canvas size
  64981. * @ignorenaming
  64982. */
  64983. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  64984. this._scene = scene;
  64985. this._audioEngine = BABYLON.Engine.audioEngine;
  64986. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  64987. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  64988. this._webAudioAnalyser.minDecibels = -140;
  64989. this._webAudioAnalyser.maxDecibels = 0;
  64990. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64991. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64992. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  64993. }
  64994. }
  64995. /**
  64996. * Get the number of data values you will have to play with for the visualization
  64997. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  64998. * @returns a number
  64999. */
  65000. Analyser.prototype.getFrequencyBinCount = function () {
  65001. if (this._audioEngine.canUseWebAudio) {
  65002. return this._webAudioAnalyser.frequencyBinCount;
  65003. }
  65004. else {
  65005. return 0;
  65006. }
  65007. };
  65008. /**
  65009. * Gets the current frequency data as a byte array
  65010. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65011. * @returns a Uint8Array
  65012. */
  65013. Analyser.prototype.getByteFrequencyData = function () {
  65014. if (this._audioEngine.canUseWebAudio) {
  65015. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65016. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65017. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  65018. }
  65019. return this._byteFreqs;
  65020. };
  65021. /**
  65022. * Gets the current waveform as a byte array
  65023. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  65024. * @returns a Uint8Array
  65025. */
  65026. Analyser.prototype.getByteTimeDomainData = function () {
  65027. if (this._audioEngine.canUseWebAudio) {
  65028. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65029. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65030. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  65031. }
  65032. return this._byteTime;
  65033. };
  65034. /**
  65035. * Gets the current frequency data as a float array
  65036. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65037. * @returns a Float32Array
  65038. */
  65039. Analyser.prototype.getFloatFrequencyData = function () {
  65040. if (this._audioEngine.canUseWebAudio) {
  65041. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65042. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65043. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  65044. }
  65045. return this._floatFreqs;
  65046. };
  65047. /**
  65048. * Renders the debug canvas
  65049. */
  65050. Analyser.prototype.drawDebugCanvas = function () {
  65051. var _this = this;
  65052. if (this._audioEngine.canUseWebAudio) {
  65053. if (!this._debugCanvas) {
  65054. this._debugCanvas = document.createElement("canvas");
  65055. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  65056. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  65057. this._debugCanvas.style.position = "absolute";
  65058. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  65059. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  65060. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  65061. document.body.appendChild(this._debugCanvas);
  65062. this._registerFunc = function () {
  65063. _this.drawDebugCanvas();
  65064. };
  65065. this._scene.registerBeforeRender(this._registerFunc);
  65066. }
  65067. if (this._registerFunc && this._debugCanvasContext) {
  65068. var workingArray = this.getByteFrequencyData();
  65069. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  65070. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  65071. // Draw the frequency domain chart.
  65072. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  65073. var value = workingArray[i];
  65074. var percent = value / this.BARGRAPHAMPLITUDE;
  65075. var height = this.DEBUGCANVASSIZE.height * percent;
  65076. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  65077. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  65078. var hue = i / this.getFrequencyBinCount() * 360;
  65079. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  65080. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  65081. }
  65082. }
  65083. }
  65084. };
  65085. /**
  65086. * Stops rendering the debug canvas and removes it
  65087. */
  65088. Analyser.prototype.stopDebugCanvas = function () {
  65089. if (this._debugCanvas) {
  65090. if (this._registerFunc) {
  65091. this._scene.unregisterBeforeRender(this._registerFunc);
  65092. this._registerFunc = null;
  65093. }
  65094. document.body.removeChild(this._debugCanvas);
  65095. this._debugCanvas = null;
  65096. this._debugCanvasContext = null;
  65097. }
  65098. };
  65099. /**
  65100. * Connects two audio nodes
  65101. * @param inputAudioNode defines first node to connect
  65102. * @param outputAudioNode defines second node to connect
  65103. */
  65104. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  65105. if (this._audioEngine.canUseWebAudio) {
  65106. inputAudioNode.connect(this._webAudioAnalyser);
  65107. this._webAudioAnalyser.connect(outputAudioNode);
  65108. }
  65109. };
  65110. /**
  65111. * Releases all associated resources
  65112. */
  65113. Analyser.prototype.dispose = function () {
  65114. if (this._audioEngine.canUseWebAudio) {
  65115. this._webAudioAnalyser.disconnect();
  65116. }
  65117. };
  65118. return Analyser;
  65119. }());
  65120. BABYLON.Analyser = Analyser;
  65121. })(BABYLON || (BABYLON = {}));
  65122. //# sourceMappingURL=babylon.analyser.js.map
  65123. var BABYLON;
  65124. (function (BABYLON) {
  65125. /**
  65126. * Wraps one or more Sound objects and selects one with random weight for playback.
  65127. */
  65128. var WeightedSound = /** @class */ (function () {
  65129. /**
  65130. * Creates a new WeightedSound from the list of sounds given.
  65131. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  65132. * @param sounds Array of Sounds that will be selected from.
  65133. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  65134. */
  65135. function WeightedSound(loop, sounds, weights) {
  65136. var _this = this;
  65137. /** When true a Sound will be selected and played when the current playing Sound completes. */
  65138. this.loop = false;
  65139. this._coneInnerAngle = 360;
  65140. this._coneOuterAngle = 360;
  65141. this._volume = 1;
  65142. /** A Sound is currently playing. */
  65143. this.isPlaying = false;
  65144. /** A Sound is currently paused. */
  65145. this.isPaused = false;
  65146. this._sounds = [];
  65147. this._weights = [];
  65148. if (sounds.length !== weights.length) {
  65149. throw new Error('Sounds length does not equal weights length');
  65150. }
  65151. this.loop = loop;
  65152. this._weights = weights;
  65153. // Normalize the weights
  65154. var weightSum = 0;
  65155. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  65156. var weight = weights_1[_i];
  65157. weightSum += weight;
  65158. }
  65159. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  65160. for (var i = 0; i < this._weights.length; i++) {
  65161. this._weights[i] *= invWeightSum;
  65162. }
  65163. this._sounds = sounds;
  65164. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  65165. var sound = _b[_a];
  65166. sound.onEndedObservable.add(function () { _this._onended(); });
  65167. }
  65168. }
  65169. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  65170. /**
  65171. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  65172. */
  65173. get: function () {
  65174. return this._coneInnerAngle;
  65175. },
  65176. /**
  65177. * The size of cone in degress for a directional sound in which there will be no attenuation.
  65178. */
  65179. set: function (value) {
  65180. if (value !== this._coneInnerAngle) {
  65181. if (this._coneOuterAngle < value) {
  65182. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65183. return;
  65184. }
  65185. this._coneInnerAngle = value;
  65186. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65187. var sound = _a[_i];
  65188. sound.directionalConeInnerAngle = value;
  65189. }
  65190. }
  65191. },
  65192. enumerable: true,
  65193. configurable: true
  65194. });
  65195. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  65196. /**
  65197. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65198. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65199. */
  65200. get: function () {
  65201. return this._coneOuterAngle;
  65202. },
  65203. /**
  65204. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65205. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65206. */
  65207. set: function (value) {
  65208. if (value !== this._coneOuterAngle) {
  65209. if (value < this._coneInnerAngle) {
  65210. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65211. return;
  65212. }
  65213. this._coneOuterAngle = value;
  65214. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65215. var sound = _a[_i];
  65216. sound.directionalConeOuterAngle = value;
  65217. }
  65218. }
  65219. },
  65220. enumerable: true,
  65221. configurable: true
  65222. });
  65223. Object.defineProperty(WeightedSound.prototype, "volume", {
  65224. /**
  65225. * Playback volume.
  65226. */
  65227. get: function () {
  65228. return this._volume;
  65229. },
  65230. /**
  65231. * Playback volume.
  65232. */
  65233. set: function (value) {
  65234. if (value !== this._volume) {
  65235. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65236. var sound = _a[_i];
  65237. sound.setVolume(value);
  65238. }
  65239. }
  65240. },
  65241. enumerable: true,
  65242. configurable: true
  65243. });
  65244. WeightedSound.prototype._onended = function () {
  65245. if (this._currentIndex !== undefined) {
  65246. this._sounds[this._currentIndex].autoplay = false;
  65247. }
  65248. if (this.loop && this.isPlaying) {
  65249. this.play();
  65250. }
  65251. else {
  65252. this.isPlaying = false;
  65253. }
  65254. };
  65255. /**
  65256. * Suspend playback
  65257. */
  65258. WeightedSound.prototype.pause = function () {
  65259. this.isPaused = true;
  65260. if (this._currentIndex !== undefined) {
  65261. this._sounds[this._currentIndex].pause();
  65262. }
  65263. };
  65264. /**
  65265. * Stop playback
  65266. */
  65267. WeightedSound.prototype.stop = function () {
  65268. this.isPlaying = false;
  65269. if (this._currentIndex !== undefined) {
  65270. this._sounds[this._currentIndex].stop();
  65271. }
  65272. };
  65273. /**
  65274. * Start playback.
  65275. * @param startOffset Position the clip head at a specific time in seconds.
  65276. */
  65277. WeightedSound.prototype.play = function (startOffset) {
  65278. if (!this.isPaused) {
  65279. this.stop();
  65280. var randomValue = Math.random();
  65281. var total = 0;
  65282. for (var i = 0; i < this._weights.length; i++) {
  65283. total += this._weights[i];
  65284. if (randomValue <= total) {
  65285. this._currentIndex = i;
  65286. break;
  65287. }
  65288. }
  65289. }
  65290. var sound = this._sounds[this._currentIndex];
  65291. if (sound.isReady()) {
  65292. sound.play(0, this.isPaused ? undefined : startOffset);
  65293. }
  65294. else {
  65295. sound.autoplay = true;
  65296. }
  65297. this.isPlaying = true;
  65298. this.isPaused = false;
  65299. };
  65300. return WeightedSound;
  65301. }());
  65302. BABYLON.WeightedSound = WeightedSound;
  65303. })(BABYLON || (BABYLON = {}));
  65304. //# sourceMappingURL=babylon.weightedsound.js.map
  65305. var BABYLON;
  65306. (function (BABYLON) {
  65307. var CubeTexture = /** @class */ (function (_super) {
  65308. __extends(CubeTexture, _super);
  65309. /**
  65310. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  65311. * as prefiltered data.
  65312. * @param rootUrl defines the url of the texture or the root name of the six images
  65313. * @param scene defines the scene the texture is attached to
  65314. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  65315. * @param noMipmap defines if mipmaps should be created or not
  65316. * @param files defines the six files to load for the different faces
  65317. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  65318. * @param onError defines a callback triggered in case of error during load
  65319. * @param format defines the internal format to use for the texture once loaded
  65320. * @param prefiltered defines whether or not the texture is created from prefiltered data
  65321. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  65322. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  65323. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  65324. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  65325. * @return the cube texture
  65326. */
  65327. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  65328. if (extensions === void 0) { extensions = null; }
  65329. if (noMipmap === void 0) { noMipmap = false; }
  65330. if (files === void 0) { files = null; }
  65331. if (onLoad === void 0) { onLoad = null; }
  65332. if (onError === void 0) { onError = null; }
  65333. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65334. if (prefiltered === void 0) { prefiltered = false; }
  65335. if (forcedExtension === void 0) { forcedExtension = null; }
  65336. if (createPolynomials === void 0) { createPolynomials = false; }
  65337. if (lodScale === void 0) { lodScale = 0.8; }
  65338. if (lodOffset === void 0) { lodOffset = 0; }
  65339. var _this = _super.call(this, scene) || this;
  65340. /**
  65341. * Gets or sets the center of the bounding box associated with the cube texture
  65342. * It must define where the camera used to render the texture was set
  65343. */
  65344. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  65345. _this._rotationY = 0;
  65346. /** @hidden */
  65347. _this._prefiltered = false;
  65348. _this.name = rootUrl;
  65349. _this.url = rootUrl;
  65350. _this._noMipmap = noMipmap;
  65351. _this.hasAlpha = false;
  65352. _this._format = format;
  65353. _this.isCube = true;
  65354. _this._textureMatrix = BABYLON.Matrix.Identity();
  65355. _this._createPolynomials = createPolynomials;
  65356. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65357. if (!rootUrl && !files) {
  65358. return _this;
  65359. }
  65360. var lastDot = rootUrl.lastIndexOf(".");
  65361. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  65362. var isDDS = (extension === ".dds");
  65363. var isEnv = (extension === ".env");
  65364. if (isEnv) {
  65365. _this.gammaSpace = false;
  65366. _this._prefiltered = false;
  65367. }
  65368. else {
  65369. _this._prefiltered = prefiltered;
  65370. if (prefiltered) {
  65371. _this.gammaSpace = false;
  65372. }
  65373. }
  65374. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  65375. if (!files) {
  65376. if (!isEnv && !isDDS && !extensions) {
  65377. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  65378. }
  65379. files = [];
  65380. if (extensions) {
  65381. for (var index = 0; index < extensions.length; index++) {
  65382. files.push(rootUrl + extensions[index]);
  65383. }
  65384. }
  65385. }
  65386. _this._files = files;
  65387. if (!_this._texture) {
  65388. if (!scene.useDelayedTextureLoading) {
  65389. if (prefiltered) {
  65390. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  65391. }
  65392. else {
  65393. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  65394. }
  65395. }
  65396. else {
  65397. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65398. }
  65399. }
  65400. else if (onLoad) {
  65401. if (_this._texture.isReady) {
  65402. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  65403. }
  65404. else {
  65405. _this._texture.onLoadedObservable.add(onLoad);
  65406. }
  65407. }
  65408. return _this;
  65409. }
  65410. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  65411. get: function () {
  65412. return this._boundingBoxSize;
  65413. },
  65414. /**
  65415. * Gets or sets the size of the bounding box associated with the cube texture
  65416. * When defined, the cubemap will switch to local mode
  65417. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65418. * @example https://www.babylonjs-playground.com/#RNASML
  65419. */
  65420. set: function (value) {
  65421. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65422. return;
  65423. }
  65424. this._boundingBoxSize = value;
  65425. var scene = this.getScene();
  65426. if (scene) {
  65427. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65428. }
  65429. },
  65430. enumerable: true,
  65431. configurable: true
  65432. });
  65433. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  65434. /**
  65435. * Gets texture matrix rotation angle around Y axis radians.
  65436. */
  65437. get: function () {
  65438. return this._rotationY;
  65439. },
  65440. /**
  65441. * Sets texture matrix rotation angle around Y axis in radians.
  65442. */
  65443. set: function (value) {
  65444. this._rotationY = value;
  65445. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  65446. },
  65447. enumerable: true,
  65448. configurable: true
  65449. });
  65450. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  65451. var rootUrlKey = "";
  65452. files.forEach(function (url) { return rootUrlKey += url; });
  65453. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  65454. };
  65455. /**
  65456. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  65457. * @param url defines the url of the prefiltered texture
  65458. * @param scene defines the scene the texture is attached to
  65459. * @param forcedExtension defines the extension of the file if different from the url
  65460. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  65461. * @return the prefiltered texture
  65462. */
  65463. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  65464. if (forcedExtension === void 0) { forcedExtension = null; }
  65465. if (createPolynomials === void 0) { createPolynomials = true; }
  65466. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  65467. };
  65468. // Methods
  65469. CubeTexture.prototype.delayLoad = function () {
  65470. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  65471. return;
  65472. }
  65473. var scene = this.getScene();
  65474. if (!scene) {
  65475. return;
  65476. }
  65477. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  65478. this._texture = this._getFromCache(this.url, this._noMipmap);
  65479. if (!this._texture) {
  65480. if (this._prefiltered) {
  65481. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  65482. }
  65483. else {
  65484. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  65485. }
  65486. }
  65487. };
  65488. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  65489. return this._textureMatrix;
  65490. };
  65491. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  65492. this._textureMatrix = value;
  65493. };
  65494. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  65495. var texture = BABYLON.SerializationHelper.Parse(function () {
  65496. var prefiltered = false;
  65497. if (parsedTexture.prefiltered) {
  65498. prefiltered = parsedTexture.prefiltered;
  65499. }
  65500. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  65501. }, parsedTexture, scene);
  65502. // Local Cubemaps
  65503. if (parsedTexture.boundingBoxPosition) {
  65504. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  65505. }
  65506. if (parsedTexture.boundingBoxSize) {
  65507. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  65508. }
  65509. // Animations
  65510. if (parsedTexture.animations) {
  65511. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  65512. var parsedAnimation = parsedTexture.animations[animationIndex];
  65513. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  65514. }
  65515. }
  65516. return texture;
  65517. };
  65518. CubeTexture.prototype.clone = function () {
  65519. var _this = this;
  65520. return BABYLON.SerializationHelper.Clone(function () {
  65521. var scene = _this.getScene();
  65522. if (!scene) {
  65523. return _this;
  65524. }
  65525. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  65526. }, this);
  65527. };
  65528. __decorate([
  65529. BABYLON.serialize("rotationY")
  65530. ], CubeTexture.prototype, "_rotationY", void 0);
  65531. return CubeTexture;
  65532. }(BABYLON.BaseTexture));
  65533. BABYLON.CubeTexture = CubeTexture;
  65534. })(BABYLON || (BABYLON = {}));
  65535. //# sourceMappingURL=babylon.cubeTexture.js.map
  65536. var BABYLON;
  65537. (function (BABYLON) {
  65538. /**
  65539. * Raw cube texture where the raw buffers are passed in
  65540. */
  65541. var RawCubeTexture = /** @class */ (function (_super) {
  65542. __extends(RawCubeTexture, _super);
  65543. /**
  65544. * Creates a cube texture where the raw buffers are passed in.
  65545. * @param scene defines the scene the texture is attached to
  65546. * @param data defines the array of data to use to create each face
  65547. * @param size defines the size of the textures
  65548. * @param format defines the format of the data
  65549. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  65550. * @param generateMipMaps defines if the engine should generate the mip levels
  65551. * @param invertY defines if data must be stored with Y axis inverted
  65552. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  65553. * @param compression defines the compression used (null by default)
  65554. */
  65555. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  65556. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65557. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65558. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65559. if (invertY === void 0) { invertY = false; }
  65560. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65561. if (compression === void 0) { compression = null; }
  65562. var _this = _super.call(this, "", scene) || this;
  65563. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  65564. return _this;
  65565. }
  65566. /**
  65567. * Updates the raw cube texture.
  65568. * @param data defines the data to store
  65569. * @param format defines the data format
  65570. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  65571. * @param invertY defines if data must be stored with Y axis inverted
  65572. * @param compression defines the compression used (null by default)
  65573. * @param level defines which level of the texture to update
  65574. */
  65575. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  65576. if (compression === void 0) { compression = null; }
  65577. if (level === void 0) { level = 0; }
  65578. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  65579. };
  65580. /**
  65581. * Updates a raw cube texture with RGBD encoded data.
  65582. * @param data defines the array of data [mipmap][face] to use to create each face
  65583. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  65584. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  65585. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  65586. * @returns a promsie that resolves when the operation is complete
  65587. */
  65588. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  65589. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  65590. if (lodScale === void 0) { lodScale = 0.8; }
  65591. if (lodOffset === void 0) { lodOffset = 0; }
  65592. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  65593. };
  65594. /**
  65595. * Clones the raw cube texture.
  65596. * @return a new cube texture
  65597. */
  65598. RawCubeTexture.prototype.clone = function () {
  65599. var _this = this;
  65600. return BABYLON.SerializationHelper.Clone(function () {
  65601. var scene = _this.getScene();
  65602. var internalTexture = _this._texture;
  65603. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  65604. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  65605. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  65606. }
  65607. return texture;
  65608. }, this);
  65609. };
  65610. /** @hidden */
  65611. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  65612. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  65613. internalTexture._bufferViewArrayArray = data;
  65614. internalTexture._lodGenerationScale = lodScale;
  65615. internalTexture._lodGenerationOffset = lodOffset;
  65616. internalTexture._sphericalPolynomial = sphericalPolynomial;
  65617. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  65618. internalTexture.isReady = true;
  65619. });
  65620. };
  65621. return RawCubeTexture;
  65622. }(BABYLON.CubeTexture));
  65623. BABYLON.RawCubeTexture = RawCubeTexture;
  65624. })(BABYLON || (BABYLON = {}));
  65625. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  65626. var BABYLON;
  65627. (function (BABYLON) {
  65628. var RenderTargetTexture = /** @class */ (function (_super) {
  65629. __extends(RenderTargetTexture, _super);
  65630. /**
  65631. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  65632. * or used a shadow, depth texture...
  65633. * @param name The friendly name of the texture
  65634. * @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)
  65635. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  65636. * @param generateMipMaps True if mip maps need to be generated after render.
  65637. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  65638. * @param type The type of the buffer in the RTT (int, half float, float...)
  65639. * @param isCube True if a cube texture needs to be created
  65640. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  65641. * @param generateDepthBuffer True to generate a depth buffer
  65642. * @param generateStencilBuffer True to generate a stencil buffer
  65643. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  65644. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  65645. */
  65646. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  65647. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  65648. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65649. if (isCube === void 0) { isCube = false; }
  65650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65651. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  65652. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  65653. if (isMulti === void 0) { isMulti = false; }
  65654. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65655. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65656. _this.isCube = isCube;
  65657. _this.renderParticles = true;
  65658. _this.renderSprites = false;
  65659. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  65660. _this.ignoreCameraViewport = false;
  65661. // Events
  65662. /**
  65663. * An event triggered when the texture is unbind.
  65664. */
  65665. _this.onBeforeBindObservable = new BABYLON.Observable();
  65666. /**
  65667. * An event triggered when the texture is unbind.
  65668. */
  65669. _this.onAfterUnbindObservable = new BABYLON.Observable();
  65670. /**
  65671. * An event triggered before rendering the texture
  65672. */
  65673. _this.onBeforeRenderObservable = new BABYLON.Observable();
  65674. /**
  65675. * An event triggered after rendering the texture
  65676. */
  65677. _this.onAfterRenderObservable = new BABYLON.Observable();
  65678. /**
  65679. * An event triggered after the texture clear
  65680. */
  65681. _this.onClearObservable = new BABYLON.Observable();
  65682. _this._currentRefreshId = -1;
  65683. _this._refreshRate = 1;
  65684. _this._samples = 1;
  65685. /**
  65686. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  65687. * It must define where the camera used to render the texture is set
  65688. */
  65689. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  65690. scene = _this.getScene();
  65691. if (!scene) {
  65692. return _this;
  65693. }
  65694. _this.renderList = new Array();
  65695. _this._engine = scene.getEngine();
  65696. _this.name = name;
  65697. _this.isRenderTarget = true;
  65698. _this._initialSizeParameter = size;
  65699. _this._processSizeParameter(size);
  65700. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  65701. });
  65702. _this._generateMipMaps = generateMipMaps ? true : false;
  65703. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  65704. // Rendering groups
  65705. _this._renderingManager = new BABYLON.RenderingManager(scene);
  65706. _this._renderingManager._useSceneAutoClearSetup = true;
  65707. if (isMulti) {
  65708. return _this;
  65709. }
  65710. _this._renderTargetOptions = {
  65711. generateMipMaps: generateMipMaps,
  65712. type: type,
  65713. format: format,
  65714. samplingMode: samplingMode,
  65715. generateDepthBuffer: generateDepthBuffer,
  65716. generateStencilBuffer: generateStencilBuffer
  65717. };
  65718. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  65719. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65720. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65721. }
  65722. if (isCube) {
  65723. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  65724. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  65725. _this._textureMatrix = BABYLON.Matrix.Identity();
  65726. }
  65727. else {
  65728. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  65729. }
  65730. return _this;
  65731. }
  65732. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  65733. get: function () {
  65734. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  65735. },
  65736. enumerable: true,
  65737. configurable: true
  65738. });
  65739. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  65740. get: function () {
  65741. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  65742. },
  65743. enumerable: true,
  65744. configurable: true
  65745. });
  65746. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  65747. get: function () {
  65748. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  65749. },
  65750. enumerable: true,
  65751. configurable: true
  65752. });
  65753. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  65754. /**
  65755. * Use this list to define the list of mesh you want to render.
  65756. */
  65757. get: function () {
  65758. return this._renderList;
  65759. },
  65760. set: function (value) {
  65761. this._renderList = value;
  65762. if (this._renderList) {
  65763. this._hookArray(this._renderList);
  65764. }
  65765. },
  65766. enumerable: true,
  65767. configurable: true
  65768. });
  65769. RenderTargetTexture.prototype._hookArray = function (array) {
  65770. var _this = this;
  65771. var oldPush = array.push;
  65772. array.push = function () {
  65773. var items = [];
  65774. for (var _i = 0; _i < arguments.length; _i++) {
  65775. items[_i] = arguments[_i];
  65776. }
  65777. var result = oldPush.apply(array, items);
  65778. _this.getScene().meshes.forEach(function (mesh) {
  65779. mesh._markSubMeshesAsLightDirty();
  65780. });
  65781. return result;
  65782. };
  65783. var oldSplice = array.splice;
  65784. array.splice = function (index, deleteCount) {
  65785. var deleted = oldSplice.apply(array, [index, deleteCount]);
  65786. _this.getScene().meshes.forEach(function (mesh) {
  65787. mesh._markSubMeshesAsLightDirty();
  65788. });
  65789. return deleted;
  65790. };
  65791. };
  65792. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  65793. set: function (callback) {
  65794. if (this._onAfterUnbindObserver) {
  65795. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  65796. }
  65797. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  65798. },
  65799. enumerable: true,
  65800. configurable: true
  65801. });
  65802. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  65803. set: function (callback) {
  65804. if (this._onBeforeRenderObserver) {
  65805. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65806. }
  65807. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65808. },
  65809. enumerable: true,
  65810. configurable: true
  65811. });
  65812. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  65813. set: function (callback) {
  65814. if (this._onAfterRenderObserver) {
  65815. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65816. }
  65817. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65818. },
  65819. enumerable: true,
  65820. configurable: true
  65821. });
  65822. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  65823. set: function (callback) {
  65824. if (this._onClearObserver) {
  65825. this.onClearObservable.remove(this._onClearObserver);
  65826. }
  65827. this._onClearObserver = this.onClearObservable.add(callback);
  65828. },
  65829. enumerable: true,
  65830. configurable: true
  65831. });
  65832. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  65833. get: function () {
  65834. return this._renderTargetOptions;
  65835. },
  65836. enumerable: true,
  65837. configurable: true
  65838. });
  65839. RenderTargetTexture.prototype._onRatioRescale = function () {
  65840. if (this._sizeRatio) {
  65841. this.resize(this._initialSizeParameter);
  65842. }
  65843. };
  65844. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  65845. get: function () {
  65846. return this._boundingBoxSize;
  65847. },
  65848. /**
  65849. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  65850. * When defined, the cubemap will switch to local mode
  65851. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65852. * @example https://www.babylonjs-playground.com/#RNASML
  65853. */
  65854. set: function (value) {
  65855. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65856. return;
  65857. }
  65858. this._boundingBoxSize = value;
  65859. var scene = this.getScene();
  65860. if (scene) {
  65861. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65862. }
  65863. },
  65864. enumerable: true,
  65865. configurable: true
  65866. });
  65867. /**
  65868. * Creates a depth stencil texture.
  65869. * This is only available in WebGL 2 or with the depth texture extension available.
  65870. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  65871. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  65872. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  65873. */
  65874. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  65875. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  65876. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  65877. if (generateStencil === void 0) { generateStencil = false; }
  65878. if (!this.getScene()) {
  65879. return;
  65880. }
  65881. var engine = this.getScene().getEngine();
  65882. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  65883. bilinearFiltering: bilinearFiltering,
  65884. comparisonFunction: comparisonFunction,
  65885. generateStencil: generateStencil,
  65886. isCube: this.isCube
  65887. });
  65888. engine.setFrameBufferDepthStencilTexture(this);
  65889. };
  65890. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  65891. if (size.ratio) {
  65892. this._sizeRatio = size.ratio;
  65893. this._size = {
  65894. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  65895. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  65896. };
  65897. }
  65898. else {
  65899. this._size = size;
  65900. }
  65901. };
  65902. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  65903. get: function () {
  65904. return this._samples;
  65905. },
  65906. set: function (value) {
  65907. if (this._samples === value) {
  65908. return;
  65909. }
  65910. var scene = this.getScene();
  65911. if (!scene) {
  65912. return;
  65913. }
  65914. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  65915. },
  65916. enumerable: true,
  65917. configurable: true
  65918. });
  65919. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  65920. this._currentRefreshId = -1;
  65921. };
  65922. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  65923. get: function () {
  65924. return this._refreshRate;
  65925. },
  65926. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65927. set: function (value) {
  65928. this._refreshRate = value;
  65929. this.resetRefreshCounter();
  65930. },
  65931. enumerable: true,
  65932. configurable: true
  65933. });
  65934. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  65935. if (!this._postProcessManager) {
  65936. var scene = this.getScene();
  65937. if (!scene) {
  65938. return;
  65939. }
  65940. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  65941. this._postProcesses = new Array();
  65942. }
  65943. this._postProcesses.push(postProcess);
  65944. this._postProcesses[0].autoClear = false;
  65945. };
  65946. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  65947. if (!this._postProcesses) {
  65948. return;
  65949. }
  65950. if (dispose) {
  65951. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  65952. var postProcess = _a[_i];
  65953. postProcess.dispose();
  65954. }
  65955. }
  65956. this._postProcesses = [];
  65957. };
  65958. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  65959. if (!this._postProcesses) {
  65960. return;
  65961. }
  65962. var index = this._postProcesses.indexOf(postProcess);
  65963. if (index === -1) {
  65964. return;
  65965. }
  65966. this._postProcesses.splice(index, 1);
  65967. if (this._postProcesses.length > 0) {
  65968. this._postProcesses[0].autoClear = false;
  65969. }
  65970. };
  65971. RenderTargetTexture.prototype._shouldRender = function () {
  65972. if (this._currentRefreshId === -1) { // At least render once
  65973. this._currentRefreshId = 1;
  65974. return true;
  65975. }
  65976. if (this.refreshRate === this._currentRefreshId) {
  65977. this._currentRefreshId = 1;
  65978. return true;
  65979. }
  65980. this._currentRefreshId++;
  65981. return false;
  65982. };
  65983. RenderTargetTexture.prototype.getRenderSize = function () {
  65984. if (this._size.width) {
  65985. return this._size.width;
  65986. }
  65987. return this._size;
  65988. };
  65989. RenderTargetTexture.prototype.getRenderWidth = function () {
  65990. if (this._size.width) {
  65991. return this._size.width;
  65992. }
  65993. return this._size;
  65994. };
  65995. RenderTargetTexture.prototype.getRenderHeight = function () {
  65996. if (this._size.width) {
  65997. return this._size.height;
  65998. }
  65999. return this._size;
  66000. };
  66001. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  66002. get: function () {
  66003. return true;
  66004. },
  66005. enumerable: true,
  66006. configurable: true
  66007. });
  66008. RenderTargetTexture.prototype.scale = function (ratio) {
  66009. var newSize = this.getRenderSize() * ratio;
  66010. this.resize(newSize);
  66011. };
  66012. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  66013. if (this.isCube) {
  66014. return this._textureMatrix;
  66015. }
  66016. return _super.prototype.getReflectionTextureMatrix.call(this);
  66017. };
  66018. RenderTargetTexture.prototype.resize = function (size) {
  66019. this.releaseInternalTexture();
  66020. var scene = this.getScene();
  66021. if (!scene) {
  66022. return;
  66023. }
  66024. this._processSizeParameter(size);
  66025. if (this.isCube) {
  66026. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  66027. }
  66028. else {
  66029. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  66030. }
  66031. };
  66032. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  66033. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  66034. if (dumpForDebug === void 0) { dumpForDebug = false; }
  66035. var scene = this.getScene();
  66036. if (!scene) {
  66037. return;
  66038. }
  66039. var engine = scene.getEngine();
  66040. if (this.useCameraPostProcesses !== undefined) {
  66041. useCameraPostProcess = this.useCameraPostProcesses;
  66042. }
  66043. if (this._waitingRenderList) {
  66044. this.renderList = [];
  66045. for (var index = 0; index < this._waitingRenderList.length; index++) {
  66046. var id = this._waitingRenderList[index];
  66047. var mesh_1 = scene.getMeshByID(id);
  66048. if (mesh_1) {
  66049. this.renderList.push(mesh_1);
  66050. }
  66051. }
  66052. delete this._waitingRenderList;
  66053. }
  66054. // Is predicate defined?
  66055. if (this.renderListPredicate) {
  66056. if (this.renderList) {
  66057. this.renderList.splice(0); // Clear previous renderList
  66058. }
  66059. else {
  66060. this.renderList = [];
  66061. }
  66062. var scene = this.getScene();
  66063. if (!scene) {
  66064. return;
  66065. }
  66066. var sceneMeshes = scene.meshes;
  66067. for (var index = 0; index < sceneMeshes.length; index++) {
  66068. var mesh = sceneMeshes[index];
  66069. if (this.renderListPredicate(mesh)) {
  66070. this.renderList.push(mesh);
  66071. }
  66072. }
  66073. }
  66074. this.onBeforeBindObservable.notifyObservers(this);
  66075. // Set custom projection.
  66076. // Needs to be before binding to prevent changing the aspect ratio.
  66077. var camera;
  66078. if (this.activeCamera) {
  66079. camera = this.activeCamera;
  66080. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66081. if (this.activeCamera !== scene.activeCamera) {
  66082. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  66083. }
  66084. }
  66085. else {
  66086. camera = scene.activeCamera;
  66087. if (camera) {
  66088. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66089. }
  66090. }
  66091. // Prepare renderingManager
  66092. this._renderingManager.reset();
  66093. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  66094. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  66095. var sceneRenderId = scene.getRenderId();
  66096. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  66097. var mesh = currentRenderList[meshIndex];
  66098. if (mesh) {
  66099. if (!mesh.isReady(this.refreshRate === 0)) {
  66100. this.resetRefreshCounter();
  66101. continue;
  66102. }
  66103. mesh._preActivateForIntermediateRendering(sceneRenderId);
  66104. var isMasked = void 0;
  66105. if (!this.renderList && camera) {
  66106. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  66107. }
  66108. else {
  66109. isMasked = false;
  66110. }
  66111. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  66112. mesh._activate(sceneRenderId);
  66113. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  66114. var subMesh = mesh.subMeshes[subIndex];
  66115. scene._activeIndices.addCount(subMesh.indexCount, false);
  66116. this._renderingManager.dispatch(subMesh, mesh);
  66117. }
  66118. }
  66119. }
  66120. }
  66121. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  66122. var particleSystem = scene.particleSystems[particleIndex];
  66123. var emitter = particleSystem.emitter;
  66124. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  66125. continue;
  66126. }
  66127. if (currentRenderList.indexOf(emitter) >= 0) {
  66128. this._renderingManager.dispatchParticles(particleSystem);
  66129. }
  66130. }
  66131. if (this.isCube) {
  66132. for (var face = 0; face < 6; face++) {
  66133. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66134. scene.incrementRenderId();
  66135. scene.resetCachedMaterial();
  66136. }
  66137. }
  66138. else {
  66139. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66140. }
  66141. this.onAfterUnbindObservable.notifyObservers(this);
  66142. if (scene.activeCamera) {
  66143. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  66144. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  66145. }
  66146. engine.setViewport(scene.activeCamera.viewport);
  66147. }
  66148. scene.resetCachedMaterial();
  66149. };
  66150. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  66151. var minimum = 128;
  66152. var x = renderDimension * scale;
  66153. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  66154. // Ensure we don't exceed the render dimension (while staying POT)
  66155. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  66156. };
  66157. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66158. var _this = this;
  66159. if (!this._texture) {
  66160. return;
  66161. }
  66162. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  66163. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  66164. });
  66165. };
  66166. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  66167. var scene = this.getScene();
  66168. if (!scene) {
  66169. return;
  66170. }
  66171. var engine = scene.getEngine();
  66172. if (!this._texture) {
  66173. return;
  66174. }
  66175. // Bind
  66176. if (this._postProcessManager) {
  66177. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  66178. }
  66179. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  66180. if (this._texture) {
  66181. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  66182. }
  66183. }
  66184. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  66185. // Clear
  66186. if (this.onClearObservable.hasObservers()) {
  66187. this.onClearObservable.notifyObservers(engine);
  66188. }
  66189. else {
  66190. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  66191. }
  66192. if (!this._doNotChangeAspectRatio) {
  66193. scene.updateTransformMatrix(true);
  66194. }
  66195. // Render
  66196. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  66197. if (this._postProcessManager) {
  66198. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  66199. }
  66200. else if (useCameraPostProcess) {
  66201. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  66202. }
  66203. if (!this._doNotChangeAspectRatio) {
  66204. scene.updateTransformMatrix(true);
  66205. }
  66206. // Dump ?
  66207. if (dumpForDebug) {
  66208. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  66209. }
  66210. // Unbind
  66211. if (!this.isCube || faceIndex === 5) {
  66212. if (this.isCube) {
  66213. if (faceIndex === 5) {
  66214. engine.generateMipMapsForCubemap(this._texture);
  66215. }
  66216. }
  66217. this.unbindFrameBuffer(engine, faceIndex);
  66218. }
  66219. else {
  66220. this.onAfterRenderObservable.notifyObservers(faceIndex);
  66221. }
  66222. };
  66223. /**
  66224. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  66225. * This allowed control for front to back rendering or reversly depending of the special needs.
  66226. *
  66227. * @param renderingGroupId The rendering group id corresponding to its index
  66228. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  66229. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  66230. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  66231. */
  66232. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  66233. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  66234. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  66235. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  66236. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  66237. };
  66238. /**
  66239. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  66240. *
  66241. * @param renderingGroupId The rendering group id corresponding to its index
  66242. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  66243. */
  66244. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  66245. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  66246. this._renderingManager._useSceneAutoClearSetup = false;
  66247. };
  66248. RenderTargetTexture.prototype.clone = function () {
  66249. var textureSize = this.getSize();
  66250. 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);
  66251. // Base texture
  66252. newTexture.hasAlpha = this.hasAlpha;
  66253. newTexture.level = this.level;
  66254. // RenderTarget Texture
  66255. newTexture.coordinatesMode = this.coordinatesMode;
  66256. if (this.renderList) {
  66257. newTexture.renderList = this.renderList.slice(0);
  66258. }
  66259. return newTexture;
  66260. };
  66261. RenderTargetTexture.prototype.serialize = function () {
  66262. if (!this.name) {
  66263. return null;
  66264. }
  66265. var serializationObject = _super.prototype.serialize.call(this);
  66266. serializationObject.renderTargetSize = this.getRenderSize();
  66267. serializationObject.renderList = [];
  66268. if (this.renderList) {
  66269. for (var index = 0; index < this.renderList.length; index++) {
  66270. serializationObject.renderList.push(this.renderList[index].id);
  66271. }
  66272. }
  66273. return serializationObject;
  66274. };
  66275. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  66276. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  66277. var objBuffer = this.getInternalTexture();
  66278. var scene = this.getScene();
  66279. if (objBuffer && scene) {
  66280. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  66281. }
  66282. };
  66283. RenderTargetTexture.prototype.dispose = function () {
  66284. if (this._postProcessManager) {
  66285. this._postProcessManager.dispose();
  66286. this._postProcessManager = null;
  66287. }
  66288. this.clearPostProcesses(true);
  66289. if (this._resizeObserver) {
  66290. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  66291. this._resizeObserver = null;
  66292. }
  66293. this.renderList = null;
  66294. // Remove from custom render targets
  66295. var scene = this.getScene();
  66296. if (!scene) {
  66297. return;
  66298. }
  66299. var index = scene.customRenderTargets.indexOf(this);
  66300. if (index >= 0) {
  66301. scene.customRenderTargets.splice(index, 1);
  66302. }
  66303. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  66304. var camera = _a[_i];
  66305. index = camera.customRenderTargets.indexOf(this);
  66306. if (index >= 0) {
  66307. camera.customRenderTargets.splice(index, 1);
  66308. }
  66309. }
  66310. _super.prototype.dispose.call(this);
  66311. };
  66312. RenderTargetTexture.prototype._rebuild = function () {
  66313. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  66314. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  66315. }
  66316. if (this._postProcessManager) {
  66317. this._postProcessManager._rebuild();
  66318. }
  66319. };
  66320. /**
  66321. * Clear the info related to rendering groups preventing retention point in material dispose.
  66322. */
  66323. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  66324. if (this._renderingManager) {
  66325. this._renderingManager.freeRenderingGroups();
  66326. }
  66327. };
  66328. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  66329. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  66330. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  66331. return RenderTargetTexture;
  66332. }(BABYLON.Texture));
  66333. BABYLON.RenderTargetTexture = RenderTargetTexture;
  66334. })(BABYLON || (BABYLON = {}));
  66335. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  66336. var BABYLON;
  66337. (function (BABYLON) {
  66338. ;
  66339. var MultiRenderTarget = /** @class */ (function (_super) {
  66340. __extends(MultiRenderTarget, _super);
  66341. function MultiRenderTarget(name, size, count, scene, options) {
  66342. var _this = this;
  66343. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  66344. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  66345. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  66346. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  66347. _this._engine = scene.getEngine();
  66348. if (!_this.isSupported) {
  66349. _this.dispose();
  66350. return;
  66351. }
  66352. var types = [];
  66353. var samplingModes = [];
  66354. for (var i = 0; i < count; i++) {
  66355. if (options && options.types && options.types[i] !== undefined) {
  66356. types.push(options.types[i]);
  66357. }
  66358. else {
  66359. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  66360. }
  66361. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  66362. samplingModes.push(options.samplingModes[i]);
  66363. }
  66364. else {
  66365. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66366. }
  66367. }
  66368. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  66369. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  66370. _this._size = size;
  66371. _this._multiRenderTargetOptions = {
  66372. samplingModes: samplingModes,
  66373. generateMipMaps: generateMipMaps,
  66374. generateDepthBuffer: generateDepthBuffer,
  66375. generateStencilBuffer: generateStencilBuffer,
  66376. generateDepthTexture: generateDepthTexture,
  66377. types: types,
  66378. textureCount: count
  66379. };
  66380. _this._createInternalTextures();
  66381. _this._createTextures();
  66382. return _this;
  66383. }
  66384. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  66385. get: function () {
  66386. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  66387. },
  66388. enumerable: true,
  66389. configurable: true
  66390. });
  66391. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  66392. get: function () {
  66393. return this._textures;
  66394. },
  66395. enumerable: true,
  66396. configurable: true
  66397. });
  66398. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  66399. get: function () {
  66400. return this._textures[this._textures.length - 1];
  66401. },
  66402. enumerable: true,
  66403. configurable: true
  66404. });
  66405. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  66406. set: function (wrap) {
  66407. if (this._textures) {
  66408. for (var i = 0; i < this._textures.length; i++) {
  66409. this._textures[i].wrapU = wrap;
  66410. }
  66411. }
  66412. },
  66413. enumerable: true,
  66414. configurable: true
  66415. });
  66416. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  66417. set: function (wrap) {
  66418. if (this._textures) {
  66419. for (var i = 0; i < this._textures.length; i++) {
  66420. this._textures[i].wrapV = wrap;
  66421. }
  66422. }
  66423. },
  66424. enumerable: true,
  66425. configurable: true
  66426. });
  66427. MultiRenderTarget.prototype._rebuild = function () {
  66428. this.releaseInternalTextures();
  66429. this._createInternalTextures();
  66430. for (var i = 0; i < this._internalTextures.length; i++) {
  66431. var texture = this._textures[i];
  66432. texture._texture = this._internalTextures[i];
  66433. }
  66434. // Keeps references to frame buffer and stencil/depth buffer
  66435. this._texture = this._internalTextures[0];
  66436. };
  66437. MultiRenderTarget.prototype._createInternalTextures = function () {
  66438. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  66439. };
  66440. MultiRenderTarget.prototype._createTextures = function () {
  66441. this._textures = [];
  66442. for (var i = 0; i < this._internalTextures.length; i++) {
  66443. var texture = new BABYLON.Texture(null, this.getScene());
  66444. texture._texture = this._internalTextures[i];
  66445. this._textures.push(texture);
  66446. }
  66447. // Keeps references to frame buffer and stencil/depth buffer
  66448. this._texture = this._internalTextures[0];
  66449. };
  66450. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  66451. get: function () {
  66452. return this._samples;
  66453. },
  66454. set: function (value) {
  66455. if (this._samples === value) {
  66456. return;
  66457. }
  66458. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  66459. },
  66460. enumerable: true,
  66461. configurable: true
  66462. });
  66463. MultiRenderTarget.prototype.resize = function (size) {
  66464. this.releaseInternalTextures();
  66465. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  66466. this._createInternalTextures();
  66467. };
  66468. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66469. var _this = this;
  66470. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  66471. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  66472. });
  66473. };
  66474. MultiRenderTarget.prototype.dispose = function () {
  66475. this.releaseInternalTextures();
  66476. _super.prototype.dispose.call(this);
  66477. };
  66478. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  66479. if (!this._internalTextures) {
  66480. return;
  66481. }
  66482. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  66483. if (this._internalTextures[i] !== undefined) {
  66484. this._internalTextures[i].dispose();
  66485. this._internalTextures.splice(i, 1);
  66486. }
  66487. }
  66488. };
  66489. return MultiRenderTarget;
  66490. }(BABYLON.RenderTargetTexture));
  66491. BABYLON.MultiRenderTarget = MultiRenderTarget;
  66492. })(BABYLON || (BABYLON = {}));
  66493. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  66494. var BABYLON;
  66495. (function (BABYLON) {
  66496. var MirrorTexture = /** @class */ (function (_super) {
  66497. __extends(MirrorTexture, _super);
  66498. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  66499. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66500. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66501. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66502. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  66503. _this.scene = scene;
  66504. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  66505. _this._transformMatrix = BABYLON.Matrix.Zero();
  66506. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  66507. _this._adaptiveBlurKernel = 0;
  66508. _this._blurKernelX = 0;
  66509. _this._blurKernelY = 0;
  66510. _this._blurRatio = 1.0;
  66511. _this.ignoreCameraViewport = true;
  66512. _this._updateGammaSpace();
  66513. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  66514. _this._updateGammaSpace;
  66515. });
  66516. _this.onBeforeRenderObservable.add(function () {
  66517. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  66518. _this._savedViewMatrix = scene.getViewMatrix();
  66519. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  66520. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  66521. scene.clipPlane = _this.mirrorPlane;
  66522. scene.getEngine().cullBackFaces = false;
  66523. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  66524. });
  66525. _this.onAfterRenderObservable.add(function () {
  66526. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  66527. scene.getEngine().cullBackFaces = true;
  66528. scene._mirroredCameraPosition = null;
  66529. delete scene.clipPlane;
  66530. });
  66531. return _this;
  66532. }
  66533. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  66534. get: function () {
  66535. return this._blurRatio;
  66536. },
  66537. set: function (value) {
  66538. if (this._blurRatio === value) {
  66539. return;
  66540. }
  66541. this._blurRatio = value;
  66542. this._preparePostProcesses();
  66543. },
  66544. enumerable: true,
  66545. configurable: true
  66546. });
  66547. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  66548. set: function (value) {
  66549. this._adaptiveBlurKernel = value;
  66550. this._autoComputeBlurKernel();
  66551. },
  66552. enumerable: true,
  66553. configurable: true
  66554. });
  66555. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  66556. set: function (value) {
  66557. this.blurKernelX = value;
  66558. this.blurKernelY = value;
  66559. },
  66560. enumerable: true,
  66561. configurable: true
  66562. });
  66563. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  66564. get: function () {
  66565. return this._blurKernelX;
  66566. },
  66567. set: function (value) {
  66568. if (this._blurKernelX === value) {
  66569. return;
  66570. }
  66571. this._blurKernelX = value;
  66572. this._preparePostProcesses();
  66573. },
  66574. enumerable: true,
  66575. configurable: true
  66576. });
  66577. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  66578. get: function () {
  66579. return this._blurKernelY;
  66580. },
  66581. set: function (value) {
  66582. if (this._blurKernelY === value) {
  66583. return;
  66584. }
  66585. this._blurKernelY = value;
  66586. this._preparePostProcesses();
  66587. },
  66588. enumerable: true,
  66589. configurable: true
  66590. });
  66591. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  66592. var engine = this.getScene().getEngine();
  66593. var dw = this.getRenderWidth() / engine.getRenderWidth();
  66594. var dh = this.getRenderHeight() / engine.getRenderHeight();
  66595. this.blurKernelX = this._adaptiveBlurKernel * dw;
  66596. this.blurKernelY = this._adaptiveBlurKernel * dh;
  66597. };
  66598. MirrorTexture.prototype._onRatioRescale = function () {
  66599. if (this._sizeRatio) {
  66600. this.resize(this._initialSizeParameter);
  66601. if (!this._adaptiveBlurKernel) {
  66602. this._preparePostProcesses();
  66603. }
  66604. }
  66605. if (this._adaptiveBlurKernel) {
  66606. this._autoComputeBlurKernel();
  66607. }
  66608. };
  66609. MirrorTexture.prototype._updateGammaSpace = function () {
  66610. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  66611. };
  66612. MirrorTexture.prototype._preparePostProcesses = function () {
  66613. this.clearPostProcesses(true);
  66614. if (this._blurKernelX && this._blurKernelY) {
  66615. var engine = this.getScene().getEngine();
  66616. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66617. 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);
  66618. this._blurX.autoClear = false;
  66619. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  66620. this._blurX.inputTexture = this._texture;
  66621. }
  66622. else {
  66623. this._blurX.alwaysForcePOT = true;
  66624. }
  66625. 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);
  66626. this._blurY.autoClear = false;
  66627. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  66628. this.addPostProcess(this._blurX);
  66629. this.addPostProcess(this._blurY);
  66630. }
  66631. else {
  66632. if (this._blurY) {
  66633. this.removePostProcess(this._blurY);
  66634. this._blurY.dispose();
  66635. this._blurY = null;
  66636. }
  66637. if (this._blurX) {
  66638. this.removePostProcess(this._blurX);
  66639. this._blurX.dispose();
  66640. this._blurX = null;
  66641. }
  66642. }
  66643. };
  66644. MirrorTexture.prototype.clone = function () {
  66645. var scene = this.getScene();
  66646. if (!scene) {
  66647. return this;
  66648. }
  66649. var textureSize = this.getSize();
  66650. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  66651. // Base texture
  66652. newTexture.hasAlpha = this.hasAlpha;
  66653. newTexture.level = this.level;
  66654. // Mirror Texture
  66655. newTexture.mirrorPlane = this.mirrorPlane.clone();
  66656. if (this.renderList) {
  66657. newTexture.renderList = this.renderList.slice(0);
  66658. }
  66659. return newTexture;
  66660. };
  66661. MirrorTexture.prototype.serialize = function () {
  66662. if (!this.name) {
  66663. return null;
  66664. }
  66665. var serializationObject = _super.prototype.serialize.call(this);
  66666. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  66667. return serializationObject;
  66668. };
  66669. MirrorTexture.prototype.dispose = function () {
  66670. _super.prototype.dispose.call(this);
  66671. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  66672. };
  66673. return MirrorTexture;
  66674. }(BABYLON.RenderTargetTexture));
  66675. BABYLON.MirrorTexture = MirrorTexture;
  66676. })(BABYLON || (BABYLON = {}));
  66677. //# sourceMappingURL=babylon.mirrorTexture.js.map
  66678. var BABYLON;
  66679. (function (BABYLON) {
  66680. /**
  66681. * Creates a refraction texture used by refraction channel of the standard material.
  66682. * @param name the texture name
  66683. * @param size size of the underlying texture
  66684. * @param scene root scene
  66685. */
  66686. var RefractionTexture = /** @class */ (function (_super) {
  66687. __extends(RefractionTexture, _super);
  66688. function RefractionTexture(name, size, scene, generateMipMaps) {
  66689. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  66690. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  66691. _this.depth = 2.0;
  66692. _this.onBeforeRenderObservable.add(function () {
  66693. scene.clipPlane = _this.refractionPlane;
  66694. });
  66695. _this.onAfterRenderObservable.add(function () {
  66696. delete scene.clipPlane;
  66697. });
  66698. return _this;
  66699. }
  66700. RefractionTexture.prototype.clone = function () {
  66701. var scene = this.getScene();
  66702. if (!scene) {
  66703. return this;
  66704. }
  66705. var textureSize = this.getSize();
  66706. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  66707. // Base texture
  66708. newTexture.hasAlpha = this.hasAlpha;
  66709. newTexture.level = this.level;
  66710. // Refraction Texture
  66711. newTexture.refractionPlane = this.refractionPlane.clone();
  66712. if (this.renderList) {
  66713. newTexture.renderList = this.renderList.slice(0);
  66714. }
  66715. newTexture.depth = this.depth;
  66716. return newTexture;
  66717. };
  66718. RefractionTexture.prototype.serialize = function () {
  66719. if (!this.name) {
  66720. return null;
  66721. }
  66722. var serializationObject = _super.prototype.serialize.call(this);
  66723. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  66724. serializationObject.depth = this.depth;
  66725. return serializationObject;
  66726. };
  66727. return RefractionTexture;
  66728. }(BABYLON.RenderTargetTexture));
  66729. BABYLON.RefractionTexture = RefractionTexture;
  66730. })(BABYLON || (BABYLON = {}));
  66731. //# sourceMappingURL=babylon.refractionTexture.js.map
  66732. var BABYLON;
  66733. (function (BABYLON) {
  66734. /**
  66735. * A class extending {BABYLON.Texture} allowing drawing on a texture
  66736. * @see http://doc.babylonjs.com/how_to/dynamictexture
  66737. */
  66738. var DynamicTexture = /** @class */ (function (_super) {
  66739. __extends(DynamicTexture, _super);
  66740. /**
  66741. * Creates a {BABYLON.DynamicTexture}
  66742. * @param name defines the name of the texture
  66743. * @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
  66744. * @param scene defines the scene where you want the texture
  66745. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  66746. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  66747. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  66748. */
  66749. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  66750. if (scene === void 0) { scene = null; }
  66751. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66752. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66753. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  66754. _this.name = name;
  66755. _this._engine = _this.getScene().getEngine();
  66756. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66757. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66758. _this._generateMipMaps = generateMipMaps;
  66759. if (options.getContext) {
  66760. _this._canvas = options;
  66761. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66762. }
  66763. else {
  66764. _this._canvas = document.createElement("canvas");
  66765. if (options.width || options.width === 0) {
  66766. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66767. }
  66768. else {
  66769. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  66770. }
  66771. }
  66772. var textureSize = _this.getSize();
  66773. _this._canvas.width = textureSize.width;
  66774. _this._canvas.height = textureSize.height;
  66775. _this._context = _this._canvas.getContext("2d");
  66776. return _this;
  66777. }
  66778. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  66779. /**
  66780. * Gets the current state of canRescale
  66781. */
  66782. get: function () {
  66783. return true;
  66784. },
  66785. enumerable: true,
  66786. configurable: true
  66787. });
  66788. DynamicTexture.prototype._recreate = function (textureSize) {
  66789. this._canvas.width = textureSize.width;
  66790. this._canvas.height = textureSize.height;
  66791. this.releaseInternalTexture();
  66792. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  66793. };
  66794. /**
  66795. * Scales the texture
  66796. * @param ratio the scale factor to apply to both width and height
  66797. */
  66798. DynamicTexture.prototype.scale = function (ratio) {
  66799. var textureSize = this.getSize();
  66800. textureSize.width *= ratio;
  66801. textureSize.height *= ratio;
  66802. this._recreate(textureSize);
  66803. };
  66804. /**
  66805. * Resizes the texture
  66806. * @param width the new width
  66807. * @param height the new height
  66808. */
  66809. DynamicTexture.prototype.scaleTo = function (width, height) {
  66810. var textureSize = this.getSize();
  66811. textureSize.width = width;
  66812. textureSize.height = height;
  66813. this._recreate(textureSize);
  66814. };
  66815. /**
  66816. * Gets the context of the canvas used by the texture
  66817. * @returns the canvas context of the dynamic texture
  66818. */
  66819. DynamicTexture.prototype.getContext = function () {
  66820. return this._context;
  66821. };
  66822. /**
  66823. * Clears the texture
  66824. */
  66825. DynamicTexture.prototype.clear = function () {
  66826. var size = this.getSize();
  66827. this._context.fillRect(0, 0, size.width, size.height);
  66828. };
  66829. /**
  66830. * Updates the texture
  66831. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66832. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  66833. */
  66834. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  66835. if (premulAlpha === void 0) { premulAlpha = false; }
  66836. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  66837. };
  66838. /**
  66839. * Draws text onto the texture
  66840. * @param text defines the text to be drawn
  66841. * @param x defines the placement of the text from the left
  66842. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  66843. * @param font defines the font to be used with font-style, font-size, font-name
  66844. * @param color defines the color used for the text
  66845. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  66846. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66847. * @param update defines whether texture is immediately update (default is true)
  66848. */
  66849. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  66850. if (update === void 0) { update = true; }
  66851. var size = this.getSize();
  66852. if (clearColor) {
  66853. this._context.fillStyle = clearColor;
  66854. this._context.fillRect(0, 0, size.width, size.height);
  66855. }
  66856. this._context.font = font;
  66857. if (x === null || x === undefined) {
  66858. var textSize = this._context.measureText(text);
  66859. x = (size.width - textSize.width) / 2;
  66860. }
  66861. if (y === null || y === undefined) {
  66862. var fontSize = parseInt((font.replace(/\D/g, '')));
  66863. y = (size.height / 2) + (fontSize / 3.65);
  66864. }
  66865. this._context.fillStyle = color;
  66866. this._context.fillText(text, x, y);
  66867. if (update) {
  66868. this.update(invertY);
  66869. }
  66870. };
  66871. /**
  66872. * Clones the texture
  66873. * @returns the clone of the texture.
  66874. */
  66875. DynamicTexture.prototype.clone = function () {
  66876. var scene = this.getScene();
  66877. if (!scene) {
  66878. return this;
  66879. }
  66880. var textureSize = this.getSize();
  66881. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  66882. // Base texture
  66883. newTexture.hasAlpha = this.hasAlpha;
  66884. newTexture.level = this.level;
  66885. // Dynamic Texture
  66886. newTexture.wrapU = this.wrapU;
  66887. newTexture.wrapV = this.wrapV;
  66888. return newTexture;
  66889. };
  66890. /**
  66891. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  66892. * @returns a serialized dynamic texture object
  66893. */
  66894. DynamicTexture.prototype.serialize = function () {
  66895. var scene = this.getScene();
  66896. if (scene && !scene.isReady()) {
  66897. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  66898. }
  66899. var serializationObject = _super.prototype.serialize.call(this);
  66900. serializationObject.base64String = this._canvas.toDataURL();
  66901. serializationObject.invertY = this._invertY;
  66902. serializationObject.samplingMode = this.samplingMode;
  66903. return serializationObject;
  66904. };
  66905. /** @hidden */
  66906. DynamicTexture.prototype._rebuild = function () {
  66907. this.update();
  66908. };
  66909. return DynamicTexture;
  66910. }(BABYLON.Texture));
  66911. BABYLON.DynamicTexture = DynamicTexture;
  66912. })(BABYLON || (BABYLON = {}));
  66913. //# sourceMappingURL=babylon.dynamicTexture.js.map
  66914. var BABYLON;
  66915. (function (BABYLON) {
  66916. var VideoTexture = /** @class */ (function (_super) {
  66917. __extends(VideoTexture, _super);
  66918. /**
  66919. * Creates a video texture.
  66920. * Sample : https://doc.babylonjs.com/how_to/video_texture
  66921. * @param {string | null} name optional name, will detect from video source, if not defined
  66922. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  66923. * @param {BABYLON.Scene} scene is obviously the current scene.
  66924. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  66925. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  66926. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  66927. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  66928. */
  66929. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  66930. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66931. if (invertY === void 0) { invertY = false; }
  66932. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66933. if (settings === void 0) { settings = {
  66934. autoPlay: true,
  66935. loop: true,
  66936. autoUpdateTexture: true,
  66937. }; }
  66938. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66939. _this._onUserActionRequestedObservable = null;
  66940. _this._stillImageCaptured = false;
  66941. _this._poster = false;
  66942. _this._createInternalTexture = function () {
  66943. if (_this._texture != null) {
  66944. if (_this._poster) {
  66945. _this._texture.dispose();
  66946. _this._poster = false;
  66947. }
  66948. else {
  66949. return;
  66950. }
  66951. }
  66952. if (!_this._engine.needPOTTextures ||
  66953. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  66954. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66955. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66956. }
  66957. else {
  66958. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66959. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66960. _this._generateMipMaps = false;
  66961. }
  66962. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  66963. if (!_this.video.autoplay) {
  66964. var oldHandler_1 = _this.video.onplaying;
  66965. var error_1 = false;
  66966. _this.video.onplaying = function () {
  66967. _this.video.onplaying = oldHandler_1;
  66968. _this._texture.isReady = true;
  66969. _this._updateInternalTexture();
  66970. if (!error_1) {
  66971. _this.video.pause();
  66972. }
  66973. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66974. _this.onLoadObservable.notifyObservers(_this);
  66975. }
  66976. };
  66977. var playing = _this.video.play();
  66978. if (playing) {
  66979. playing.then(function () {
  66980. // Everything is good.
  66981. })
  66982. .catch(function () {
  66983. error_1 = true;
  66984. // On Chrome for instance, new policies might prevent playing without user interaction.
  66985. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  66986. _this._onUserActionRequestedObservable.notifyObservers(_this);
  66987. }
  66988. });
  66989. }
  66990. else {
  66991. _this.video.onplaying = oldHandler_1;
  66992. _this._texture.isReady = true;
  66993. _this._updateInternalTexture();
  66994. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66995. _this.onLoadObservable.notifyObservers(_this);
  66996. }
  66997. }
  66998. }
  66999. else {
  67000. _this._texture.isReady = true;
  67001. _this._updateInternalTexture();
  67002. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67003. _this.onLoadObservable.notifyObservers(_this);
  67004. }
  67005. }
  67006. };
  67007. _this.reset = function () {
  67008. if (_this._texture == null) {
  67009. return;
  67010. }
  67011. if (!_this._poster) {
  67012. _this._texture.dispose();
  67013. _this._texture = null;
  67014. }
  67015. };
  67016. _this._updateInternalTexture = function (e) {
  67017. if (_this._texture == null || !_this._texture.isReady) {
  67018. return;
  67019. }
  67020. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  67021. return;
  67022. }
  67023. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  67024. };
  67025. _this._engine = _this.getScene().getEngine();
  67026. _this._generateMipMaps = generateMipMaps;
  67027. _this._samplingMode = samplingMode;
  67028. _this.autoUpdateTexture = settings.autoUpdateTexture;
  67029. _this.name = name || _this._getName(src);
  67030. _this.video = _this._getVideo(src);
  67031. if (settings.poster) {
  67032. _this.video.poster = settings.poster;
  67033. }
  67034. if (settings.autoPlay !== undefined) {
  67035. _this.video.autoplay = settings.autoPlay;
  67036. }
  67037. if (settings.loop !== undefined) {
  67038. _this.video.loop = settings.loop;
  67039. }
  67040. _this.video.setAttribute("playsinline", "");
  67041. _this.video.addEventListener("canplay", _this._createInternalTexture);
  67042. _this.video.addEventListener("paused", _this._updateInternalTexture);
  67043. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  67044. _this.video.addEventListener("emptied", _this.reset);
  67045. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  67046. _this._createInternalTexture();
  67047. }
  67048. if (settings.poster) {
  67049. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  67050. _this._poster = true;
  67051. }
  67052. return _this;
  67053. }
  67054. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  67055. get: function () {
  67056. if (!this._onUserActionRequestedObservable) {
  67057. this._onUserActionRequestedObservable = new BABYLON.Observable();
  67058. }
  67059. return this._onUserActionRequestedObservable;
  67060. },
  67061. enumerable: true,
  67062. configurable: true
  67063. });
  67064. VideoTexture.prototype._getName = function (src) {
  67065. if (src instanceof HTMLVideoElement) {
  67066. return src.currentSrc;
  67067. }
  67068. if (typeof src === "object") {
  67069. return src.toString();
  67070. }
  67071. return src;
  67072. };
  67073. ;
  67074. VideoTexture.prototype._getVideo = function (src) {
  67075. if (src instanceof HTMLVideoElement) {
  67076. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  67077. return src;
  67078. }
  67079. var video = document.createElement("video");
  67080. if (typeof src === "string") {
  67081. BABYLON.Tools.SetCorsBehavior(src, video);
  67082. video.src = src;
  67083. }
  67084. else {
  67085. BABYLON.Tools.SetCorsBehavior(src[0], video);
  67086. src.forEach(function (url) {
  67087. var source = document.createElement("source");
  67088. source.src = url;
  67089. video.appendChild(source);
  67090. });
  67091. }
  67092. return video;
  67093. };
  67094. ;
  67095. /**
  67096. * Internal method to initiate `update`.
  67097. */
  67098. VideoTexture.prototype._rebuild = function () {
  67099. this.update();
  67100. };
  67101. /**
  67102. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  67103. */
  67104. VideoTexture.prototype.update = function () {
  67105. if (!this.autoUpdateTexture) {
  67106. // Expecting user to call `updateTexture` manually
  67107. return;
  67108. }
  67109. this.updateTexture(true);
  67110. };
  67111. /**
  67112. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  67113. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  67114. */
  67115. VideoTexture.prototype.updateTexture = function (isVisible) {
  67116. if (!isVisible) {
  67117. return;
  67118. }
  67119. if (this.video.paused && this._stillImageCaptured) {
  67120. return;
  67121. }
  67122. this._stillImageCaptured = true;
  67123. this._updateInternalTexture();
  67124. };
  67125. /**
  67126. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  67127. * @param url New url.
  67128. */
  67129. VideoTexture.prototype.updateURL = function (url) {
  67130. this.video.src = url;
  67131. };
  67132. VideoTexture.prototype.dispose = function () {
  67133. _super.prototype.dispose.call(this);
  67134. if (this._onUserActionRequestedObservable) {
  67135. this._onUserActionRequestedObservable.clear();
  67136. this._onUserActionRequestedObservable = null;
  67137. }
  67138. this.video.removeEventListener("canplay", this._createInternalTexture);
  67139. this.video.removeEventListener("paused", this._updateInternalTexture);
  67140. this.video.removeEventListener("seeked", this._updateInternalTexture);
  67141. this.video.removeEventListener("emptied", this.reset);
  67142. this.video.pause();
  67143. };
  67144. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  67145. var video = document.createElement("video");
  67146. video.setAttribute('autoplay', '');
  67147. video.setAttribute('muted', '');
  67148. video.setAttribute('playsinline', '');
  67149. var constraintsDeviceId;
  67150. if (constraints && constraints.deviceId) {
  67151. constraintsDeviceId = {
  67152. exact: constraints.deviceId,
  67153. };
  67154. }
  67155. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  67156. if (navigator.mediaDevices) {
  67157. navigator.mediaDevices.getUserMedia({ video: constraints })
  67158. .then(function (stream) {
  67159. if (video.mozSrcObject !== undefined) {
  67160. // hack for Firefox < 19
  67161. video.mozSrcObject = stream;
  67162. }
  67163. else {
  67164. video.srcObject = stream;
  67165. }
  67166. var onPlaying = function () {
  67167. if (onReady) {
  67168. onReady(new VideoTexture("video", video, scene, true, true));
  67169. }
  67170. video.removeEventListener("playing", onPlaying);
  67171. };
  67172. video.addEventListener("playing", onPlaying);
  67173. video.play();
  67174. })
  67175. .catch(function (err) {
  67176. BABYLON.Tools.Error(err.name);
  67177. });
  67178. }
  67179. else {
  67180. navigator.getUserMedia =
  67181. navigator.getUserMedia ||
  67182. navigator.webkitGetUserMedia ||
  67183. navigator.mozGetUserMedia ||
  67184. navigator.msGetUserMedia;
  67185. if (navigator.getUserMedia) {
  67186. navigator.getUserMedia({
  67187. video: {
  67188. deviceId: constraintsDeviceId,
  67189. width: {
  67190. min: (constraints && constraints.minWidth) || 256,
  67191. max: (constraints && constraints.maxWidth) || 640,
  67192. },
  67193. height: {
  67194. min: (constraints && constraints.minHeight) || 256,
  67195. max: (constraints && constraints.maxHeight) || 480,
  67196. },
  67197. },
  67198. }, function (stream) {
  67199. if (video.mozSrcObject !== undefined) {
  67200. // hack for Firefox < 19
  67201. video.mozSrcObject = stream;
  67202. }
  67203. else {
  67204. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  67205. }
  67206. video.play();
  67207. if (onReady) {
  67208. onReady(new VideoTexture("video", video, scene, true, true));
  67209. }
  67210. }, function (e) {
  67211. BABYLON.Tools.Error(e.name);
  67212. });
  67213. }
  67214. }
  67215. };
  67216. return VideoTexture;
  67217. }(BABYLON.Texture));
  67218. BABYLON.VideoTexture = VideoTexture;
  67219. })(BABYLON || (BABYLON = {}));
  67220. //# sourceMappingURL=babylon.videoTexture.js.map
  67221. var BABYLON;
  67222. (function (BABYLON) {
  67223. var RawTexture = /** @class */ (function (_super) {
  67224. __extends(RawTexture, _super);
  67225. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  67226. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67227. if (invertY === void 0) { invertY = false; }
  67228. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67229. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67230. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67231. _this.format = format;
  67232. _this._engine = scene.getEngine();
  67233. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  67234. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67235. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67236. return _this;
  67237. }
  67238. RawTexture.prototype.update = function (data) {
  67239. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  67240. };
  67241. // Statics
  67242. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67243. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67244. if (invertY === void 0) { invertY = false; }
  67245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67246. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  67247. };
  67248. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67249. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67250. if (invertY === void 0) { invertY = false; }
  67251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67252. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  67253. };
  67254. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67255. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67256. if (invertY === void 0) { invertY = false; }
  67257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67258. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  67259. };
  67260. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67261. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67262. if (invertY === void 0) { invertY = false; }
  67263. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67264. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67265. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  67266. };
  67267. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67268. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67269. if (invertY === void 0) { invertY = false; }
  67270. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67271. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67272. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  67273. };
  67274. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67275. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67276. if (invertY === void 0) { invertY = false; }
  67277. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67278. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67279. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  67280. };
  67281. return RawTexture;
  67282. }(BABYLON.Texture));
  67283. BABYLON.RawTexture = RawTexture;
  67284. })(BABYLON || (BABYLON = {}));
  67285. //# sourceMappingURL=babylon.rawTexture.js.map
  67286. var BABYLON;
  67287. (function (BABYLON) {
  67288. /**
  67289. * Class used to store 3D textures containing user data
  67290. */
  67291. var RawTexture3D = /** @class */ (function (_super) {
  67292. __extends(RawTexture3D, _super);
  67293. /**
  67294. * Create a new RawTexture3D
  67295. * @param data defines the data of the texture
  67296. * @param width defines the width of the texture
  67297. * @param height defines the height of the texture
  67298. * @param depth defines the depth of the texture
  67299. * @param format defines the texture format to use
  67300. * @param scene defines the hosting scene
  67301. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  67302. * @param invertY defines if texture must be stored with Y axis inverted
  67303. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  67304. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  67305. */
  67306. function RawTexture3D(data, width, height, depth,
  67307. /** Gets or sets the texture format to use */
  67308. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  67309. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67310. if (invertY === void 0) { invertY = false; }
  67311. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67312. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67313. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67314. _this.format = format;
  67315. _this._engine = scene.getEngine();
  67316. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  67317. _this.is3D = true;
  67318. return _this;
  67319. }
  67320. /**
  67321. * Update the texture with new data
  67322. * @param data defines the data to store in the texture
  67323. */
  67324. RawTexture3D.prototype.update = function (data) {
  67325. if (!this._texture) {
  67326. return;
  67327. }
  67328. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  67329. };
  67330. return RawTexture3D;
  67331. }(BABYLON.Texture));
  67332. BABYLON.RawTexture3D = RawTexture3D;
  67333. })(BABYLON || (BABYLON = {}));
  67334. //# sourceMappingURL=babylon.rawTexture3D.js.map
  67335. var BABYLON;
  67336. (function (BABYLON) {
  67337. /**
  67338. * PostProcessManager is used to manage one or more post processes or post process pipelines
  67339. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  67340. */
  67341. var PostProcessManager = /** @class */ (function () {
  67342. /**
  67343. * Creates a new instance PostProcess
  67344. * @param scene The scene that the post process is associated with.
  67345. */
  67346. function PostProcessManager(scene) {
  67347. this._vertexBuffers = {};
  67348. this._scene = scene;
  67349. }
  67350. PostProcessManager.prototype._prepareBuffers = function () {
  67351. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  67352. return;
  67353. }
  67354. // VBO
  67355. var vertices = [];
  67356. vertices.push(1, 1);
  67357. vertices.push(-1, 1);
  67358. vertices.push(-1, -1);
  67359. vertices.push(1, -1);
  67360. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67361. this._buildIndexBuffer();
  67362. };
  67363. PostProcessManager.prototype._buildIndexBuffer = function () {
  67364. // Indices
  67365. var indices = [];
  67366. indices.push(0);
  67367. indices.push(1);
  67368. indices.push(2);
  67369. indices.push(0);
  67370. indices.push(2);
  67371. indices.push(3);
  67372. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  67373. };
  67374. /**
  67375. * Rebuilds the vertex buffers of the manager.
  67376. */
  67377. PostProcessManager.prototype._rebuild = function () {
  67378. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67379. if (!vb) {
  67380. return;
  67381. }
  67382. vb._rebuild();
  67383. this._buildIndexBuffer();
  67384. };
  67385. // Methods
  67386. /**
  67387. * Prepares a frame to be run through a post process.
  67388. * @param sourceTexture The input texture to the post procesess. (default: null)
  67389. * @param postProcesses An array of post processes to be run. (default: null)
  67390. * @returns True if the post processes were able to be run.
  67391. */
  67392. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  67393. if (sourceTexture === void 0) { sourceTexture = null; }
  67394. if (postProcesses === void 0) { postProcesses = null; }
  67395. var camera = this._scene.activeCamera;
  67396. if (!camera) {
  67397. return false;
  67398. }
  67399. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  67400. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  67401. return false;
  67402. }
  67403. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  67404. return true;
  67405. };
  67406. /**
  67407. * Manually render a set of post processes to a texture.
  67408. * @param postProcesses An array of post processes to be run.
  67409. * @param targetTexture The target texture to render to.
  67410. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  67411. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  67412. * @param lodLevel defines which lod of the texture to render to
  67413. */
  67414. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  67415. if (targetTexture === void 0) { targetTexture = null; }
  67416. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  67417. if (faceIndex === void 0) { faceIndex = 0; }
  67418. if (lodLevel === void 0) { lodLevel = 0; }
  67419. var engine = this._scene.getEngine();
  67420. for (var index = 0; index < postProcesses.length; index++) {
  67421. if (index < postProcesses.length - 1) {
  67422. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  67423. }
  67424. else {
  67425. if (targetTexture) {
  67426. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  67427. }
  67428. else {
  67429. engine.restoreDefaultFramebuffer();
  67430. }
  67431. }
  67432. var pp = postProcesses[index];
  67433. var effect = pp.apply();
  67434. if (effect) {
  67435. pp.onBeforeRenderObservable.notifyObservers(effect);
  67436. // VBOs
  67437. this._prepareBuffers();
  67438. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  67439. // Draw order
  67440. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67441. pp.onAfterRenderObservable.notifyObservers(effect);
  67442. }
  67443. }
  67444. // Restore depth buffer
  67445. engine.setDepthBuffer(true);
  67446. engine.setDepthWrite(true);
  67447. };
  67448. /**
  67449. * Finalize the result of the output of the postprocesses.
  67450. * @param doNotPresent If true the result will not be displayed to the screen.
  67451. * @param targetTexture The target texture to render to.
  67452. * @param faceIndex The index of the face to bind the target texture to.
  67453. * @param postProcesses The array of post processes to render.
  67454. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  67455. */
  67456. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  67457. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  67458. var camera = this._scene.activeCamera;
  67459. if (!camera) {
  67460. return;
  67461. }
  67462. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  67463. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  67464. return;
  67465. }
  67466. var engine = this._scene.getEngine();
  67467. for (var index = 0, len = postProcesses.length; index < len; index++) {
  67468. var pp = postProcesses[index];
  67469. if (index < len - 1) {
  67470. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  67471. }
  67472. else {
  67473. if (targetTexture) {
  67474. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  67475. pp._outputTexture = targetTexture;
  67476. }
  67477. else {
  67478. engine.restoreDefaultFramebuffer();
  67479. pp._outputTexture = null;
  67480. }
  67481. }
  67482. if (doNotPresent) {
  67483. break;
  67484. }
  67485. var effect = pp.apply();
  67486. if (effect) {
  67487. pp.onBeforeRenderObservable.notifyObservers(effect);
  67488. // VBOs
  67489. this._prepareBuffers();
  67490. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  67491. // Draw order
  67492. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67493. pp.onAfterRenderObservable.notifyObservers(effect);
  67494. }
  67495. }
  67496. // Restore states
  67497. engine.setDepthBuffer(true);
  67498. engine.setDepthWrite(true);
  67499. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67500. };
  67501. /**
  67502. * Disposes of the post process manager.
  67503. */
  67504. PostProcessManager.prototype.dispose = function () {
  67505. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67506. if (buffer) {
  67507. buffer.dispose();
  67508. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67509. }
  67510. if (this._indexBuffer) {
  67511. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67512. this._indexBuffer = null;
  67513. }
  67514. };
  67515. return PostProcessManager;
  67516. }());
  67517. BABYLON.PostProcessManager = PostProcessManager;
  67518. })(BABYLON || (BABYLON = {}));
  67519. //# sourceMappingURL=babylon.postProcessManager.js.map
  67520. var BABYLON;
  67521. (function (BABYLON) {
  67522. /**
  67523. * PostProcess can be used to apply a shader to a texture after it has been rendered
  67524. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  67525. */
  67526. var PostProcess = /** @class */ (function () {
  67527. /**
  67528. * Creates a new instance PostProcess
  67529. * @param name The name of the PostProcess.
  67530. * @param fragmentUrl The url of the fragment shader to be used.
  67531. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  67532. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  67533. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  67534. * @param camera The camera to apply the render pass to.
  67535. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67536. * @param engine The engine which the post process will be applied. (default: current engine)
  67537. * @param reusable If the post process can be reused on the same frame. (default: false)
  67538. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  67539. * @param textureType Type of textures used when performing the post process. (default: 0)
  67540. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  67541. * @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
  67542. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  67543. */
  67544. function PostProcess(
  67545. /** Name of the PostProcess. */
  67546. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  67547. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  67548. if (defines === void 0) { defines = null; }
  67549. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67550. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  67551. if (blockCompilation === void 0) { blockCompilation = false; }
  67552. this.name = name;
  67553. /**
  67554. * Width of the texture to apply the post process on
  67555. */
  67556. this.width = -1;
  67557. /**
  67558. * Height of the texture to apply the post process on
  67559. */
  67560. this.height = -1;
  67561. /**
  67562. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  67563. */
  67564. this._outputTexture = null;
  67565. /**
  67566. * If the buffer needs to be cleared before applying the post process. (default: true)
  67567. * Should be set to false if shader will overwrite all previous pixels.
  67568. */
  67569. this.autoClear = true;
  67570. /**
  67571. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  67572. */
  67573. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  67574. /**
  67575. * Animations to be used for the post processing
  67576. */
  67577. this.animations = new Array();
  67578. /**
  67579. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  67580. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  67581. */
  67582. this.enablePixelPerfectMode = false;
  67583. /**
  67584. * Force the postprocess to be applied without taking in account viewport
  67585. */
  67586. this.forceFullscreenViewport = true;
  67587. /**
  67588. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  67589. *
  67590. * | Value | Type | Description |
  67591. * | ----- | ----------------------------------- | ----------- |
  67592. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  67593. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  67594. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  67595. *
  67596. */
  67597. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  67598. /**
  67599. * Force textures to be a power of two (default: false)
  67600. */
  67601. this.alwaysForcePOT = false;
  67602. /**
  67603. * Number of sample textures (default: 1)
  67604. */
  67605. this.samples = 1;
  67606. /**
  67607. * Modify the scale of the post process to be the same as the viewport (default: false)
  67608. */
  67609. this.adaptScaleToCurrentViewport = false;
  67610. this._reusable = false;
  67611. /**
  67612. * Smart array of input and output textures for the post process.
  67613. */
  67614. this._textures = new BABYLON.SmartArray(2);
  67615. /**
  67616. * The index in _textures that corresponds to the output texture.
  67617. */
  67618. this._currentRenderTextureInd = 0;
  67619. this._scaleRatio = new BABYLON.Vector2(1, 1);
  67620. this._texelSize = BABYLON.Vector2.Zero();
  67621. // Events
  67622. /**
  67623. * An event triggered when the postprocess is activated.
  67624. */
  67625. this.onActivateObservable = new BABYLON.Observable();
  67626. /**
  67627. * An event triggered when the postprocess changes its size.
  67628. */
  67629. this.onSizeChangedObservable = new BABYLON.Observable();
  67630. /**
  67631. * An event triggered when the postprocess applies its effect.
  67632. */
  67633. this.onApplyObservable = new BABYLON.Observable();
  67634. /**
  67635. * An event triggered before rendering the postprocess
  67636. */
  67637. this.onBeforeRenderObservable = new BABYLON.Observable();
  67638. /**
  67639. * An event triggered after rendering the postprocess
  67640. */
  67641. this.onAfterRenderObservable = new BABYLON.Observable();
  67642. if (camera != null) {
  67643. this._camera = camera;
  67644. this._scene = camera.getScene();
  67645. camera.attachPostProcess(this);
  67646. this._engine = this._scene.getEngine();
  67647. this._scene.postProcesses.push(this);
  67648. }
  67649. else if (engine) {
  67650. this._engine = engine;
  67651. this._engine.postProcesses.push(this);
  67652. }
  67653. this._options = options;
  67654. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  67655. this._reusable = reusable || false;
  67656. this._textureType = textureType;
  67657. this._samplers = samplers || [];
  67658. this._samplers.push("textureSampler");
  67659. this._fragmentUrl = fragmentUrl;
  67660. this._vertexUrl = vertexUrl;
  67661. this._parameters = parameters || [];
  67662. this._parameters.push("scale");
  67663. this._indexParameters = indexParameters;
  67664. if (!blockCompilation) {
  67665. this.updateEffect(defines);
  67666. }
  67667. }
  67668. Object.defineProperty(PostProcess.prototype, "onActivate", {
  67669. /**
  67670. * A function that is added to the onActivateObservable
  67671. */
  67672. set: function (callback) {
  67673. if (this._onActivateObserver) {
  67674. this.onActivateObservable.remove(this._onActivateObserver);
  67675. }
  67676. if (callback) {
  67677. this._onActivateObserver = this.onActivateObservable.add(callback);
  67678. }
  67679. },
  67680. enumerable: true,
  67681. configurable: true
  67682. });
  67683. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  67684. /**
  67685. * A function that is added to the onSizeChangedObservable
  67686. */
  67687. set: function (callback) {
  67688. if (this._onSizeChangedObserver) {
  67689. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  67690. }
  67691. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  67692. },
  67693. enumerable: true,
  67694. configurable: true
  67695. });
  67696. Object.defineProperty(PostProcess.prototype, "onApply", {
  67697. /**
  67698. * A function that is added to the onApplyObservable
  67699. */
  67700. set: function (callback) {
  67701. if (this._onApplyObserver) {
  67702. this.onApplyObservable.remove(this._onApplyObserver);
  67703. }
  67704. this._onApplyObserver = this.onApplyObservable.add(callback);
  67705. },
  67706. enumerable: true,
  67707. configurable: true
  67708. });
  67709. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  67710. /**
  67711. * A function that is added to the onBeforeRenderObservable
  67712. */
  67713. set: function (callback) {
  67714. if (this._onBeforeRenderObserver) {
  67715. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67716. }
  67717. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67718. },
  67719. enumerable: true,
  67720. configurable: true
  67721. });
  67722. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  67723. /**
  67724. * A function that is added to the onAfterRenderObservable
  67725. */
  67726. set: function (callback) {
  67727. if (this._onAfterRenderObserver) {
  67728. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67729. }
  67730. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67731. },
  67732. enumerable: true,
  67733. configurable: true
  67734. });
  67735. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  67736. /**
  67737. * 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
  67738. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  67739. */
  67740. get: function () {
  67741. return this._textures.data[this._currentRenderTextureInd];
  67742. },
  67743. set: function (value) {
  67744. this._forcedOutputTexture = value;
  67745. },
  67746. enumerable: true,
  67747. configurable: true
  67748. });
  67749. /**
  67750. * Gets the camera which post process is applied to.
  67751. * @returns The camera the post process is applied to.
  67752. */
  67753. PostProcess.prototype.getCamera = function () {
  67754. return this._camera;
  67755. };
  67756. Object.defineProperty(PostProcess.prototype, "texelSize", {
  67757. /**
  67758. * Gets the texel size of the postprocess.
  67759. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  67760. */
  67761. get: function () {
  67762. if (this._shareOutputWithPostProcess) {
  67763. return this._shareOutputWithPostProcess.texelSize;
  67764. }
  67765. if (this._forcedOutputTexture) {
  67766. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  67767. }
  67768. return this._texelSize;
  67769. },
  67770. enumerable: true,
  67771. configurable: true
  67772. });
  67773. /**
  67774. * Gets the engine which this post process belongs to.
  67775. * @returns The engine the post process was enabled with.
  67776. */
  67777. PostProcess.prototype.getEngine = function () {
  67778. return this._engine;
  67779. };
  67780. /**
  67781. * The effect that is created when initializing the post process.
  67782. * @returns The created effect corrisponding the the postprocess.
  67783. */
  67784. PostProcess.prototype.getEffect = function () {
  67785. return this._effect;
  67786. };
  67787. /**
  67788. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  67789. * @param postProcess The post process to share the output with.
  67790. * @returns This post process.
  67791. */
  67792. PostProcess.prototype.shareOutputWith = function (postProcess) {
  67793. this._disposeTextures();
  67794. this._shareOutputWithPostProcess = postProcess;
  67795. return this;
  67796. };
  67797. /**
  67798. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  67799. * This should be called if the post process that shares output with this post process is disabled/disposed.
  67800. */
  67801. PostProcess.prototype.useOwnOutput = function () {
  67802. if (this._textures.length == 0) {
  67803. this._textures = new BABYLON.SmartArray(2);
  67804. }
  67805. this._shareOutputWithPostProcess = null;
  67806. };
  67807. /**
  67808. * Updates the effect with the current post process compile time values and recompiles the shader.
  67809. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  67810. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  67811. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  67812. * @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
  67813. * @param onCompiled Called when the shader has been compiled.
  67814. * @param onError Called if there is an error when compiling a shader.
  67815. */
  67816. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  67817. if (defines === void 0) { defines = null; }
  67818. if (uniforms === void 0) { uniforms = null; }
  67819. if (samplers === void 0) { samplers = null; }
  67820. 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);
  67821. };
  67822. /**
  67823. * The post process is reusable if it can be used multiple times within one frame.
  67824. * @returns If the post process is reusable
  67825. */
  67826. PostProcess.prototype.isReusable = function () {
  67827. return this._reusable;
  67828. };
  67829. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  67830. PostProcess.prototype.markTextureDirty = function () {
  67831. this.width = -1;
  67832. };
  67833. /**
  67834. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  67835. * 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.
  67836. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  67837. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  67838. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  67839. * @returns The target texture that was bound to be written to.
  67840. */
  67841. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  67842. var _this = this;
  67843. if (sourceTexture === void 0) { sourceTexture = null; }
  67844. camera = camera || this._camera;
  67845. var scene = camera.getScene();
  67846. var engine = scene.getEngine();
  67847. var maxSize = engine.getCaps().maxTextureSize;
  67848. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  67849. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  67850. // 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
  67851. var webVRCamera = camera.parent;
  67852. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  67853. requiredWidth /= 2;
  67854. }
  67855. var desiredWidth = (this._options.width || requiredWidth);
  67856. var desiredHeight = this._options.height || requiredHeight;
  67857. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  67858. if (this.adaptScaleToCurrentViewport) {
  67859. var currentViewport = engine.currentViewport;
  67860. if (currentViewport) {
  67861. desiredWidth *= currentViewport.width;
  67862. desiredHeight *= currentViewport.height;
  67863. }
  67864. }
  67865. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  67866. if (!this._options.width) {
  67867. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  67868. }
  67869. if (!this._options.height) {
  67870. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  67871. }
  67872. }
  67873. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  67874. if (this._textures.length > 0) {
  67875. for (var i = 0; i < this._textures.length; i++) {
  67876. this._engine._releaseTexture(this._textures.data[i]);
  67877. }
  67878. this._textures.reset();
  67879. }
  67880. this.width = desiredWidth;
  67881. this.height = desiredHeight;
  67882. var textureSize = { width: this.width, height: this.height };
  67883. var textureOptions = {
  67884. generateMipMaps: false,
  67885. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  67886. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  67887. samplingMode: this.renderTargetSamplingMode,
  67888. type: this._textureType
  67889. };
  67890. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67891. if (this._reusable) {
  67892. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67893. }
  67894. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  67895. this.onSizeChangedObservable.notifyObservers(this);
  67896. }
  67897. this._textures.forEach(function (texture) {
  67898. if (texture.samples !== _this.samples) {
  67899. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  67900. }
  67901. });
  67902. }
  67903. var target;
  67904. if (this._shareOutputWithPostProcess) {
  67905. target = this._shareOutputWithPostProcess.inputTexture;
  67906. }
  67907. else if (this._forcedOutputTexture) {
  67908. target = this._forcedOutputTexture;
  67909. this.width = this._forcedOutputTexture.width;
  67910. this.height = this._forcedOutputTexture.height;
  67911. }
  67912. else {
  67913. target = this.inputTexture;
  67914. }
  67915. // Bind the input of this post process to be used as the output of the previous post process.
  67916. if (this.enablePixelPerfectMode) {
  67917. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  67918. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  67919. }
  67920. else {
  67921. this._scaleRatio.copyFromFloats(1, 1);
  67922. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  67923. }
  67924. this.onActivateObservable.notifyObservers(camera);
  67925. // Clear
  67926. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  67927. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  67928. }
  67929. if (this._reusable) {
  67930. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  67931. }
  67932. return target;
  67933. };
  67934. Object.defineProperty(PostProcess.prototype, "isSupported", {
  67935. /**
  67936. * If the post process is supported.
  67937. */
  67938. get: function () {
  67939. return this._effect.isSupported;
  67940. },
  67941. enumerable: true,
  67942. configurable: true
  67943. });
  67944. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  67945. /**
  67946. * The aspect ratio of the output texture.
  67947. */
  67948. get: function () {
  67949. if (this._shareOutputWithPostProcess) {
  67950. return this._shareOutputWithPostProcess.aspectRatio;
  67951. }
  67952. if (this._forcedOutputTexture) {
  67953. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  67954. }
  67955. return this.width / this.height;
  67956. },
  67957. enumerable: true,
  67958. configurable: true
  67959. });
  67960. /**
  67961. * Get a value indicating if the post-process is ready to be used
  67962. * @returns true if the post-process is ready (shader is compiled)
  67963. */
  67964. PostProcess.prototype.isReady = function () {
  67965. return this._effect && this._effect.isReady();
  67966. };
  67967. /**
  67968. * Binds all textures and uniforms to the shader, this will be run on every pass.
  67969. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  67970. */
  67971. PostProcess.prototype.apply = function () {
  67972. // Check
  67973. if (!this._effect || !this._effect.isReady())
  67974. return null;
  67975. // States
  67976. this._engine.enableEffect(this._effect);
  67977. this._engine.setState(false);
  67978. this._engine.setDepthBuffer(false);
  67979. this._engine.setDepthWrite(false);
  67980. // Alpha
  67981. this._engine.setAlphaMode(this.alphaMode);
  67982. if (this.alphaConstants) {
  67983. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  67984. }
  67985. // Bind the output texture of the preivous post process as the input to this post process.
  67986. var source;
  67987. if (this._shareOutputWithPostProcess) {
  67988. source = this._shareOutputWithPostProcess.inputTexture;
  67989. }
  67990. else if (this._forcedOutputTexture) {
  67991. source = this._forcedOutputTexture;
  67992. }
  67993. else {
  67994. source = this.inputTexture;
  67995. }
  67996. this._effect._bindTexture("textureSampler", source);
  67997. // Parameters
  67998. this._effect.setVector2("scale", this._scaleRatio);
  67999. this.onApplyObservable.notifyObservers(this._effect);
  68000. return this._effect;
  68001. };
  68002. PostProcess.prototype._disposeTextures = function () {
  68003. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  68004. return;
  68005. }
  68006. if (this._textures.length > 0) {
  68007. for (var i = 0; i < this._textures.length; i++) {
  68008. this._engine._releaseTexture(this._textures.data[i]);
  68009. }
  68010. }
  68011. this._textures.dispose();
  68012. };
  68013. /**
  68014. * Disposes the post process.
  68015. * @param camera The camera to dispose the post process on.
  68016. */
  68017. PostProcess.prototype.dispose = function (camera) {
  68018. camera = camera || this._camera;
  68019. this._disposeTextures();
  68020. if (this._scene) {
  68021. var index_1 = this._scene.postProcesses.indexOf(this);
  68022. if (index_1 !== -1) {
  68023. this._scene.postProcesses.splice(index_1, 1);
  68024. }
  68025. }
  68026. else {
  68027. var index_2 = this._engine.postProcesses.indexOf(this);
  68028. if (index_2 !== -1) {
  68029. this._engine.postProcesses.splice(index_2, 1);
  68030. }
  68031. }
  68032. if (!camera) {
  68033. return;
  68034. }
  68035. camera.detachPostProcess(this);
  68036. var index = camera._postProcesses.indexOf(this);
  68037. if (index === 0 && camera._postProcesses.length > 0) {
  68038. var firstPostProcess = this._camera._getFirstPostProcess();
  68039. if (firstPostProcess) {
  68040. firstPostProcess.markTextureDirty();
  68041. }
  68042. }
  68043. this.onActivateObservable.clear();
  68044. this.onAfterRenderObservable.clear();
  68045. this.onApplyObservable.clear();
  68046. this.onBeforeRenderObservable.clear();
  68047. this.onSizeChangedObservable.clear();
  68048. };
  68049. return PostProcess;
  68050. }());
  68051. BABYLON.PostProcess = PostProcess;
  68052. })(BABYLON || (BABYLON = {}));
  68053. //# sourceMappingURL=babylon.postProcess.js.map
  68054. var BABYLON;
  68055. (function (BABYLON) {
  68056. var PassPostProcess = /** @class */ (function (_super) {
  68057. __extends(PassPostProcess, _super);
  68058. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68059. if (camera === void 0) { camera = null; }
  68060. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68061. if (blockCompilation === void 0) { blockCompilation = false; }
  68062. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  68063. }
  68064. return PassPostProcess;
  68065. }(BABYLON.PostProcess));
  68066. BABYLON.PassPostProcess = PassPostProcess;
  68067. })(BABYLON || (BABYLON = {}));
  68068. //# sourceMappingURL=babylon.passPostProcess.js.map
  68069. var __assign = (this && this.__assign) || Object.assign || function(t) {
  68070. for (var s, i = 1, n = arguments.length; i < n; i++) {
  68071. s = arguments[i];
  68072. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  68073. t[p] = s[p];
  68074. }
  68075. return t;
  68076. };
  68077. var BABYLON;
  68078. (function (BABYLON) {
  68079. /**
  68080. * Default implementation IShadowGenerator.
  68081. * This is the main object responsible of generating shadows in the framework.
  68082. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  68083. */
  68084. var ShadowGenerator = /** @class */ (function () {
  68085. /**
  68086. * Creates a ShadowGenerator object.
  68087. * A ShadowGenerator is the required tool to use the shadows.
  68088. * Each light casting shadows needs to use its own ShadowGenerator.
  68089. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  68090. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  68091. * @param light The light object generating the shadows.
  68092. * @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.
  68093. */
  68094. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  68095. this._bias = 0.00005;
  68096. this._normalBias = 0;
  68097. this._blurBoxOffset = 1;
  68098. this._blurScale = 2;
  68099. this._blurKernel = 1;
  68100. this._useKernelBlur = false;
  68101. this._filter = ShadowGenerator.FILTER_NONE;
  68102. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  68103. this._contactHardeningLightSizeUVRatio = 0.1;
  68104. this._darkness = 0;
  68105. this._transparencyShadow = false;
  68106. /**
  68107. * Controls the extent to which the shadows fade out at the edge of the frustum
  68108. * Used only by directionals and spots
  68109. */
  68110. this.frustumEdgeFalloff = 0;
  68111. /**
  68112. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  68113. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  68114. * It might on the other hand introduce peter panning.
  68115. */
  68116. this.forceBackFacesOnly = false;
  68117. this._lightDirection = BABYLON.Vector3.Zero();
  68118. this._viewMatrix = BABYLON.Matrix.Zero();
  68119. this._projectionMatrix = BABYLON.Matrix.Zero();
  68120. this._transformMatrix = BABYLON.Matrix.Zero();
  68121. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68122. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68123. this._currentFaceIndex = 0;
  68124. this._currentFaceIndexCache = 0;
  68125. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  68126. this._mapSize = mapSize;
  68127. this._light = light;
  68128. this._scene = light.getScene();
  68129. light._shadowGenerator = this;
  68130. // Texture type fallback from float to int if not supported.
  68131. var caps = this._scene.getEngine().getCaps();
  68132. if (!useFullFloatFirst) {
  68133. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68134. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68135. }
  68136. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68137. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68138. }
  68139. else {
  68140. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68141. }
  68142. }
  68143. else {
  68144. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68145. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68146. }
  68147. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68148. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68149. }
  68150. else {
  68151. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68152. }
  68153. }
  68154. this._initializeGenerator();
  68155. this._applyFilterValues();
  68156. }
  68157. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  68158. /**
  68159. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  68160. */
  68161. get: function () {
  68162. return this._bias;
  68163. },
  68164. /**
  68165. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  68166. */
  68167. set: function (bias) {
  68168. this._bias = bias;
  68169. },
  68170. enumerable: true,
  68171. configurable: true
  68172. });
  68173. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  68174. /**
  68175. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68176. */
  68177. get: function () {
  68178. return this._normalBias;
  68179. },
  68180. /**
  68181. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68182. */
  68183. set: function (normalBias) {
  68184. this._normalBias = normalBias;
  68185. },
  68186. enumerable: true,
  68187. configurable: true
  68188. });
  68189. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  68190. /**
  68191. * Gets the blur box offset: offset applied during the blur pass.
  68192. * Only usefull if useKernelBlur = false
  68193. */
  68194. get: function () {
  68195. return this._blurBoxOffset;
  68196. },
  68197. /**
  68198. * Sets the blur box offset: offset applied during the blur pass.
  68199. * Only usefull if useKernelBlur = false
  68200. */
  68201. set: function (value) {
  68202. if (this._blurBoxOffset === value) {
  68203. return;
  68204. }
  68205. this._blurBoxOffset = value;
  68206. this._disposeBlurPostProcesses();
  68207. },
  68208. enumerable: true,
  68209. configurable: true
  68210. });
  68211. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  68212. /**
  68213. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  68214. * 2 means half of the size.
  68215. */
  68216. get: function () {
  68217. return this._blurScale;
  68218. },
  68219. /**
  68220. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  68221. * 2 means half of the size.
  68222. */
  68223. set: function (value) {
  68224. if (this._blurScale === value) {
  68225. return;
  68226. }
  68227. this._blurScale = value;
  68228. this._disposeBlurPostProcesses();
  68229. },
  68230. enumerable: true,
  68231. configurable: true
  68232. });
  68233. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  68234. /**
  68235. * Gets the blur kernel: kernel size of the blur pass.
  68236. * Only usefull if useKernelBlur = true
  68237. */
  68238. get: function () {
  68239. return this._blurKernel;
  68240. },
  68241. /**
  68242. * Sets the blur kernel: kernel size of the blur pass.
  68243. * Only usefull if useKernelBlur = true
  68244. */
  68245. set: function (value) {
  68246. if (this._blurKernel === value) {
  68247. return;
  68248. }
  68249. this._blurKernel = value;
  68250. this._disposeBlurPostProcesses();
  68251. },
  68252. enumerable: true,
  68253. configurable: true
  68254. });
  68255. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  68256. /**
  68257. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  68258. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  68259. */
  68260. get: function () {
  68261. return this._useKernelBlur;
  68262. },
  68263. /**
  68264. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  68265. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  68266. */
  68267. set: function (value) {
  68268. if (this._useKernelBlur === value) {
  68269. return;
  68270. }
  68271. this._useKernelBlur = value;
  68272. this._disposeBlurPostProcesses();
  68273. },
  68274. enumerable: true,
  68275. configurable: true
  68276. });
  68277. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  68278. /**
  68279. * Gets the depth scale used in ESM mode.
  68280. */
  68281. get: function () {
  68282. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  68283. },
  68284. /**
  68285. * Sets the depth scale used in ESM mode.
  68286. * This can override the scale stored on the light.
  68287. */
  68288. set: function (value) {
  68289. this._depthScale = value;
  68290. },
  68291. enumerable: true,
  68292. configurable: true
  68293. });
  68294. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  68295. /**
  68296. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  68297. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  68298. */
  68299. get: function () {
  68300. return this._filter;
  68301. },
  68302. /**
  68303. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  68304. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  68305. */
  68306. set: function (value) {
  68307. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  68308. if (this._light.needCube()) {
  68309. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  68310. this.useExponentialShadowMap = true;
  68311. return;
  68312. }
  68313. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  68314. this.useCloseExponentialShadowMap = true;
  68315. return;
  68316. }
  68317. // PCF on cubemap would also be expensive
  68318. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  68319. this.usePoissonSampling = true;
  68320. return;
  68321. }
  68322. }
  68323. // Weblg1 fallback for PCF.
  68324. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  68325. if (this._scene.getEngine().webGLVersion === 1) {
  68326. this.usePoissonSampling = true;
  68327. return;
  68328. }
  68329. }
  68330. if (this._filter === value) {
  68331. return;
  68332. }
  68333. this._filter = value;
  68334. this._disposeBlurPostProcesses();
  68335. this._applyFilterValues();
  68336. this._light._markMeshesAsLightDirty();
  68337. },
  68338. enumerable: true,
  68339. configurable: true
  68340. });
  68341. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  68342. /**
  68343. * Gets if the current filter is set to Poisson Sampling.
  68344. */
  68345. get: function () {
  68346. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  68347. },
  68348. /**
  68349. * Sets the current filter to Poisson Sampling.
  68350. */
  68351. set: function (value) {
  68352. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  68353. return;
  68354. }
  68355. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  68356. },
  68357. enumerable: true,
  68358. configurable: true
  68359. });
  68360. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  68361. /**
  68362. * Gets if the current filter is set to VSM.
  68363. * DEPRECATED. Should use useExponentialShadowMap instead.
  68364. */
  68365. get: function () {
  68366. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  68367. return this.useExponentialShadowMap;
  68368. },
  68369. /**
  68370. * Sets the current filter is to VSM.
  68371. * DEPRECATED. Should use useExponentialShadowMap instead.
  68372. */
  68373. set: function (value) {
  68374. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  68375. this.useExponentialShadowMap = value;
  68376. },
  68377. enumerable: true,
  68378. configurable: true
  68379. });
  68380. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  68381. /**
  68382. * Gets if the current filter is set to blurred VSM.
  68383. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  68384. */
  68385. get: function () {
  68386. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  68387. return this.useBlurExponentialShadowMap;
  68388. },
  68389. /**
  68390. * Sets the current filter is to blurred VSM.
  68391. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  68392. */
  68393. set: function (value) {
  68394. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  68395. this.useBlurExponentialShadowMap = value;
  68396. },
  68397. enumerable: true,
  68398. configurable: true
  68399. });
  68400. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  68401. /**
  68402. * Gets if the current filter is set to ESM.
  68403. */
  68404. get: function () {
  68405. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  68406. },
  68407. /**
  68408. * Sets the current filter is to ESM.
  68409. */
  68410. set: function (value) {
  68411. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  68412. return;
  68413. }
  68414. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68415. },
  68416. enumerable: true,
  68417. configurable: true
  68418. });
  68419. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  68420. /**
  68421. * Gets if the current filter is set to filtered ESM.
  68422. */
  68423. get: function () {
  68424. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  68425. },
  68426. /**
  68427. * Gets if the current filter is set to filtered ESM.
  68428. */
  68429. set: function (value) {
  68430. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  68431. return;
  68432. }
  68433. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68434. },
  68435. enumerable: true,
  68436. configurable: true
  68437. });
  68438. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  68439. /**
  68440. * Gets if the current filter is set to "close ESM" (using the inverse of the
  68441. * exponential to prevent steep falloff artifacts).
  68442. */
  68443. get: function () {
  68444. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  68445. },
  68446. /**
  68447. * Sets the current filter to "close ESM" (using the inverse of the
  68448. * exponential to prevent steep falloff artifacts).
  68449. */
  68450. set: function (value) {
  68451. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  68452. return;
  68453. }
  68454. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68455. },
  68456. enumerable: true,
  68457. configurable: true
  68458. });
  68459. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  68460. /**
  68461. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  68462. * exponential to prevent steep falloff artifacts).
  68463. */
  68464. get: function () {
  68465. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  68466. },
  68467. /**
  68468. * Sets the current filter to filtered "close ESM" (using the inverse of the
  68469. * exponential to prevent steep falloff artifacts).
  68470. */
  68471. set: function (value) {
  68472. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  68473. return;
  68474. }
  68475. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68476. },
  68477. enumerable: true,
  68478. configurable: true
  68479. });
  68480. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  68481. /**
  68482. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  68483. */
  68484. get: function () {
  68485. return this.filter === ShadowGenerator.FILTER_PCF;
  68486. },
  68487. /**
  68488. * Sets the current filter to "PCF" (percentage closer filtering).
  68489. */
  68490. set: function (value) {
  68491. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  68492. return;
  68493. }
  68494. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  68495. },
  68496. enumerable: true,
  68497. configurable: true
  68498. });
  68499. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  68500. /**
  68501. * Gets the PCF or PCSS Quality.
  68502. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  68503. */
  68504. get: function () {
  68505. return this._filteringQuality;
  68506. },
  68507. /**
  68508. * Sets the PCF or PCSS Quality.
  68509. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  68510. */
  68511. set: function (filteringQuality) {
  68512. this._filteringQuality = filteringQuality;
  68513. },
  68514. enumerable: true,
  68515. configurable: true
  68516. });
  68517. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  68518. /**
  68519. * Gets if the current filter is set to "PCSS" (contact hardening).
  68520. */
  68521. get: function () {
  68522. return this.filter === ShadowGenerator.FILTER_PCSS;
  68523. },
  68524. /**
  68525. * Sets the current filter to "PCSS" (contact hardening).
  68526. */
  68527. set: function (value) {
  68528. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  68529. return;
  68530. }
  68531. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  68532. },
  68533. enumerable: true,
  68534. configurable: true
  68535. });
  68536. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  68537. /**
  68538. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  68539. * Using a ratio helps keeping shape stability independently of the map size.
  68540. *
  68541. * It does not account for the light projection as it was having too much
  68542. * instability during the light setup or during light position changes.
  68543. *
  68544. * Only valid if useContactHardeningShadow is true.
  68545. */
  68546. get: function () {
  68547. return this._contactHardeningLightSizeUVRatio;
  68548. },
  68549. /**
  68550. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  68551. * Using a ratio helps keeping shape stability independently of the map size.
  68552. *
  68553. * It does not account for the light projection as it was having too much
  68554. * instability during the light setup or during light position changes.
  68555. *
  68556. * Only valid if useContactHardeningShadow is true.
  68557. */
  68558. set: function (contactHardeningLightSizeUVRatio) {
  68559. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  68560. },
  68561. enumerable: true,
  68562. configurable: true
  68563. });
  68564. /**
  68565. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  68566. * 0 means strongest and 1 would means no shadow.
  68567. * @returns the darkness.
  68568. */
  68569. ShadowGenerator.prototype.getDarkness = function () {
  68570. return this._darkness;
  68571. };
  68572. /**
  68573. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  68574. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  68575. * @returns the shadow generator allowing fluent coding.
  68576. */
  68577. ShadowGenerator.prototype.setDarkness = function (darkness) {
  68578. if (darkness >= 1.0)
  68579. this._darkness = 1.0;
  68580. else if (darkness <= 0.0)
  68581. this._darkness = 0.0;
  68582. else
  68583. this._darkness = darkness;
  68584. return this;
  68585. };
  68586. /**
  68587. * Sets the ability to have transparent shadow (boolean).
  68588. * @param transparent True if transparent else False
  68589. * @returns the shadow generator allowing fluent coding
  68590. */
  68591. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  68592. this._transparencyShadow = transparent;
  68593. return this;
  68594. };
  68595. /**
  68596. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  68597. * @returns The render target texture if present otherwise, null
  68598. */
  68599. ShadowGenerator.prototype.getShadowMap = function () {
  68600. return this._shadowMap;
  68601. };
  68602. /**
  68603. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  68604. * @returns The render target texture if the shadow map is present otherwise, null
  68605. */
  68606. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  68607. if (this._shadowMap2) {
  68608. return this._shadowMap2;
  68609. }
  68610. return this._shadowMap;
  68611. };
  68612. /**
  68613. * Helper function to add a mesh and its descendants to the list of shadow casters.
  68614. * @param mesh Mesh to add
  68615. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  68616. * @returns the Shadow Generator itself
  68617. */
  68618. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  68619. if (includeDescendants === void 0) { includeDescendants = true; }
  68620. if (!this._shadowMap) {
  68621. return this;
  68622. }
  68623. if (!this._shadowMap.renderList) {
  68624. this._shadowMap.renderList = [];
  68625. }
  68626. this._shadowMap.renderList.push(mesh);
  68627. if (includeDescendants) {
  68628. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  68629. }
  68630. return this;
  68631. var _a;
  68632. };
  68633. /**
  68634. * Helper function to remove a mesh and its descendants from the list of shadow casters
  68635. * @param mesh Mesh to remove
  68636. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  68637. * @returns the Shadow Generator itself
  68638. */
  68639. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  68640. if (includeDescendants === void 0) { includeDescendants = true; }
  68641. if (!this._shadowMap || !this._shadowMap.renderList) {
  68642. return this;
  68643. }
  68644. var index = this._shadowMap.renderList.indexOf(mesh);
  68645. if (index !== -1) {
  68646. this._shadowMap.renderList.splice(index, 1);
  68647. }
  68648. if (includeDescendants) {
  68649. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  68650. var child = _a[_i];
  68651. this.removeShadowCaster(child);
  68652. }
  68653. }
  68654. return this;
  68655. };
  68656. /**
  68657. * Returns the associated light object.
  68658. * @returns the light generating the shadow
  68659. */
  68660. ShadowGenerator.prototype.getLight = function () {
  68661. return this._light;
  68662. };
  68663. ShadowGenerator.prototype._initializeGenerator = function () {
  68664. this._light._markMeshesAsLightDirty();
  68665. this._initializeShadowMap();
  68666. };
  68667. ShadowGenerator.prototype._initializeShadowMap = function () {
  68668. var _this = this;
  68669. // Render target
  68670. var engine = this._scene.getEngine();
  68671. if (engine.webGLVersion > 1) {
  68672. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  68673. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  68674. }
  68675. else {
  68676. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  68677. }
  68678. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68679. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68680. this._shadowMap.anisotropicFilteringLevel = 1;
  68681. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68682. this._shadowMap.renderParticles = false;
  68683. this._shadowMap.ignoreCameraViewport = true;
  68684. // Record Face Index before render.
  68685. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  68686. _this._currentFaceIndex = faceIndex;
  68687. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68688. engine.setColorWrite(false);
  68689. }
  68690. });
  68691. // Custom render function.
  68692. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  68693. // Blur if required afer render.
  68694. this._shadowMap.onAfterUnbindObservable.add(function () {
  68695. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68696. engine.setColorWrite(true);
  68697. }
  68698. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  68699. return;
  68700. }
  68701. var shadowMap = _this.getShadowMapForRendering();
  68702. if (shadowMap) {
  68703. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  68704. }
  68705. });
  68706. // Clear according to the chosen filter.
  68707. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  68708. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  68709. this._shadowMap.onClearObservable.add(function (engine) {
  68710. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68711. engine.clear(clearOne, false, true, false);
  68712. }
  68713. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  68714. engine.clear(clearZero, true, true, false);
  68715. }
  68716. else {
  68717. engine.clear(clearOne, true, true, false);
  68718. }
  68719. });
  68720. };
  68721. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  68722. var _this = this;
  68723. var engine = this._scene.getEngine();
  68724. var targetSize = this._mapSize / this.blurScale;
  68725. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  68726. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  68727. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68728. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68729. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68730. }
  68731. if (this.useKernelBlur) {
  68732. 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);
  68733. this._kernelBlurXPostprocess.width = targetSize;
  68734. this._kernelBlurXPostprocess.height = targetSize;
  68735. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  68736. effect.setTexture("textureSampler", _this._shadowMap);
  68737. });
  68738. 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);
  68739. this._kernelBlurXPostprocess.autoClear = false;
  68740. this._kernelBlurYPostprocess.autoClear = false;
  68741. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68742. this._kernelBlurXPostprocess.packedFloat = true;
  68743. this._kernelBlurYPostprocess.packedFloat = true;
  68744. }
  68745. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  68746. }
  68747. else {
  68748. 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);
  68749. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  68750. effect.setFloat2("screenSize", targetSize, targetSize);
  68751. effect.setTexture("textureSampler", _this._shadowMap);
  68752. });
  68753. this._boxBlurPostprocess.autoClear = false;
  68754. this._blurPostProcesses = [this._boxBlurPostprocess];
  68755. }
  68756. };
  68757. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68758. var index;
  68759. var engine = this._scene.getEngine();
  68760. if (depthOnlySubMeshes.length) {
  68761. engine.setColorWrite(false);
  68762. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68763. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  68764. }
  68765. engine.setColorWrite(true);
  68766. }
  68767. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68768. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  68769. }
  68770. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68771. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  68772. }
  68773. if (this._transparencyShadow) {
  68774. for (index = 0; index < transparentSubMeshes.length; index++) {
  68775. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  68776. }
  68777. }
  68778. };
  68779. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  68780. var _this = this;
  68781. var mesh = subMesh.getRenderingMesh();
  68782. var scene = this._scene;
  68783. var engine = scene.getEngine();
  68784. var material = subMesh.getMaterial();
  68785. if (!material) {
  68786. return;
  68787. }
  68788. // Culling
  68789. engine.setState(material.backFaceCulling);
  68790. // Managing instances
  68791. var batch = mesh._getInstancesRenderList(subMesh._id);
  68792. if (batch.mustReturn) {
  68793. return;
  68794. }
  68795. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68796. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  68797. engine.enableEffect(this._effect);
  68798. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  68799. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  68800. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  68801. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68802. this._effect.setVector3("lightData", this._cachedDirection);
  68803. }
  68804. else {
  68805. this._effect.setVector3("lightData", this._cachedPosition);
  68806. }
  68807. if (scene.activeCamera) {
  68808. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  68809. }
  68810. // Alpha test
  68811. if (material && material.needAlphaTesting()) {
  68812. var alphaTexture = material.getAlphaTestTexture();
  68813. if (alphaTexture) {
  68814. this._effect.setTexture("diffuseSampler", alphaTexture);
  68815. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  68816. }
  68817. }
  68818. // Bones
  68819. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68820. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  68821. }
  68822. // Morph targets
  68823. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  68824. if (this.forceBackFacesOnly) {
  68825. engine.setState(true, 0, false, true);
  68826. }
  68827. // Draw
  68828. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68829. if (this.forceBackFacesOnly) {
  68830. engine.setState(true, 0, false, false);
  68831. }
  68832. }
  68833. else {
  68834. // Need to reset refresh rate of the shadowMap
  68835. if (this._shadowMap) {
  68836. this._shadowMap.resetRefreshCounter();
  68837. }
  68838. }
  68839. };
  68840. ShadowGenerator.prototype._applyFilterValues = function () {
  68841. if (!this._shadowMap) {
  68842. return;
  68843. }
  68844. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  68845. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  68846. }
  68847. else {
  68848. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68849. }
  68850. };
  68851. /**
  68852. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68853. * @param onCompiled Callback triggered at the and of the effects compilation
  68854. * @param options Sets of optional options forcing the compilation with different modes
  68855. */
  68856. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  68857. var _this = this;
  68858. var localOptions = __assign({ useInstances: false }, options);
  68859. var shadowMap = this.getShadowMap();
  68860. if (!shadowMap) {
  68861. if (onCompiled) {
  68862. onCompiled(this);
  68863. }
  68864. return;
  68865. }
  68866. var renderList = shadowMap.renderList;
  68867. if (!renderList) {
  68868. if (onCompiled) {
  68869. onCompiled(this);
  68870. }
  68871. return;
  68872. }
  68873. var subMeshes = new Array();
  68874. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  68875. var mesh = renderList_1[_i];
  68876. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  68877. }
  68878. if (subMeshes.length === 0) {
  68879. if (onCompiled) {
  68880. onCompiled(this);
  68881. }
  68882. return;
  68883. }
  68884. var currentIndex = 0;
  68885. var checkReady = function () {
  68886. if (!_this._scene || !_this._scene.getEngine()) {
  68887. return;
  68888. }
  68889. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  68890. currentIndex++;
  68891. if (currentIndex >= subMeshes.length) {
  68892. if (onCompiled) {
  68893. onCompiled(_this);
  68894. }
  68895. return;
  68896. }
  68897. }
  68898. setTimeout(checkReady, 16);
  68899. };
  68900. checkReady();
  68901. };
  68902. /**
  68903. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68904. * @param options Sets of optional options forcing the compilation with different modes
  68905. * @returns A promise that resolves when the compilation completes
  68906. */
  68907. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  68908. var _this = this;
  68909. return new Promise(function (resolve) {
  68910. _this.forceCompilation(function () {
  68911. resolve();
  68912. }, options);
  68913. });
  68914. };
  68915. /**
  68916. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  68917. * @param subMesh The submesh we want to render in the shadow map
  68918. * @param useInstances Defines wether will draw in the map using instances
  68919. * @returns true if ready otherwise, false
  68920. */
  68921. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  68922. var defines = [];
  68923. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68924. defines.push("#define FLOAT");
  68925. }
  68926. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68927. defines.push("#define ESM");
  68928. }
  68929. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  68930. defines.push("#define DEPTHTEXTURE");
  68931. }
  68932. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68933. var mesh = subMesh.getMesh();
  68934. var material = subMesh.getMaterial();
  68935. // Normal bias.
  68936. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68937. attribs.push(BABYLON.VertexBuffer.NormalKind);
  68938. defines.push("#define NORMAL");
  68939. if (mesh.nonUniformScaling) {
  68940. defines.push("#define NONUNIFORMSCALING");
  68941. }
  68942. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68943. defines.push("#define DIRECTIONINLIGHTDATA");
  68944. }
  68945. }
  68946. // Alpha test
  68947. if (material && material.needAlphaTesting()) {
  68948. var alphaTexture = material.getAlphaTestTexture();
  68949. if (alphaTexture) {
  68950. defines.push("#define ALPHATEST");
  68951. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68952. attribs.push(BABYLON.VertexBuffer.UVKind);
  68953. defines.push("#define UV1");
  68954. }
  68955. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68956. if (alphaTexture.coordinatesIndex === 1) {
  68957. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68958. defines.push("#define UV2");
  68959. }
  68960. }
  68961. }
  68962. }
  68963. // Bones
  68964. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68965. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68966. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68967. if (mesh.numBoneInfluencers > 4) {
  68968. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68969. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68970. }
  68971. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68972. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68973. }
  68974. else {
  68975. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68976. }
  68977. // Morph targets
  68978. var manager = mesh.morphTargetManager;
  68979. var morphInfluencers = 0;
  68980. if (manager) {
  68981. if (manager.numInfluencers > 0) {
  68982. defines.push("#define MORPHTARGETS");
  68983. morphInfluencers = manager.numInfluencers;
  68984. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  68985. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  68986. }
  68987. }
  68988. // Instances
  68989. if (useInstances) {
  68990. defines.push("#define INSTANCES");
  68991. attribs.push("world0");
  68992. attribs.push("world1");
  68993. attribs.push("world2");
  68994. attribs.push("world3");
  68995. }
  68996. // Get correct effect
  68997. var join = defines.join("\n");
  68998. if (this._cachedDefines !== join) {
  68999. this._cachedDefines = join;
  69000. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  69001. }
  69002. if (!this._effect.isReady()) {
  69003. return false;
  69004. }
  69005. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69006. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  69007. this._initializeBlurRTTAndPostProcesses();
  69008. }
  69009. }
  69010. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  69011. return false;
  69012. }
  69013. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  69014. return false;
  69015. }
  69016. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  69017. return false;
  69018. }
  69019. return true;
  69020. };
  69021. /**
  69022. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  69023. * @param defines Defines of the material we want to update
  69024. * @param lightIndex Index of the light in the enabled light list of the material
  69025. */
  69026. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  69027. var scene = this._scene;
  69028. var light = this._light;
  69029. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69030. return;
  69031. }
  69032. defines["SHADOW" + lightIndex] = true;
  69033. if (this.useContactHardeningShadow) {
  69034. defines["SHADOWPCSS" + lightIndex] = true;
  69035. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69036. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69037. }
  69038. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69039. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69040. }
  69041. // else default to high.
  69042. }
  69043. if (this.usePercentageCloserFiltering) {
  69044. defines["SHADOWPCF" + lightIndex] = true;
  69045. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69046. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69047. }
  69048. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69049. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69050. }
  69051. // else default to high.
  69052. }
  69053. else if (this.usePoissonSampling) {
  69054. defines["SHADOWPOISSON" + lightIndex] = true;
  69055. }
  69056. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69057. defines["SHADOWESM" + lightIndex] = true;
  69058. }
  69059. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69060. defines["SHADOWCLOSEESM" + lightIndex] = true;
  69061. }
  69062. if (light.needCube()) {
  69063. defines["SHADOWCUBE" + lightIndex] = true;
  69064. }
  69065. };
  69066. /**
  69067. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  69068. * defined in the generator but impacting the effect).
  69069. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  69070. * @param effect The effect we are binfing the information for
  69071. */
  69072. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  69073. var light = this._light;
  69074. var scene = this._scene;
  69075. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69076. return;
  69077. }
  69078. var camera = scene.activeCamera;
  69079. if (!camera) {
  69080. return;
  69081. }
  69082. var shadowMap = this.getShadowMap();
  69083. if (!shadowMap) {
  69084. return;
  69085. }
  69086. if (!light.needCube()) {
  69087. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  69088. }
  69089. // Only PCF uses depth stencil texture.
  69090. if (this._filter === ShadowGenerator.FILTER_PCF) {
  69091. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69092. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69093. }
  69094. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  69095. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69096. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  69097. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69098. }
  69099. else {
  69100. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69101. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  69102. }
  69103. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  69104. };
  69105. /**
  69106. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  69107. * (eq to shadow prjection matrix * light transform matrix)
  69108. * @returns The transform matrix used to create the shadow map
  69109. */
  69110. ShadowGenerator.prototype.getTransformMatrix = function () {
  69111. var scene = this._scene;
  69112. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  69113. return this._transformMatrix;
  69114. }
  69115. this._currentRenderID = scene.getRenderId();
  69116. this._currentFaceIndexCache = this._currentFaceIndex;
  69117. var lightPosition = this._light.position;
  69118. if (this._light.computeTransformedInformation()) {
  69119. lightPosition = this._light.transformedPosition;
  69120. }
  69121. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  69122. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  69123. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  69124. }
  69125. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  69126. this._cachedPosition.copyFrom(lightPosition);
  69127. this._cachedDirection.copyFrom(this._lightDirection);
  69128. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  69129. var shadowMap = this.getShadowMap();
  69130. if (shadowMap) {
  69131. var renderList = shadowMap.renderList;
  69132. if (renderList) {
  69133. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  69134. }
  69135. }
  69136. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  69137. }
  69138. return this._transformMatrix;
  69139. };
  69140. /**
  69141. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  69142. * Cube and 2D textures for instance.
  69143. */
  69144. ShadowGenerator.prototype.recreateShadowMap = function () {
  69145. var shadowMap = this._shadowMap;
  69146. if (!shadowMap) {
  69147. return;
  69148. }
  69149. // Track render list.
  69150. var renderList = shadowMap.renderList;
  69151. // Clean up existing data.
  69152. this._disposeRTTandPostProcesses();
  69153. // Reinitializes.
  69154. this._initializeGenerator();
  69155. // Reaffect the filter to ensure a correct fallback if necessary.
  69156. this.filter = this.filter;
  69157. // Reaffect the filter.
  69158. this._applyFilterValues();
  69159. // Reaffect Render List.
  69160. this._shadowMap.renderList = renderList;
  69161. };
  69162. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  69163. if (this._shadowMap2) {
  69164. this._shadowMap2.dispose();
  69165. this._shadowMap2 = null;
  69166. }
  69167. if (this._boxBlurPostprocess) {
  69168. this._boxBlurPostprocess.dispose();
  69169. this._boxBlurPostprocess = null;
  69170. }
  69171. if (this._kernelBlurXPostprocess) {
  69172. this._kernelBlurXPostprocess.dispose();
  69173. this._kernelBlurXPostprocess = null;
  69174. }
  69175. if (this._kernelBlurYPostprocess) {
  69176. this._kernelBlurYPostprocess.dispose();
  69177. this._kernelBlurYPostprocess = null;
  69178. }
  69179. this._blurPostProcesses = [];
  69180. };
  69181. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  69182. if (this._shadowMap) {
  69183. this._shadowMap.dispose();
  69184. this._shadowMap = null;
  69185. }
  69186. this._disposeBlurPostProcesses();
  69187. };
  69188. /**
  69189. * Disposes the ShadowGenerator.
  69190. * Returns nothing.
  69191. */
  69192. ShadowGenerator.prototype.dispose = function () {
  69193. this._disposeRTTandPostProcesses();
  69194. if (this._light) {
  69195. this._light._shadowGenerator = null;
  69196. this._light._markMeshesAsLightDirty();
  69197. }
  69198. };
  69199. /**
  69200. * Serializes the shadow generator setup to a json object.
  69201. * @returns The serialized JSON object
  69202. */
  69203. ShadowGenerator.prototype.serialize = function () {
  69204. var serializationObject = {};
  69205. var shadowMap = this.getShadowMap();
  69206. if (!shadowMap) {
  69207. return serializationObject;
  69208. }
  69209. serializationObject.lightId = this._light.id;
  69210. serializationObject.mapSize = shadowMap.getRenderSize();
  69211. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  69212. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  69213. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69214. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69215. serializationObject.usePoissonSampling = this.usePoissonSampling;
  69216. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  69217. serializationObject.depthScale = this.depthScale;
  69218. serializationObject.darkness = this.getDarkness();
  69219. serializationObject.blurBoxOffset = this.blurBoxOffset;
  69220. serializationObject.blurKernel = this.blurKernel;
  69221. serializationObject.blurScale = this.blurScale;
  69222. serializationObject.useKernelBlur = this.useKernelBlur;
  69223. serializationObject.transparencyShadow = this._transparencyShadow;
  69224. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  69225. serializationObject.bias = this.bias;
  69226. serializationObject.normalBias = this.normalBias;
  69227. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  69228. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  69229. serializationObject.filteringQuality = this.filteringQuality;
  69230. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  69231. serializationObject.renderList = [];
  69232. if (shadowMap.renderList) {
  69233. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  69234. var mesh = shadowMap.renderList[meshIndex];
  69235. serializationObject.renderList.push(mesh.id);
  69236. }
  69237. }
  69238. return serializationObject;
  69239. };
  69240. /**
  69241. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  69242. * @param parsedShadowGenerator The JSON object to parse
  69243. * @param scene The scene to create the shadow map for
  69244. * @returns The parsed shadow generator
  69245. */
  69246. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  69247. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  69248. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  69249. var shadowMap = shadowGenerator.getShadowMap();
  69250. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  69251. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  69252. meshes.forEach(function (mesh) {
  69253. if (!shadowMap) {
  69254. return;
  69255. }
  69256. if (!shadowMap.renderList) {
  69257. shadowMap.renderList = [];
  69258. }
  69259. shadowMap.renderList.push(mesh);
  69260. });
  69261. }
  69262. if (parsedShadowGenerator.usePoissonSampling) {
  69263. shadowGenerator.usePoissonSampling = true;
  69264. }
  69265. else if (parsedShadowGenerator.useExponentialShadowMap) {
  69266. shadowGenerator.useExponentialShadowMap = true;
  69267. }
  69268. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  69269. shadowGenerator.useBlurExponentialShadowMap = true;
  69270. }
  69271. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  69272. shadowGenerator.useCloseExponentialShadowMap = true;
  69273. }
  69274. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  69275. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  69276. }
  69277. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  69278. shadowGenerator.usePercentageCloserFiltering = true;
  69279. }
  69280. else if (parsedShadowGenerator.useContactHardeningShadow) {
  69281. shadowGenerator.useContactHardeningShadow = true;
  69282. }
  69283. if (parsedShadowGenerator.filteringQuality) {
  69284. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  69285. }
  69286. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  69287. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  69288. }
  69289. // Backward compat
  69290. else if (parsedShadowGenerator.useVarianceShadowMap) {
  69291. shadowGenerator.useExponentialShadowMap = true;
  69292. }
  69293. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  69294. shadowGenerator.useBlurExponentialShadowMap = true;
  69295. }
  69296. if (parsedShadowGenerator.depthScale) {
  69297. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  69298. }
  69299. if (parsedShadowGenerator.blurScale) {
  69300. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  69301. }
  69302. if (parsedShadowGenerator.blurBoxOffset) {
  69303. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  69304. }
  69305. if (parsedShadowGenerator.useKernelBlur) {
  69306. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  69307. }
  69308. if (parsedShadowGenerator.blurKernel) {
  69309. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  69310. }
  69311. if (parsedShadowGenerator.bias !== undefined) {
  69312. shadowGenerator.bias = parsedShadowGenerator.bias;
  69313. }
  69314. if (parsedShadowGenerator.normalBias !== undefined) {
  69315. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  69316. }
  69317. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  69318. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  69319. }
  69320. if (parsedShadowGenerator.darkness) {
  69321. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  69322. }
  69323. if (parsedShadowGenerator.transparencyShadow) {
  69324. shadowGenerator.setTransparencyShadow(true);
  69325. }
  69326. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  69327. return shadowGenerator;
  69328. };
  69329. /**
  69330. * Shadow generator mode None: no filtering applied.
  69331. */
  69332. ShadowGenerator.FILTER_NONE = 0;
  69333. /**
  69334. * Shadow generator mode ESM: Exponential Shadow Mapping.
  69335. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69336. */
  69337. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  69338. /**
  69339. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  69340. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  69341. */
  69342. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  69343. /**
  69344. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  69345. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69346. */
  69347. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  69348. /**
  69349. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  69350. * edge artifacts on steep falloff.
  69351. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69352. */
  69353. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  69354. /**
  69355. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  69356. * edge artifacts on steep falloff.
  69357. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69358. */
  69359. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  69360. /**
  69361. * Shadow generator mode PCF: Percentage Closer Filtering
  69362. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  69363. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  69364. */
  69365. ShadowGenerator.FILTER_PCF = 6;
  69366. /**
  69367. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  69368. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  69369. * Contact Hardening
  69370. */
  69371. ShadowGenerator.FILTER_PCSS = 7;
  69372. /**
  69373. * Reserved for PCF and PCSS
  69374. * Highest Quality.
  69375. *
  69376. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  69377. *
  69378. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  69379. */
  69380. ShadowGenerator.QUALITY_HIGH = 0;
  69381. /**
  69382. * Reserved for PCF and PCSS
  69383. * Good tradeoff for quality/perf cross devices
  69384. *
  69385. * Execute PCF on a 3*3 kernel.
  69386. *
  69387. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  69388. */
  69389. ShadowGenerator.QUALITY_MEDIUM = 1;
  69390. /**
  69391. * Reserved for PCF and PCSS
  69392. * The lowest quality but the fastest.
  69393. *
  69394. * Execute PCF on a 1*1 kernel.
  69395. *
  69396. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  69397. */
  69398. ShadowGenerator.QUALITY_LOW = 2;
  69399. return ShadowGenerator;
  69400. }());
  69401. BABYLON.ShadowGenerator = ShadowGenerator;
  69402. })(BABYLON || (BABYLON = {}));
  69403. //# sourceMappingURL=babylon.shadowGenerator.js.map
  69404. var BABYLON;
  69405. (function (BABYLON) {
  69406. var DefaultLoadingScreen = /** @class */ (function () {
  69407. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  69408. if (_loadingText === void 0) { _loadingText = ""; }
  69409. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  69410. var _this = this;
  69411. this._renderingCanvas = _renderingCanvas;
  69412. this._loadingText = _loadingText;
  69413. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  69414. // Resize
  69415. this._resizeLoadingUI = function () {
  69416. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  69417. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  69418. if (!_this._loadingDiv) {
  69419. return;
  69420. }
  69421. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  69422. _this._loadingDiv.style.left = canvasRect.left + "px";
  69423. _this._loadingDiv.style.top = canvasRect.top + "px";
  69424. _this._loadingDiv.style.width = canvasRect.width + "px";
  69425. _this._loadingDiv.style.height = canvasRect.height + "px";
  69426. };
  69427. }
  69428. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  69429. if (this._loadingDiv) {
  69430. // Do not add a loading screen if there is already one
  69431. return;
  69432. }
  69433. this._loadingDiv = document.createElement("div");
  69434. this._loadingDiv.id = "babylonjsLoadingDiv";
  69435. this._loadingDiv.style.opacity = "0";
  69436. this._loadingDiv.style.transition = "opacity 1.5s ease";
  69437. this._loadingDiv.style.pointerEvents = "none";
  69438. // Loading text
  69439. this._loadingTextDiv = document.createElement("div");
  69440. this._loadingTextDiv.style.position = "absolute";
  69441. this._loadingTextDiv.style.left = "0";
  69442. this._loadingTextDiv.style.top = "50%";
  69443. this._loadingTextDiv.style.marginTop = "80px";
  69444. this._loadingTextDiv.style.width = "100%";
  69445. this._loadingTextDiv.style.height = "20px";
  69446. this._loadingTextDiv.style.fontFamily = "Arial";
  69447. this._loadingTextDiv.style.fontSize = "14px";
  69448. this._loadingTextDiv.style.color = "white";
  69449. this._loadingTextDiv.style.textAlign = "center";
  69450. this._loadingTextDiv.innerHTML = "Loading";
  69451. this._loadingDiv.appendChild(this._loadingTextDiv);
  69452. //set the predefined text
  69453. this._loadingTextDiv.innerHTML = this._loadingText;
  69454. // Generating keyframes
  69455. var style = document.createElement('style');
  69456. style.type = 'text/css';
  69457. 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 }";
  69458. style.innerHTML = keyFrames;
  69459. document.getElementsByTagName('head')[0].appendChild(style);
  69460. // Loading img
  69461. var imgBack = new Image();
  69462. 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";
  69463. imgBack.style.position = "absolute";
  69464. imgBack.style.left = "50%";
  69465. imgBack.style.top = "50%";
  69466. imgBack.style.marginLeft = "-60px";
  69467. imgBack.style.marginTop = "-60px";
  69468. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  69469. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  69470. imgBack.style.transformOrigin = "50% 50%";
  69471. imgBack.style.webkitTransformOrigin = "50% 50%";
  69472. this._loadingDiv.appendChild(imgBack);
  69473. this._resizeLoadingUI();
  69474. window.addEventListener("resize", this._resizeLoadingUI);
  69475. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  69476. document.body.appendChild(this._loadingDiv);
  69477. this._loadingDiv.style.opacity = "1";
  69478. };
  69479. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  69480. var _this = this;
  69481. if (!this._loadingDiv) {
  69482. return;
  69483. }
  69484. var onTransitionEnd = function () {
  69485. if (!_this._loadingDiv) {
  69486. return;
  69487. }
  69488. document.body.removeChild(_this._loadingDiv);
  69489. window.removeEventListener("resize", _this._resizeLoadingUI);
  69490. _this._loadingDiv = null;
  69491. };
  69492. this._loadingDiv.style.opacity = "0";
  69493. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  69494. };
  69495. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  69496. set: function (text) {
  69497. this._loadingText = text;
  69498. if (this._loadingTextDiv) {
  69499. this._loadingTextDiv.innerHTML = this._loadingText;
  69500. }
  69501. },
  69502. enumerable: true,
  69503. configurable: true
  69504. });
  69505. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  69506. get: function () {
  69507. return this._loadingDivBackgroundColor;
  69508. },
  69509. set: function (color) {
  69510. this._loadingDivBackgroundColor = color;
  69511. if (!this._loadingDiv) {
  69512. return;
  69513. }
  69514. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  69515. },
  69516. enumerable: true,
  69517. configurable: true
  69518. });
  69519. return DefaultLoadingScreen;
  69520. }());
  69521. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  69522. })(BABYLON || (BABYLON = {}));
  69523. //# sourceMappingURL=babylon.loadingScreen.js.map
  69524. var BABYLON;
  69525. (function (BABYLON) {
  69526. var SceneLoaderProgressEvent = /** @class */ (function () {
  69527. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  69528. this.lengthComputable = lengthComputable;
  69529. this.loaded = loaded;
  69530. this.total = total;
  69531. }
  69532. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  69533. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  69534. };
  69535. return SceneLoaderProgressEvent;
  69536. }());
  69537. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  69538. var SceneLoader = /** @class */ (function () {
  69539. function SceneLoader() {
  69540. }
  69541. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  69542. get: function () {
  69543. return 0;
  69544. },
  69545. enumerable: true,
  69546. configurable: true
  69547. });
  69548. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  69549. get: function () {
  69550. return 1;
  69551. },
  69552. enumerable: true,
  69553. configurable: true
  69554. });
  69555. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  69556. get: function () {
  69557. return 2;
  69558. },
  69559. enumerable: true,
  69560. configurable: true
  69561. });
  69562. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  69563. get: function () {
  69564. return 3;
  69565. },
  69566. enumerable: true,
  69567. configurable: true
  69568. });
  69569. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  69570. get: function () {
  69571. return SceneLoader._ForceFullSceneLoadingForIncremental;
  69572. },
  69573. set: function (value) {
  69574. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  69575. },
  69576. enumerable: true,
  69577. configurable: true
  69578. });
  69579. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  69580. get: function () {
  69581. return SceneLoader._ShowLoadingScreen;
  69582. },
  69583. set: function (value) {
  69584. SceneLoader._ShowLoadingScreen = value;
  69585. },
  69586. enumerable: true,
  69587. configurable: true
  69588. });
  69589. Object.defineProperty(SceneLoader, "loggingLevel", {
  69590. get: function () {
  69591. return SceneLoader._loggingLevel;
  69592. },
  69593. set: function (value) {
  69594. SceneLoader._loggingLevel = value;
  69595. },
  69596. enumerable: true,
  69597. configurable: true
  69598. });
  69599. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  69600. get: function () {
  69601. return SceneLoader._CleanBoneMatrixWeights;
  69602. },
  69603. set: function (value) {
  69604. SceneLoader._CleanBoneMatrixWeights = value;
  69605. },
  69606. enumerable: true,
  69607. configurable: true
  69608. });
  69609. SceneLoader._getDefaultPlugin = function () {
  69610. return SceneLoader._registeredPlugins[".babylon"];
  69611. };
  69612. SceneLoader._getPluginForExtension = function (extension) {
  69613. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  69614. if (registeredPlugin) {
  69615. return registeredPlugin;
  69616. }
  69617. 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");
  69618. return SceneLoader._getDefaultPlugin();
  69619. };
  69620. SceneLoader._getPluginForDirectLoad = function (data) {
  69621. for (var extension in SceneLoader._registeredPlugins) {
  69622. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  69623. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  69624. return SceneLoader._registeredPlugins[extension];
  69625. }
  69626. }
  69627. return SceneLoader._getDefaultPlugin();
  69628. };
  69629. SceneLoader._getPluginForFilename = function (sceneFilename) {
  69630. if (sceneFilename.name) {
  69631. sceneFilename = sceneFilename.name;
  69632. }
  69633. var queryStringPosition = sceneFilename.indexOf("?");
  69634. if (queryStringPosition !== -1) {
  69635. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  69636. }
  69637. var dotPosition = sceneFilename.lastIndexOf(".");
  69638. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  69639. return SceneLoader._getPluginForExtension(extension);
  69640. };
  69641. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  69642. SceneLoader._getDirectLoad = function (sceneFilename) {
  69643. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  69644. return sceneFilename.substr(5);
  69645. }
  69646. return null;
  69647. };
  69648. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  69649. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  69650. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  69651. var plugin;
  69652. if (registeredPlugin.plugin.createPlugin) {
  69653. plugin = registeredPlugin.plugin.createPlugin();
  69654. }
  69655. else {
  69656. plugin = registeredPlugin.plugin;
  69657. }
  69658. var useArrayBuffer = registeredPlugin.isBinary;
  69659. var database;
  69660. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  69661. var dataCallback = function (data, responseURL) {
  69662. if (scene.isDisposed) {
  69663. onError("Scene has been disposed");
  69664. return;
  69665. }
  69666. scene.database = database;
  69667. onSuccess(plugin, data, responseURL);
  69668. };
  69669. var request = null;
  69670. var pluginDisposed = false;
  69671. var onDisposeObservable = plugin.onDisposeObservable;
  69672. if (onDisposeObservable) {
  69673. onDisposeObservable.add(function () {
  69674. pluginDisposed = true;
  69675. if (request) {
  69676. request.abort();
  69677. request = null;
  69678. }
  69679. onDispose();
  69680. });
  69681. }
  69682. var manifestChecked = function () {
  69683. if (pluginDisposed) {
  69684. return;
  69685. }
  69686. var url = rootUrl + sceneFilename;
  69687. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  69688. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  69689. } : undefined, database, useArrayBuffer, function (request, exception) {
  69690. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  69691. });
  69692. };
  69693. if (directLoad) {
  69694. dataCallback(directLoad);
  69695. return plugin;
  69696. }
  69697. if (rootUrl.indexOf("file:") === -1) {
  69698. var engine = scene.getEngine();
  69699. var canUseOfflineSupport = engine.enableOfflineSupport;
  69700. if (canUseOfflineSupport) {
  69701. // Also check for exceptions
  69702. var exceptionFound = false;
  69703. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  69704. var regex = _a[_i];
  69705. if (regex.test(rootUrl + sceneFilename)) {
  69706. exceptionFound = true;
  69707. break;
  69708. }
  69709. }
  69710. canUseOfflineSupport = !exceptionFound;
  69711. }
  69712. if (canUseOfflineSupport) {
  69713. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  69714. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  69715. }
  69716. else {
  69717. manifestChecked();
  69718. }
  69719. }
  69720. // Loading file from disk via input file or drag'n'drop
  69721. else {
  69722. var fileOrString = sceneFilename;
  69723. if (fileOrString.name) { // File
  69724. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  69725. }
  69726. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  69727. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  69728. }
  69729. else {
  69730. onError("Unable to find file named " + sceneFilename);
  69731. }
  69732. }
  69733. return plugin;
  69734. };
  69735. // Public functions
  69736. SceneLoader.GetPluginForExtension = function (extension) {
  69737. return SceneLoader._getPluginForExtension(extension).plugin;
  69738. };
  69739. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  69740. return !!SceneLoader._registeredPlugins[extension];
  69741. };
  69742. SceneLoader.RegisterPlugin = function (plugin) {
  69743. if (typeof plugin.extensions === "string") {
  69744. var extension = plugin.extensions;
  69745. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69746. plugin: plugin,
  69747. isBinary: false
  69748. };
  69749. }
  69750. else {
  69751. var extensions = plugin.extensions;
  69752. Object.keys(extensions).forEach(function (extension) {
  69753. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69754. plugin: plugin,
  69755. isBinary: extensions[extension].isBinary
  69756. };
  69757. });
  69758. }
  69759. };
  69760. /**
  69761. * Import meshes into a scene
  69762. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69763. * @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)
  69764. * @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)
  69765. * @param scene the instance of BABYLON.Scene to append to
  69766. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  69767. * @param onProgress a callback with a progress event for each file being loaded
  69768. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69769. * @param pluginExtension the extension used to determine the plugin
  69770. * @returns The loaded plugin
  69771. */
  69772. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69773. if (sceneFilename === void 0) { sceneFilename = ""; }
  69774. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69775. if (onSuccess === void 0) { onSuccess = null; }
  69776. if (onProgress === void 0) { onProgress = null; }
  69777. if (onError === void 0) { onError = null; }
  69778. if (pluginExtension === void 0) { pluginExtension = null; }
  69779. if (!scene) {
  69780. BABYLON.Tools.Error("No scene available to import mesh to");
  69781. return null;
  69782. }
  69783. if (!sceneFilename) {
  69784. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69785. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69786. }
  69787. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69788. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69789. return null;
  69790. }
  69791. var loadingToken = {};
  69792. scene._addPendingData(loadingToken);
  69793. var disposeHandler = function () {
  69794. scene._removePendingData(loadingToken);
  69795. };
  69796. var errorHandler = function (message, exception) {
  69797. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  69798. if (onError) {
  69799. onError(scene, errorMessage, exception);
  69800. }
  69801. else {
  69802. BABYLON.Tools.Error(errorMessage);
  69803. // should the exception be thrown?
  69804. }
  69805. disposeHandler();
  69806. };
  69807. var progressHandler = onProgress ? function (event) {
  69808. try {
  69809. onProgress(event);
  69810. }
  69811. catch (e) {
  69812. errorHandler("Error in onProgress callback", e);
  69813. }
  69814. } : undefined;
  69815. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  69816. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  69817. if (onSuccess) {
  69818. try {
  69819. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  69820. }
  69821. catch (e) {
  69822. errorHandler("Error in onSuccess callback", e);
  69823. }
  69824. }
  69825. scene._removePendingData(loadingToken);
  69826. };
  69827. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69828. if (plugin.rewriteRootURL) {
  69829. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  69830. }
  69831. if (sceneFilename === "") {
  69832. if (sceneFilename === "") {
  69833. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69834. }
  69835. }
  69836. if (plugin.importMesh) {
  69837. var syncedPlugin = plugin;
  69838. var meshes = new Array();
  69839. var particleSystems = new Array();
  69840. var skeletons = new Array();
  69841. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  69842. return;
  69843. }
  69844. scene.loadingPluginName = plugin.name;
  69845. successHandler(meshes, particleSystems, skeletons, []);
  69846. }
  69847. else {
  69848. var asyncedPlugin = plugin;
  69849. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  69850. scene.loadingPluginName = plugin.name;
  69851. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  69852. }).catch(function (error) {
  69853. errorHandler(error.message, error);
  69854. });
  69855. }
  69856. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69857. };
  69858. /**
  69859. * Import meshes into a scene
  69860. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69861. * @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)
  69862. * @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)
  69863. * @param scene the instance of BABYLON.Scene to append to
  69864. * @param onProgress a callback with a progress event for each file being loaded
  69865. * @param pluginExtension the extension used to determine the plugin
  69866. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  69867. */
  69868. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69869. if (sceneFilename === void 0) { sceneFilename = ""; }
  69870. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69871. if (onProgress === void 0) { onProgress = null; }
  69872. if (pluginExtension === void 0) { pluginExtension = null; }
  69873. return new Promise(function (resolve, reject) {
  69874. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  69875. resolve({
  69876. meshes: meshes,
  69877. particleSystems: particleSystems,
  69878. skeletons: skeletons,
  69879. animationGroups: animationGroups
  69880. });
  69881. }, onProgress, function (scene, message, exception) {
  69882. reject(exception || new Error(message));
  69883. }, pluginExtension);
  69884. });
  69885. };
  69886. /**
  69887. * Load a scene
  69888. * @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)
  69889. * @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)
  69890. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69891. * @param onSuccess a callback with the scene when import succeeds
  69892. * @param onProgress a callback with a progress event for each file being loaded
  69893. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69894. * @param pluginExtension the extension used to determine the plugin
  69895. * @returns The loaded plugin
  69896. */
  69897. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  69898. if (onSuccess === void 0) { onSuccess = null; }
  69899. if (onProgress === void 0) { onProgress = null; }
  69900. if (onError === void 0) { onError = null; }
  69901. if (pluginExtension === void 0) { pluginExtension = null; }
  69902. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  69903. };
  69904. /**
  69905. * Load a scene
  69906. * @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)
  69907. * @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)
  69908. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69909. * @param onProgress a callback with a progress event for each file being loaded
  69910. * @param pluginExtension the extension used to determine the plugin
  69911. * @returns The loaded scene
  69912. */
  69913. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  69914. if (onProgress === void 0) { onProgress = null; }
  69915. if (pluginExtension === void 0) { pluginExtension = null; }
  69916. return new Promise(function (resolve, reject) {
  69917. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  69918. resolve(scene);
  69919. }, onProgress, function (scene, message, exception) {
  69920. reject(exception || new Error(message));
  69921. }, pluginExtension);
  69922. });
  69923. };
  69924. /**
  69925. * Append a scene
  69926. * @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)
  69927. * @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)
  69928. * @param scene is the instance of BABYLON.Scene to append to
  69929. * @param onSuccess a callback with the scene when import succeeds
  69930. * @param onProgress a callback with a progress event for each file being loaded
  69931. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69932. * @param pluginExtension the extension used to determine the plugin
  69933. * @returns The loaded plugin
  69934. */
  69935. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69936. if (sceneFilename === void 0) { sceneFilename = ""; }
  69937. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69938. if (onSuccess === void 0) { onSuccess = null; }
  69939. if (onProgress === void 0) { onProgress = null; }
  69940. if (onError === void 0) { onError = null; }
  69941. if (pluginExtension === void 0) { pluginExtension = null; }
  69942. if (!scene) {
  69943. BABYLON.Tools.Error("No scene available to append to");
  69944. return null;
  69945. }
  69946. if (!sceneFilename) {
  69947. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69948. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69949. }
  69950. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69951. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69952. return null;
  69953. }
  69954. if (SceneLoader.ShowLoadingScreen) {
  69955. scene.getEngine().displayLoadingUI();
  69956. }
  69957. var loadingToken = {};
  69958. scene._addPendingData(loadingToken);
  69959. var disposeHandler = function () {
  69960. scene._removePendingData(loadingToken);
  69961. scene.getEngine().hideLoadingUI();
  69962. };
  69963. var errorHandler = function (message, exception) {
  69964. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69965. if (onError) {
  69966. onError(scene, errorMessage, exception);
  69967. }
  69968. else {
  69969. BABYLON.Tools.Error(errorMessage);
  69970. // should the exception be thrown?
  69971. }
  69972. disposeHandler();
  69973. };
  69974. var progressHandler = onProgress ? function (event) {
  69975. try {
  69976. onProgress(event);
  69977. }
  69978. catch (e) {
  69979. errorHandler("Error in onProgress callback", e);
  69980. }
  69981. } : undefined;
  69982. var successHandler = function () {
  69983. if (onSuccess) {
  69984. try {
  69985. onSuccess(scene);
  69986. }
  69987. catch (e) {
  69988. errorHandler("Error in onSuccess callback", e);
  69989. }
  69990. }
  69991. scene._removePendingData(loadingToken);
  69992. };
  69993. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69994. if (sceneFilename === "") {
  69995. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69996. }
  69997. if (plugin.load) {
  69998. var syncedPlugin = plugin;
  69999. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  70000. return;
  70001. }
  70002. scene.loadingPluginName = plugin.name;
  70003. successHandler();
  70004. }
  70005. else {
  70006. var asyncedPlugin = plugin;
  70007. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  70008. scene.loadingPluginName = plugin.name;
  70009. successHandler();
  70010. }).catch(function (error) {
  70011. errorHandler(error.message, error);
  70012. });
  70013. }
  70014. if (SceneLoader.ShowLoadingScreen) {
  70015. scene.executeWhenReady(function () {
  70016. scene.getEngine().hideLoadingUI();
  70017. });
  70018. }
  70019. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70020. };
  70021. /**
  70022. * Append a scene
  70023. * @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)
  70024. * @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)
  70025. * @param scene is the instance of BABYLON.Scene to append to
  70026. * @param onProgress a callback with a progress event for each file being loaded
  70027. * @param pluginExtension the extension used to determine the plugin
  70028. * @returns The given scene
  70029. */
  70030. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70031. if (sceneFilename === void 0) { sceneFilename = ""; }
  70032. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70033. if (onProgress === void 0) { onProgress = null; }
  70034. if (pluginExtension === void 0) { pluginExtension = null; }
  70035. return new Promise(function (resolve, reject) {
  70036. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  70037. resolve(scene);
  70038. }, onProgress, function (scene, message, exception) {
  70039. reject(exception || new Error(message));
  70040. }, pluginExtension);
  70041. });
  70042. };
  70043. /**
  70044. * Load a scene into an asset container
  70045. * @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)
  70046. * @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)
  70047. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  70048. * @param onSuccess a callback with the scene when import succeeds
  70049. * @param onProgress a callback with a progress event for each file being loaded
  70050. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70051. * @param pluginExtension the extension used to determine the plugin
  70052. * @returns The loaded plugin
  70053. */
  70054. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70055. if (sceneFilename === void 0) { sceneFilename = ""; }
  70056. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70057. if (onSuccess === void 0) { onSuccess = null; }
  70058. if (onProgress === void 0) { onProgress = null; }
  70059. if (onError === void 0) { onError = null; }
  70060. if (pluginExtension === void 0) { pluginExtension = null; }
  70061. if (!scene) {
  70062. BABYLON.Tools.Error("No scene available to load asset container to");
  70063. return null;
  70064. }
  70065. if (!sceneFilename) {
  70066. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70067. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70068. }
  70069. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70070. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70071. return null;
  70072. }
  70073. var loadingToken = {};
  70074. scene._addPendingData(loadingToken);
  70075. var disposeHandler = function () {
  70076. scene._removePendingData(loadingToken);
  70077. };
  70078. var errorHandler = function (message, exception) {
  70079. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70080. if (onError) {
  70081. onError(scene, errorMessage, exception);
  70082. }
  70083. else {
  70084. BABYLON.Tools.Error(errorMessage);
  70085. // should the exception be thrown?
  70086. }
  70087. disposeHandler();
  70088. };
  70089. var progressHandler = onProgress ? function (event) {
  70090. try {
  70091. onProgress(event);
  70092. }
  70093. catch (e) {
  70094. errorHandler("Error in onProgress callback", e);
  70095. }
  70096. } : undefined;
  70097. var successHandler = function (assets) {
  70098. if (onSuccess) {
  70099. try {
  70100. onSuccess(assets);
  70101. }
  70102. catch (e) {
  70103. errorHandler("Error in onSuccess callback", e);
  70104. }
  70105. }
  70106. scene._removePendingData(loadingToken);
  70107. };
  70108. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70109. if (plugin.loadAssetContainer) {
  70110. var syncedPlugin = plugin;
  70111. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  70112. if (!assetContainer) {
  70113. return;
  70114. }
  70115. scene.loadingPluginName = plugin.name;
  70116. successHandler(assetContainer);
  70117. }
  70118. else if (plugin.loadAssetContainerAsync) {
  70119. var asyncedPlugin = plugin;
  70120. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  70121. scene.loadingPluginName = plugin.name;
  70122. successHandler(assetContainer);
  70123. }).catch(function (error) {
  70124. errorHandler(error.message, error);
  70125. });
  70126. }
  70127. else {
  70128. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  70129. }
  70130. if (SceneLoader.ShowLoadingScreen) {
  70131. scene.executeWhenReady(function () {
  70132. scene.getEngine().hideLoadingUI();
  70133. });
  70134. }
  70135. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70136. };
  70137. /**
  70138. * Load a scene into an asset container
  70139. * @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)
  70140. * @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)
  70141. * @param scene is the instance of BABYLON.Scene to append to
  70142. * @param onProgress a callback with a progress event for each file being loaded
  70143. * @param pluginExtension the extension used to determine the plugin
  70144. * @returns The loaded asset container
  70145. */
  70146. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70147. if (sceneFilename === void 0) { sceneFilename = ""; }
  70148. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70149. if (onProgress === void 0) { onProgress = null; }
  70150. if (pluginExtension === void 0) { pluginExtension = null; }
  70151. return new Promise(function (resolve, reject) {
  70152. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  70153. resolve(assetContainer);
  70154. }, onProgress, function (scene, message, exception) {
  70155. reject(exception || new Error(message));
  70156. }, pluginExtension);
  70157. });
  70158. };
  70159. // Flags
  70160. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  70161. SceneLoader._ShowLoadingScreen = true;
  70162. SceneLoader._CleanBoneMatrixWeights = false;
  70163. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  70164. // Members
  70165. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  70166. SceneLoader._registeredPlugins = {};
  70167. return SceneLoader;
  70168. }());
  70169. BABYLON.SceneLoader = SceneLoader;
  70170. ;
  70171. })(BABYLON || (BABYLON = {}));
  70172. //# sourceMappingURL=babylon.sceneLoader.js.map
  70173. var BABYLON;
  70174. (function (BABYLON) {
  70175. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  70176. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70177. var parsedMaterial = parsedData.materials[index];
  70178. if (parsedMaterial.id === id) {
  70179. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70180. }
  70181. }
  70182. return null;
  70183. };
  70184. var isDescendantOf = function (mesh, names, hierarchyIds) {
  70185. for (var i in names) {
  70186. if (mesh.name === names[i]) {
  70187. hierarchyIds.push(mesh.id);
  70188. return true;
  70189. }
  70190. }
  70191. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  70192. hierarchyIds.push(mesh.id);
  70193. return true;
  70194. }
  70195. return false;
  70196. };
  70197. var logOperation = function (operation, producer) {
  70198. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  70199. };
  70200. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  70201. if (addToScene === void 0) { addToScene = false; }
  70202. var container = new BABYLON.AssetContainer(scene);
  70203. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70204. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70205. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70206. // and avoid problems with multiple concurrent .babylon loads.
  70207. var log = "importScene has failed JSON parse";
  70208. try {
  70209. var parsedData = JSON.parse(data);
  70210. log = "";
  70211. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  70212. var index;
  70213. var cache;
  70214. // Lights
  70215. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  70216. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  70217. var parsedLight = parsedData.lights[index];
  70218. var light = BABYLON.Light.Parse(parsedLight, scene);
  70219. if (light) {
  70220. container.lights.push(light);
  70221. log += (index === 0 ? "\n\tLights:" : "");
  70222. log += "\n\t\t" + light.toString(fullDetails);
  70223. }
  70224. }
  70225. }
  70226. // Animations
  70227. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  70228. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  70229. var parsedAnimation = parsedData.animations[index];
  70230. var animation = BABYLON.Animation.Parse(parsedAnimation);
  70231. scene.animations.push(animation);
  70232. container.animations.push(animation);
  70233. log += (index === 0 ? "\n\tAnimations:" : "");
  70234. log += "\n\t\t" + animation.toString(fullDetails);
  70235. }
  70236. }
  70237. // Materials
  70238. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  70239. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70240. var parsedMaterial = parsedData.materials[index];
  70241. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70242. container.materials.push(mat);
  70243. log += (index === 0 ? "\n\tMaterials:" : "");
  70244. log += "\n\t\t" + mat.toString(fullDetails);
  70245. }
  70246. }
  70247. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  70248. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  70249. var parsedMultiMaterial = parsedData.multiMaterials[index];
  70250. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  70251. container.multiMaterials.push(mmat);
  70252. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  70253. log += "\n\t\t" + mmat.toString(fullDetails);
  70254. }
  70255. }
  70256. // Morph targets
  70257. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  70258. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  70259. var managerData = _a[_i];
  70260. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  70261. }
  70262. }
  70263. // Skeletons
  70264. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  70265. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  70266. var parsedSkeleton = parsedData.skeletons[index];
  70267. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  70268. container.skeletons.push(skeleton);
  70269. log += (index === 0 ? "\n\tSkeletons:" : "");
  70270. log += "\n\t\t" + skeleton.toString(fullDetails);
  70271. }
  70272. }
  70273. // Geometries
  70274. var geometries = parsedData.geometries;
  70275. if (geometries !== undefined && geometries !== null) {
  70276. var addedGeometry = new Array();
  70277. // Boxes
  70278. var boxes = geometries.boxes;
  70279. if (boxes !== undefined && boxes !== null) {
  70280. for (index = 0, cache = boxes.length; index < cache; index++) {
  70281. var parsedBox = boxes[index];
  70282. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  70283. }
  70284. }
  70285. // Spheres
  70286. var spheres = geometries.spheres;
  70287. if (spheres !== undefined && spheres !== null) {
  70288. for (index = 0, cache = spheres.length; index < cache; index++) {
  70289. var parsedSphere = spheres[index];
  70290. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  70291. }
  70292. }
  70293. // Cylinders
  70294. var cylinders = geometries.cylinders;
  70295. if (cylinders !== undefined && cylinders !== null) {
  70296. for (index = 0, cache = cylinders.length; index < cache; index++) {
  70297. var parsedCylinder = cylinders[index];
  70298. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  70299. }
  70300. }
  70301. // Toruses
  70302. var toruses = geometries.toruses;
  70303. if (toruses !== undefined && toruses !== null) {
  70304. for (index = 0, cache = toruses.length; index < cache; index++) {
  70305. var parsedTorus = toruses[index];
  70306. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  70307. }
  70308. }
  70309. // Grounds
  70310. var grounds = geometries.grounds;
  70311. if (grounds !== undefined && grounds !== null) {
  70312. for (index = 0, cache = grounds.length; index < cache; index++) {
  70313. var parsedGround = grounds[index];
  70314. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  70315. }
  70316. }
  70317. // Planes
  70318. var planes = geometries.planes;
  70319. if (planes !== undefined && planes !== null) {
  70320. for (index = 0, cache = planes.length; index < cache; index++) {
  70321. var parsedPlane = planes[index];
  70322. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  70323. }
  70324. }
  70325. // TorusKnots
  70326. var torusKnots = geometries.torusKnots;
  70327. if (torusKnots !== undefined && torusKnots !== null) {
  70328. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  70329. var parsedTorusKnot = torusKnots[index];
  70330. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  70331. }
  70332. }
  70333. // VertexData
  70334. var vertexData = geometries.vertexData;
  70335. if (vertexData !== undefined && vertexData !== null) {
  70336. for (index = 0, cache = vertexData.length; index < cache; index++) {
  70337. var parsedVertexData = vertexData[index];
  70338. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  70339. }
  70340. }
  70341. addedGeometry.forEach(function (g) {
  70342. if (g) {
  70343. container.geometries.push(g);
  70344. }
  70345. });
  70346. }
  70347. // Transform nodes
  70348. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  70349. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  70350. var parsedTransformNode = parsedData.transformNodes[index];
  70351. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  70352. container.transformNodes.push(node);
  70353. }
  70354. }
  70355. // Meshes
  70356. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  70357. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  70358. var parsedMesh = parsedData.meshes[index];
  70359. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  70360. container.meshes.push(mesh);
  70361. log += (index === 0 ? "\n\tMeshes:" : "");
  70362. log += "\n\t\t" + mesh.toString(fullDetails);
  70363. }
  70364. }
  70365. // Cameras
  70366. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  70367. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  70368. var parsedCamera = parsedData.cameras[index];
  70369. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  70370. container.cameras.push(camera);
  70371. log += (index === 0 ? "\n\tCameras:" : "");
  70372. log += "\n\t\t" + camera.toString(fullDetails);
  70373. }
  70374. }
  70375. // Browsing all the graph to connect the dots
  70376. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  70377. var camera = scene.cameras[index];
  70378. if (camera._waitingParentId) {
  70379. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  70380. camera._waitingParentId = null;
  70381. }
  70382. }
  70383. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  70384. var light_1 = scene.lights[index];
  70385. if (light_1 && light_1._waitingParentId) {
  70386. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  70387. light_1._waitingParentId = null;
  70388. }
  70389. }
  70390. // Sounds
  70391. // TODO: add sound
  70392. var loadedSounds = [];
  70393. var loadedSound;
  70394. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  70395. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  70396. var parsedSound = parsedData.sounds[index];
  70397. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70398. if (!parsedSound.url)
  70399. parsedSound.url = parsedSound.name;
  70400. if (!loadedSounds[parsedSound.url]) {
  70401. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  70402. loadedSounds[parsedSound.url] = loadedSound;
  70403. container.sounds.push(loadedSound);
  70404. }
  70405. else {
  70406. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  70407. }
  70408. }
  70409. else {
  70410. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  70411. }
  70412. }
  70413. }
  70414. loadedSounds = [];
  70415. // Connect parents & children and parse actions
  70416. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  70417. var transformNode = scene.transformNodes[index];
  70418. if (transformNode._waitingParentId) {
  70419. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  70420. transformNode._waitingParentId = null;
  70421. }
  70422. }
  70423. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70424. var mesh = scene.meshes[index];
  70425. if (mesh._waitingParentId) {
  70426. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  70427. mesh._waitingParentId = null;
  70428. }
  70429. if (mesh._waitingActions) {
  70430. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  70431. mesh._waitingActions = null;
  70432. }
  70433. }
  70434. // freeze world matrix application
  70435. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70436. var currentMesh = scene.meshes[index];
  70437. if (currentMesh._waitingFreezeWorldMatrix) {
  70438. currentMesh.freezeWorldMatrix();
  70439. currentMesh._waitingFreezeWorldMatrix = null;
  70440. }
  70441. else {
  70442. currentMesh.computeWorldMatrix(true);
  70443. }
  70444. }
  70445. // Shadows
  70446. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  70447. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  70448. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  70449. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  70450. // SG would be available on their associated lights
  70451. }
  70452. }
  70453. // Lights exclusions / inclusions
  70454. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  70455. var light_2 = scene.lights[index];
  70456. // Excluded check
  70457. if (light_2._excludedMeshesIds.length > 0) {
  70458. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  70459. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  70460. if (excludedMesh) {
  70461. light_2.excludedMeshes.push(excludedMesh);
  70462. }
  70463. }
  70464. light_2._excludedMeshesIds = [];
  70465. }
  70466. // Included check
  70467. if (light_2._includedOnlyMeshesIds.length > 0) {
  70468. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  70469. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  70470. if (includedOnlyMesh) {
  70471. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  70472. }
  70473. }
  70474. light_2._includedOnlyMeshesIds = [];
  70475. }
  70476. }
  70477. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  70478. // Actions (scene)
  70479. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  70480. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  70481. }
  70482. if (!addToScene) {
  70483. container.removeAllFromScene();
  70484. }
  70485. }
  70486. catch (err) {
  70487. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  70488. if (onError) {
  70489. onError(msg, err);
  70490. }
  70491. else {
  70492. BABYLON.Tools.Log(msg);
  70493. throw err;
  70494. }
  70495. }
  70496. finally {
  70497. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70498. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70499. }
  70500. }
  70501. return container;
  70502. };
  70503. BABYLON.SceneLoader.RegisterPlugin({
  70504. name: "babylon.js",
  70505. extensions: ".babylon",
  70506. canDirectLoad: function (data) {
  70507. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  70508. return true;
  70509. }
  70510. return false;
  70511. },
  70512. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  70513. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70514. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70515. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70516. // and avoid problems with multiple concurrent .babylon loads.
  70517. var log = "importMesh has failed JSON parse";
  70518. try {
  70519. var parsedData = JSON.parse(data);
  70520. log = "";
  70521. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  70522. if (!meshesNames) {
  70523. meshesNames = null;
  70524. }
  70525. else if (!Array.isArray(meshesNames)) {
  70526. meshesNames = [meshesNames];
  70527. }
  70528. var hierarchyIds = new Array();
  70529. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  70530. var loadedSkeletonsIds = [];
  70531. var loadedMaterialsIds = [];
  70532. var index;
  70533. var cache;
  70534. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  70535. var parsedMesh = parsedData.meshes[index];
  70536. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  70537. if (meshesNames !== null) {
  70538. // Remove found mesh name from list.
  70539. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  70540. }
  70541. //Geometry?
  70542. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  70543. //does the file contain geometries?
  70544. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  70545. //find the correct geometry and add it to the scene
  70546. var found = false;
  70547. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  70548. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  70549. return;
  70550. }
  70551. else {
  70552. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  70553. if (parsedGeometryData.id === parsedMesh.geometryId) {
  70554. switch (geometryType) {
  70555. case "boxes":
  70556. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  70557. break;
  70558. case "spheres":
  70559. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  70560. break;
  70561. case "cylinders":
  70562. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  70563. break;
  70564. case "toruses":
  70565. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  70566. break;
  70567. case "grounds":
  70568. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  70569. break;
  70570. case "planes":
  70571. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  70572. break;
  70573. case "torusKnots":
  70574. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  70575. break;
  70576. case "vertexData":
  70577. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  70578. break;
  70579. }
  70580. found = true;
  70581. }
  70582. });
  70583. }
  70584. });
  70585. if (found === false) {
  70586. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  70587. }
  70588. }
  70589. }
  70590. // Material ?
  70591. if (parsedMesh.materialId) {
  70592. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  70593. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  70594. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  70595. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  70596. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  70597. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  70598. var subMatId = parsedMultiMaterial.materials[matIndex];
  70599. loadedMaterialsIds.push(subMatId);
  70600. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  70601. if (mat) {
  70602. log += "\n\tMaterial " + mat.toString(fullDetails);
  70603. }
  70604. }
  70605. loadedMaterialsIds.push(parsedMultiMaterial.id);
  70606. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  70607. if (mmat) {
  70608. materialFound = true;
  70609. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  70610. }
  70611. break;
  70612. }
  70613. }
  70614. }
  70615. if (materialFound === false) {
  70616. loadedMaterialsIds.push(parsedMesh.materialId);
  70617. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  70618. if (!mat) {
  70619. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  70620. }
  70621. else {
  70622. log += "\n\tMaterial " + mat.toString(fullDetails);
  70623. }
  70624. }
  70625. }
  70626. // Skeleton ?
  70627. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  70628. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  70629. if (skeletonAlreadyLoaded === false) {
  70630. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  70631. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  70632. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  70633. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  70634. skeletons.push(skeleton);
  70635. loadedSkeletonsIds.push(parsedSkeleton.id);
  70636. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  70637. }
  70638. }
  70639. }
  70640. }
  70641. // Morph targets ?
  70642. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  70643. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  70644. var managerData = _a[_i];
  70645. BABYLON.MorphTargetManager.Parse(managerData, scene);
  70646. }
  70647. }
  70648. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  70649. meshes.push(mesh);
  70650. log += "\n\tMesh " + mesh.toString(fullDetails);
  70651. }
  70652. }
  70653. // Connecting parents
  70654. var currentMesh;
  70655. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70656. currentMesh = scene.meshes[index];
  70657. if (currentMesh._waitingParentId) {
  70658. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  70659. currentMesh._waitingParentId = null;
  70660. }
  70661. }
  70662. // freeze and compute world matrix application
  70663. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70664. currentMesh = scene.meshes[index];
  70665. if (currentMesh._waitingFreezeWorldMatrix) {
  70666. currentMesh.freezeWorldMatrix();
  70667. currentMesh._waitingFreezeWorldMatrix = null;
  70668. }
  70669. else {
  70670. currentMesh.computeWorldMatrix(true);
  70671. }
  70672. }
  70673. }
  70674. // Particles
  70675. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  70676. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  70677. if (parser) {
  70678. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  70679. var parsedParticleSystem = parsedData.particleSystems[index];
  70680. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  70681. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  70682. }
  70683. }
  70684. }
  70685. }
  70686. return true;
  70687. }
  70688. catch (err) {
  70689. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  70690. if (onError) {
  70691. onError(msg, err);
  70692. }
  70693. else {
  70694. BABYLON.Tools.Log(msg);
  70695. throw err;
  70696. }
  70697. }
  70698. finally {
  70699. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70700. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70701. }
  70702. }
  70703. return false;
  70704. },
  70705. load: function (scene, data, rootUrl, onError) {
  70706. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70707. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70708. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70709. // and avoid problems with multiple concurrent .babylon loads.
  70710. var log = "importScene has failed JSON parse";
  70711. try {
  70712. var parsedData = JSON.parse(data);
  70713. log = "";
  70714. // Scene
  70715. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  70716. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  70717. }
  70718. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  70719. scene.autoClear = parsedData.autoClear;
  70720. }
  70721. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  70722. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  70723. }
  70724. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  70725. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  70726. }
  70727. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  70728. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  70729. }
  70730. // Fog
  70731. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  70732. scene.fogMode = parsedData.fogMode;
  70733. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  70734. scene.fogStart = parsedData.fogStart;
  70735. scene.fogEnd = parsedData.fogEnd;
  70736. scene.fogDensity = parsedData.fogDensity;
  70737. log += "\tFog mode for scene: ";
  70738. switch (scene.fogMode) {
  70739. // getters not compiling, so using hardcoded
  70740. case 1:
  70741. log += "exp\n";
  70742. break;
  70743. case 2:
  70744. log += "exp2\n";
  70745. break;
  70746. case 3:
  70747. log += "linear\n";
  70748. break;
  70749. }
  70750. }
  70751. //Physics
  70752. if (parsedData.physicsEnabled) {
  70753. var physicsPlugin;
  70754. if (parsedData.physicsEngine === "cannon") {
  70755. physicsPlugin = new BABYLON.CannonJSPlugin();
  70756. }
  70757. else if (parsedData.physicsEngine === "oimo") {
  70758. physicsPlugin = new BABYLON.OimoJSPlugin();
  70759. }
  70760. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  70761. //else - default engine, which is currently oimo
  70762. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  70763. scene.enablePhysics(physicsGravity, physicsPlugin);
  70764. }
  70765. // Metadata
  70766. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  70767. scene.metadata = parsedData.metadata;
  70768. }
  70769. //collisions, if defined. otherwise, default is true
  70770. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  70771. scene.collisionsEnabled = parsedData.collisionsEnabled;
  70772. }
  70773. scene.workerCollisions = !!parsedData.workerCollisions;
  70774. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  70775. if (!container) {
  70776. return false;
  70777. }
  70778. if (parsedData.autoAnimate) {
  70779. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  70780. }
  70781. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  70782. scene.setActiveCameraByID(parsedData.activeCameraID);
  70783. }
  70784. // Environment texture
  70785. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  70786. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  70787. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  70788. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  70789. if (parsedData.environmentTextureRotationY) {
  70790. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  70791. }
  70792. scene.environmentTexture = hdrTexture;
  70793. }
  70794. else {
  70795. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  70796. if (parsedData.environmentTextureRotationY) {
  70797. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  70798. }
  70799. scene.environmentTexture = cubeTexture;
  70800. }
  70801. if (parsedData.createDefaultSkybox === true) {
  70802. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  70803. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  70804. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  70805. }
  70806. }
  70807. // Finish
  70808. return true;
  70809. }
  70810. catch (err) {
  70811. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  70812. if (onError) {
  70813. onError(msg, err);
  70814. }
  70815. else {
  70816. BABYLON.Tools.Log(msg);
  70817. throw err;
  70818. }
  70819. }
  70820. finally {
  70821. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70822. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70823. }
  70824. }
  70825. return false;
  70826. },
  70827. loadAssetContainer: function (scene, data, rootUrl, onError) {
  70828. var container = loadAssetContainer(scene, data, rootUrl, onError);
  70829. return container;
  70830. }
  70831. });
  70832. })(BABYLON || (BABYLON = {}));
  70833. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  70834. var BABYLON;
  70835. (function (BABYLON) {
  70836. var FilesInput = /** @class */ (function () {
  70837. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  70838. this.onProcessFileCallback = function () { return true; };
  70839. this._engine = engine;
  70840. this._currentScene = scene;
  70841. this._sceneLoadedCallback = sceneLoadedCallback;
  70842. this._progressCallback = progressCallback;
  70843. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  70844. this._textureLoadingCallback = textureLoadingCallback;
  70845. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  70846. this._onReloadCallback = onReloadCallback;
  70847. this._errorCallback = errorCallback;
  70848. }
  70849. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  70850. var _this = this;
  70851. if (elementToMonitor) {
  70852. this._elementToMonitor = elementToMonitor;
  70853. this._dragEnterHandler = function (e) { _this.drag(e); };
  70854. this._dragOverHandler = function (e) { _this.drag(e); };
  70855. this._dropHandler = function (e) { _this.drop(e); };
  70856. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  70857. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  70858. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  70859. }
  70860. };
  70861. FilesInput.prototype.dispose = function () {
  70862. if (!this._elementToMonitor) {
  70863. return;
  70864. }
  70865. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  70866. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  70867. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  70868. };
  70869. FilesInput.prototype.renderFunction = function () {
  70870. if (this._additionalRenderLoopLogicCallback) {
  70871. this._additionalRenderLoopLogicCallback();
  70872. }
  70873. if (this._currentScene) {
  70874. if (this._textureLoadingCallback) {
  70875. var remaining = this._currentScene.getWaitingItemsCount();
  70876. if (remaining > 0) {
  70877. this._textureLoadingCallback(remaining);
  70878. }
  70879. }
  70880. this._currentScene.render();
  70881. }
  70882. };
  70883. FilesInput.prototype.drag = function (e) {
  70884. e.stopPropagation();
  70885. e.preventDefault();
  70886. };
  70887. FilesInput.prototype.drop = function (eventDrop) {
  70888. eventDrop.stopPropagation();
  70889. eventDrop.preventDefault();
  70890. this.loadFiles(eventDrop);
  70891. };
  70892. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  70893. var _this = this;
  70894. var reader = folder.createReader();
  70895. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  70896. reader.readEntries(function (entries) {
  70897. remaining.count += entries.length;
  70898. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  70899. var entry = entries_1[_i];
  70900. if (entry.isFile) {
  70901. entry.file(function (file) {
  70902. file.correctName = relativePath + file.name;
  70903. files.push(file);
  70904. if (--remaining.count === 0) {
  70905. callback();
  70906. }
  70907. });
  70908. }
  70909. else if (entry.isDirectory) {
  70910. _this._traverseFolder(entry, files, remaining, callback);
  70911. }
  70912. }
  70913. if (--remaining.count) {
  70914. callback();
  70915. }
  70916. });
  70917. };
  70918. FilesInput.prototype._processFiles = function (files) {
  70919. for (var i = 0; i < files.length; i++) {
  70920. var name = files[i].correctName.toLowerCase();
  70921. var extension = name.split('.').pop();
  70922. if (!this.onProcessFileCallback(files[i], name, extension)) {
  70923. continue;
  70924. }
  70925. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  70926. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  70927. this._sceneFileToLoad = files[i];
  70928. }
  70929. else {
  70930. FilesInput.FilesToLoad[name] = files[i];
  70931. }
  70932. }
  70933. };
  70934. FilesInput.prototype.loadFiles = function (event) {
  70935. var _this = this;
  70936. if (this._startingProcessingFilesCallback)
  70937. this._startingProcessingFilesCallback();
  70938. // Handling data transfer via drag'n'drop
  70939. if (event && event.dataTransfer && event.dataTransfer.files) {
  70940. this._filesToLoad = event.dataTransfer.files;
  70941. }
  70942. // Handling files from input files
  70943. if (event && event.target && event.target.files) {
  70944. this._filesToLoad = event.target.files;
  70945. }
  70946. if (this._filesToLoad && this._filesToLoad.length > 0) {
  70947. var files_1 = new Array();
  70948. var folders = [];
  70949. var items = event.dataTransfer ? event.dataTransfer.items : null;
  70950. for (var i = 0; i < this._filesToLoad.length; i++) {
  70951. var fileToLoad = this._filesToLoad[i];
  70952. var name_1 = fileToLoad.name.toLowerCase();
  70953. var entry = void 0;
  70954. fileToLoad.correctName = name_1;
  70955. if (items) {
  70956. var item = items[i];
  70957. if (item.getAsEntry) {
  70958. entry = item.getAsEntry();
  70959. }
  70960. else if (item.webkitGetAsEntry) {
  70961. entry = item.webkitGetAsEntry();
  70962. }
  70963. }
  70964. if (!entry) {
  70965. files_1.push(fileToLoad);
  70966. }
  70967. else {
  70968. if (entry.isDirectory) {
  70969. folders.push(entry);
  70970. }
  70971. else {
  70972. files_1.push(fileToLoad);
  70973. }
  70974. }
  70975. }
  70976. if (folders.length === 0) {
  70977. this._processFiles(files_1);
  70978. this._processReload();
  70979. }
  70980. else {
  70981. var remaining = { count: folders.length };
  70982. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  70983. var folder = folders_1[_i];
  70984. this._traverseFolder(folder, files_1, remaining, function () {
  70985. _this._processFiles(files_1);
  70986. if (remaining.count === 0) {
  70987. _this._processReload();
  70988. }
  70989. });
  70990. }
  70991. }
  70992. }
  70993. };
  70994. FilesInput.prototype._processReload = function () {
  70995. if (this._onReloadCallback) {
  70996. this._onReloadCallback(this._sceneFileToLoad);
  70997. }
  70998. else {
  70999. this.reload();
  71000. }
  71001. };
  71002. FilesInput.prototype.reload = function () {
  71003. var _this = this;
  71004. // If a scene file has been provided
  71005. if (this._sceneFileToLoad) {
  71006. if (this._currentScene) {
  71007. if (BABYLON.Tools.errorsCount > 0) {
  71008. BABYLON.Tools.ClearLogCache();
  71009. }
  71010. this._engine.stopRenderLoop();
  71011. }
  71012. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  71013. if (_this._progressCallback) {
  71014. _this._progressCallback(progress);
  71015. }
  71016. }).then(function (scene) {
  71017. if (_this._currentScene) {
  71018. _this._currentScene.dispose();
  71019. }
  71020. _this._currentScene = scene;
  71021. if (_this._sceneLoadedCallback) {
  71022. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  71023. }
  71024. // Wait for textures and shaders to be ready
  71025. _this._currentScene.executeWhenReady(function () {
  71026. _this._engine.runRenderLoop(function () {
  71027. _this.renderFunction();
  71028. });
  71029. });
  71030. }).catch(function (error) {
  71031. if (_this._errorCallback) {
  71032. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  71033. }
  71034. });
  71035. }
  71036. else {
  71037. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  71038. }
  71039. };
  71040. FilesInput.FilesToLoad = {};
  71041. return FilesInput;
  71042. }());
  71043. BABYLON.FilesInput = FilesInput;
  71044. })(BABYLON || (BABYLON = {}));
  71045. //# sourceMappingURL=babylon.filesInput.js.map
  71046. var BABYLON;
  71047. (function (BABYLON) {
  71048. var Tags = /** @class */ (function () {
  71049. function Tags() {
  71050. }
  71051. Tags.EnableFor = function (obj) {
  71052. obj._tags = obj._tags || {};
  71053. obj.hasTags = function () {
  71054. return Tags.HasTags(obj);
  71055. };
  71056. obj.addTags = function (tagsString) {
  71057. return Tags.AddTagsTo(obj, tagsString);
  71058. };
  71059. obj.removeTags = function (tagsString) {
  71060. return Tags.RemoveTagsFrom(obj, tagsString);
  71061. };
  71062. obj.matchesTagsQuery = function (tagsQuery) {
  71063. return Tags.MatchesQuery(obj, tagsQuery);
  71064. };
  71065. };
  71066. Tags.DisableFor = function (obj) {
  71067. delete obj._tags;
  71068. delete obj.hasTags;
  71069. delete obj.addTags;
  71070. delete obj.removeTags;
  71071. delete obj.matchesTagsQuery;
  71072. };
  71073. Tags.HasTags = function (obj) {
  71074. if (!obj._tags) {
  71075. return false;
  71076. }
  71077. return !BABYLON.Tools.IsEmpty(obj._tags);
  71078. };
  71079. Tags.GetTags = function (obj, asString) {
  71080. if (asString === void 0) { asString = true; }
  71081. if (!obj._tags) {
  71082. return null;
  71083. }
  71084. if (asString) {
  71085. var tagsArray = [];
  71086. for (var tag in obj._tags) {
  71087. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  71088. tagsArray.push(tag);
  71089. }
  71090. }
  71091. return tagsArray.join(" ");
  71092. }
  71093. else {
  71094. return obj._tags;
  71095. }
  71096. };
  71097. // the tags 'true' and 'false' are reserved and cannot be used as tags
  71098. // a tag cannot start with '||', '&&', and '!'
  71099. // it cannot contain whitespaces
  71100. Tags.AddTagsTo = function (obj, tagsString) {
  71101. if (!tagsString) {
  71102. return;
  71103. }
  71104. if (typeof tagsString !== "string") {
  71105. return;
  71106. }
  71107. var tags = tagsString.split(" ");
  71108. tags.forEach(function (tag, index, array) {
  71109. Tags._AddTagTo(obj, tag);
  71110. });
  71111. };
  71112. Tags._AddTagTo = function (obj, tag) {
  71113. tag = tag.trim();
  71114. if (tag === "" || tag === "true" || tag === "false") {
  71115. return;
  71116. }
  71117. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  71118. return;
  71119. }
  71120. Tags.EnableFor(obj);
  71121. obj._tags[tag] = true;
  71122. };
  71123. Tags.RemoveTagsFrom = function (obj, tagsString) {
  71124. if (!Tags.HasTags(obj)) {
  71125. return;
  71126. }
  71127. var tags = tagsString.split(" ");
  71128. for (var t in tags) {
  71129. Tags._RemoveTagFrom(obj, tags[t]);
  71130. }
  71131. };
  71132. Tags._RemoveTagFrom = function (obj, tag) {
  71133. delete obj._tags[tag];
  71134. };
  71135. Tags.MatchesQuery = function (obj, tagsQuery) {
  71136. if (tagsQuery === undefined) {
  71137. return true;
  71138. }
  71139. if (tagsQuery === "") {
  71140. return Tags.HasTags(obj);
  71141. }
  71142. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  71143. };
  71144. return Tags;
  71145. }());
  71146. BABYLON.Tags = Tags;
  71147. })(BABYLON || (BABYLON = {}));
  71148. //# sourceMappingURL=babylon.tags.js.map
  71149. var BABYLON;
  71150. (function (BABYLON) {
  71151. /**
  71152. * Class used to evalaute queries containing `and` and `or` operators
  71153. */
  71154. var AndOrNotEvaluator = /** @class */ (function () {
  71155. function AndOrNotEvaluator() {
  71156. }
  71157. /**
  71158. * Evaluate a query
  71159. * @param query defines the query to evaluate
  71160. * @param evaluateCallback defines the callback used to filter result
  71161. * @returns true if the query matches
  71162. */
  71163. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  71164. if (!query.match(/\([^\(\)]*\)/g)) {
  71165. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  71166. }
  71167. else {
  71168. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  71169. // remove parenthesis
  71170. r = r.slice(1, r.length - 1);
  71171. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  71172. });
  71173. }
  71174. if (query === "true") {
  71175. return true;
  71176. }
  71177. if (query === "false") {
  71178. return false;
  71179. }
  71180. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  71181. };
  71182. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  71183. evaluateCallback = evaluateCallback || (function (r) {
  71184. return r === "true" ? true : false;
  71185. });
  71186. var result;
  71187. var or = parenthesisContent.split("||");
  71188. for (var i in or) {
  71189. if (or.hasOwnProperty(i)) {
  71190. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  71191. var and = ori.split("&&");
  71192. if (and.length > 1) {
  71193. for (var j = 0; j < and.length; ++j) {
  71194. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  71195. if (andj !== "true" && andj !== "false") {
  71196. if (andj[0] === "!") {
  71197. result = !evaluateCallback(andj.substring(1));
  71198. }
  71199. else {
  71200. result = evaluateCallback(andj);
  71201. }
  71202. }
  71203. else {
  71204. result = andj === "true" ? true : false;
  71205. }
  71206. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  71207. ori = "false";
  71208. break;
  71209. }
  71210. }
  71211. }
  71212. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  71213. result = true;
  71214. break;
  71215. }
  71216. // result equals false (or undefined)
  71217. if (ori !== "true" && ori !== "false") {
  71218. if (ori[0] === "!") {
  71219. result = !evaluateCallback(ori.substring(1));
  71220. }
  71221. else {
  71222. result = evaluateCallback(ori);
  71223. }
  71224. }
  71225. else {
  71226. result = ori === "true" ? true : false;
  71227. }
  71228. }
  71229. }
  71230. // the whole parenthesis scope is replaced by 'true' or 'false'
  71231. return result ? "true" : "false";
  71232. };
  71233. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  71234. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  71235. // remove whitespaces
  71236. r = r.replace(/[\s]/g, function () { return ""; });
  71237. return r.length % 2 ? "!" : "";
  71238. });
  71239. booleanString = booleanString.trim();
  71240. if (booleanString === "!true") {
  71241. booleanString = "false";
  71242. }
  71243. else if (booleanString === "!false") {
  71244. booleanString = "true";
  71245. }
  71246. return booleanString;
  71247. };
  71248. return AndOrNotEvaluator;
  71249. }());
  71250. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  71251. })(BABYLON || (BABYLON = {}));
  71252. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  71253. var BABYLON;
  71254. (function (BABYLON) {
  71255. /**
  71256. * Class used to enable access to IndexedDB
  71257. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  71258. */
  71259. var Database = /** @class */ (function () {
  71260. /**
  71261. * Creates a new Database
  71262. * @param urlToScene defines the url to load the scene
  71263. * @param callbackManifestChecked defines the callback to use when manifest is checked
  71264. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  71265. */
  71266. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  71267. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  71268. var _this = this;
  71269. // Handling various flavors of prefixed version of IndexedDB
  71270. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  71271. this.callbackManifestChecked = callbackManifestChecked;
  71272. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  71273. this.db = null;
  71274. this._enableSceneOffline = false;
  71275. this._enableTexturesOffline = false;
  71276. this.manifestVersionFound = 0;
  71277. this.mustUpdateRessources = false;
  71278. this.hasReachedQuota = false;
  71279. if (!Database.IDBStorageEnabled) {
  71280. this.callbackManifestChecked(true);
  71281. }
  71282. else {
  71283. if (disableManifestCheck) {
  71284. this._enableSceneOffline = true;
  71285. this._enableTexturesOffline = true;
  71286. this.manifestVersionFound = 1;
  71287. BABYLON.Tools.SetImmediate(function () {
  71288. _this.callbackManifestChecked(true);
  71289. });
  71290. }
  71291. else {
  71292. this._checkManifestFile();
  71293. }
  71294. }
  71295. }
  71296. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  71297. /**
  71298. * Gets a boolean indicating if scene must be saved in the database
  71299. */
  71300. get: function () {
  71301. return this._enableSceneOffline;
  71302. },
  71303. enumerable: true,
  71304. configurable: true
  71305. });
  71306. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  71307. /**
  71308. * Gets a boolean indicating if textures must be saved in the database
  71309. */
  71310. get: function () {
  71311. return this._enableTexturesOffline;
  71312. },
  71313. enumerable: true,
  71314. configurable: true
  71315. });
  71316. Database.prototype._checkManifestFile = function () {
  71317. var _this = this;
  71318. var noManifestFile = function () {
  71319. _this._enableSceneOffline = false;
  71320. _this._enableTexturesOffline = false;
  71321. _this.callbackManifestChecked(false);
  71322. };
  71323. var timeStampUsed = false;
  71324. var manifestURL = this.currentSceneUrl + ".manifest";
  71325. var xhr = new XMLHttpRequest();
  71326. if (navigator.onLine) {
  71327. // Adding a timestamp to by-pass browsers' cache
  71328. timeStampUsed = true;
  71329. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  71330. }
  71331. xhr.open("GET", manifestURL, true);
  71332. xhr.addEventListener("load", function () {
  71333. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  71334. try {
  71335. var manifestFile = JSON.parse(xhr.response);
  71336. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  71337. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  71338. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  71339. _this.manifestVersionFound = manifestFile.version;
  71340. }
  71341. if (_this.callbackManifestChecked) {
  71342. _this.callbackManifestChecked(true);
  71343. }
  71344. }
  71345. catch (ex) {
  71346. noManifestFile();
  71347. }
  71348. }
  71349. else {
  71350. noManifestFile();
  71351. }
  71352. }, false);
  71353. xhr.addEventListener("error", function (event) {
  71354. if (timeStampUsed) {
  71355. timeStampUsed = false;
  71356. // Let's retry without the timeStamp
  71357. // It could fail when coupled with HTML5 Offline API
  71358. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  71359. xhr.open("GET", retryManifestURL, true);
  71360. xhr.send();
  71361. }
  71362. else {
  71363. noManifestFile();
  71364. }
  71365. }, false);
  71366. try {
  71367. xhr.send();
  71368. }
  71369. catch (ex) {
  71370. BABYLON.Tools.Error("Error on XHR send request.");
  71371. this.callbackManifestChecked(false);
  71372. }
  71373. };
  71374. /**
  71375. * Open the database and make it available
  71376. * @param successCallback defines the callback to call on success
  71377. * @param errorCallback defines the callback to call on error
  71378. */
  71379. Database.prototype.openAsync = function (successCallback, errorCallback) {
  71380. var _this = this;
  71381. var handleError = function () {
  71382. _this.isSupported = false;
  71383. if (errorCallback)
  71384. errorCallback();
  71385. };
  71386. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  71387. // Your browser doesn't support IndexedDB
  71388. this.isSupported = false;
  71389. if (errorCallback)
  71390. errorCallback();
  71391. }
  71392. else {
  71393. // If the DB hasn't been opened or created yet
  71394. if (!this.db) {
  71395. this.hasReachedQuota = false;
  71396. this.isSupported = true;
  71397. var request = this.idbFactory.open("babylonjs", 1);
  71398. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  71399. request.onerror = function (event) {
  71400. handleError();
  71401. };
  71402. // executes when a version change transaction cannot complete due to other active transactions
  71403. request.onblocked = function (event) {
  71404. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  71405. handleError();
  71406. };
  71407. // DB has been opened successfully
  71408. request.onsuccess = function (event) {
  71409. _this.db = request.result;
  71410. successCallback();
  71411. };
  71412. // Initialization of the DB. Creating Scenes & Textures stores
  71413. request.onupgradeneeded = function (event) {
  71414. _this.db = (event.target).result;
  71415. if (_this.db) {
  71416. try {
  71417. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  71418. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  71419. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  71420. }
  71421. catch (ex) {
  71422. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  71423. handleError();
  71424. }
  71425. }
  71426. };
  71427. }
  71428. // DB has already been created and opened
  71429. else {
  71430. if (successCallback)
  71431. successCallback();
  71432. }
  71433. }
  71434. };
  71435. /**
  71436. * Loads an image from the database
  71437. * @param url defines the url to load from
  71438. * @param image defines the target DOM image
  71439. */
  71440. Database.prototype.loadImageFromDB = function (url, image) {
  71441. var _this = this;
  71442. var completeURL = Database._ReturnFullUrlLocation(url);
  71443. var saveAndLoadImage = function () {
  71444. if (!_this.hasReachedQuota && _this.db !== null) {
  71445. // the texture is not yet in the DB, let's try to save it
  71446. _this._saveImageIntoDBAsync(completeURL, image);
  71447. }
  71448. // If the texture is not in the DB and we've reached the DB quota limit
  71449. // let's load it directly from the web
  71450. else {
  71451. image.src = url;
  71452. }
  71453. };
  71454. if (!this.mustUpdateRessources) {
  71455. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  71456. }
  71457. // First time we're download the images or update requested in the manifest file by a version change
  71458. else {
  71459. saveAndLoadImage();
  71460. }
  71461. };
  71462. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  71463. if (this.isSupported && this.db !== null) {
  71464. var texture;
  71465. var transaction = this.db.transaction(["textures"]);
  71466. transaction.onabort = function (event) {
  71467. image.src = url;
  71468. };
  71469. transaction.oncomplete = function (event) {
  71470. var blobTextureURL;
  71471. if (texture) {
  71472. var URL = window.URL || window.webkitURL;
  71473. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  71474. image.onerror = function () {
  71475. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  71476. image.src = url;
  71477. };
  71478. image.src = blobTextureURL;
  71479. }
  71480. else {
  71481. notInDBCallback();
  71482. }
  71483. };
  71484. var getRequest = transaction.objectStore("textures").get(url);
  71485. getRequest.onsuccess = function (event) {
  71486. texture = (event.target).result;
  71487. };
  71488. getRequest.onerror = function (event) {
  71489. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  71490. image.src = url;
  71491. };
  71492. }
  71493. else {
  71494. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71495. image.src = url;
  71496. }
  71497. };
  71498. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  71499. var _this = this;
  71500. if (this.isSupported) {
  71501. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  71502. var generateBlobUrl = function () {
  71503. var blobTextureURL;
  71504. if (blob) {
  71505. var URL = window.URL || window.webkitURL;
  71506. try {
  71507. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  71508. }
  71509. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  71510. catch (ex) {
  71511. blobTextureURL = URL.createObjectURL(blob);
  71512. }
  71513. }
  71514. if (blobTextureURL) {
  71515. image.src = blobTextureURL;
  71516. }
  71517. };
  71518. if (Database.IsUASupportingBlobStorage) { // Create XHR
  71519. var xhr = new XMLHttpRequest(), blob;
  71520. xhr.open("GET", url, true);
  71521. xhr.responseType = "blob";
  71522. xhr.addEventListener("load", function () {
  71523. if (xhr.status === 200 && _this.db) {
  71524. // Blob as response (XHR2)
  71525. blob = xhr.response;
  71526. var transaction = _this.db.transaction(["textures"], "readwrite");
  71527. // the transaction could abort because of a QuotaExceededError error
  71528. transaction.onabort = function (event) {
  71529. try {
  71530. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71531. var srcElement = (event.srcElement || event.target);
  71532. var error = srcElement.error;
  71533. if (error && error.name === "QuotaExceededError") {
  71534. _this.hasReachedQuota = true;
  71535. }
  71536. }
  71537. catch (ex) { }
  71538. generateBlobUrl();
  71539. };
  71540. transaction.oncomplete = function (event) {
  71541. generateBlobUrl();
  71542. };
  71543. var newTexture = { textureUrl: url, data: blob };
  71544. try {
  71545. // Put the blob into the dabase
  71546. var addRequest = transaction.objectStore("textures").put(newTexture);
  71547. addRequest.onsuccess = function (event) {
  71548. };
  71549. addRequest.onerror = function (event) {
  71550. generateBlobUrl();
  71551. };
  71552. }
  71553. catch (ex) {
  71554. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  71555. if (ex.code === 25) {
  71556. Database.IsUASupportingBlobStorage = false;
  71557. }
  71558. image.src = url;
  71559. }
  71560. }
  71561. else {
  71562. image.src = url;
  71563. }
  71564. }, false);
  71565. xhr.addEventListener("error", function (event) {
  71566. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  71567. image.src = url;
  71568. }, false);
  71569. xhr.send();
  71570. }
  71571. else {
  71572. image.src = url;
  71573. }
  71574. }
  71575. else {
  71576. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71577. image.src = url;
  71578. }
  71579. };
  71580. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  71581. var _this = this;
  71582. var updateVersion = function () {
  71583. // the version is not yet in the DB or we need to update it
  71584. _this._saveVersionIntoDBAsync(url, versionLoaded);
  71585. };
  71586. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  71587. };
  71588. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  71589. var _this = this;
  71590. if (this.isSupported && this.db) {
  71591. var version;
  71592. try {
  71593. var transaction = this.db.transaction(["versions"]);
  71594. transaction.oncomplete = function (event) {
  71595. if (version) {
  71596. // If the version in the JSON file is different from the version in DB
  71597. if (_this.manifestVersionFound !== version.data) {
  71598. _this.mustUpdateRessources = true;
  71599. updateInDBCallback();
  71600. }
  71601. else {
  71602. callback(version.data);
  71603. }
  71604. }
  71605. // version was not found in DB
  71606. else {
  71607. _this.mustUpdateRessources = true;
  71608. updateInDBCallback();
  71609. }
  71610. };
  71611. transaction.onabort = function (event) {
  71612. callback(-1);
  71613. };
  71614. var getRequest = transaction.objectStore("versions").get(url);
  71615. getRequest.onsuccess = function (event) {
  71616. version = (event.target).result;
  71617. };
  71618. getRequest.onerror = function (event) {
  71619. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  71620. callback(-1);
  71621. };
  71622. }
  71623. catch (ex) {
  71624. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  71625. callback(-1);
  71626. }
  71627. }
  71628. else {
  71629. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71630. callback(-1);
  71631. }
  71632. };
  71633. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  71634. var _this = this;
  71635. if (this.isSupported && !this.hasReachedQuota && this.db) {
  71636. try {
  71637. // Open a transaction to the database
  71638. var transaction = this.db.transaction(["versions"], "readwrite");
  71639. // the transaction could abort because of a QuotaExceededError error
  71640. transaction.onabort = function (event) {
  71641. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71642. var error = event.srcElement['error'];
  71643. if (error && error.name === "QuotaExceededError") {
  71644. _this.hasReachedQuota = true;
  71645. }
  71646. }
  71647. catch (ex) { }
  71648. callback(-1);
  71649. };
  71650. transaction.oncomplete = function (event) {
  71651. callback(_this.manifestVersionFound);
  71652. };
  71653. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  71654. // Put the scene into the database
  71655. var addRequest = transaction.objectStore("versions").put(newVersion);
  71656. addRequest.onsuccess = function (event) {
  71657. };
  71658. addRequest.onerror = function (event) {
  71659. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  71660. };
  71661. }
  71662. catch (ex) {
  71663. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  71664. callback(-1);
  71665. }
  71666. }
  71667. else {
  71668. callback(-1);
  71669. }
  71670. };
  71671. /**
  71672. * Loads a file from database
  71673. * @param url defines the URL to load from
  71674. * @param sceneLoaded defines a callback to call on success
  71675. * @param progressCallBack defines a callback to call when progress changed
  71676. * @param errorCallback defines a callback to call on error
  71677. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  71678. */
  71679. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  71680. var _this = this;
  71681. var completeUrl = Database._ReturnFullUrlLocation(url);
  71682. var saveAndLoadFile = function () {
  71683. // the scene is not yet in the DB, let's try to save it
  71684. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  71685. };
  71686. this._checkVersionFromDB(completeUrl, function (version) {
  71687. if (version !== -1) {
  71688. if (!_this.mustUpdateRessources) {
  71689. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  71690. }
  71691. else {
  71692. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  71693. }
  71694. }
  71695. else {
  71696. if (errorCallback) {
  71697. errorCallback();
  71698. }
  71699. }
  71700. });
  71701. };
  71702. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  71703. if (this.isSupported && this.db) {
  71704. var targetStore;
  71705. if (url.indexOf(".babylon") !== -1) {
  71706. targetStore = "scenes";
  71707. }
  71708. else {
  71709. targetStore = "textures";
  71710. }
  71711. var file;
  71712. var transaction = this.db.transaction([targetStore]);
  71713. transaction.oncomplete = function (event) {
  71714. if (file) {
  71715. callback(file.data);
  71716. }
  71717. // file was not found in DB
  71718. else {
  71719. notInDBCallback();
  71720. }
  71721. };
  71722. transaction.onabort = function (event) {
  71723. notInDBCallback();
  71724. };
  71725. var getRequest = transaction.objectStore(targetStore).get(url);
  71726. getRequest.onsuccess = function (event) {
  71727. file = (event.target).result;
  71728. };
  71729. getRequest.onerror = function (event) {
  71730. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  71731. notInDBCallback();
  71732. };
  71733. }
  71734. else {
  71735. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71736. callback();
  71737. }
  71738. };
  71739. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  71740. var _this = this;
  71741. if (this.isSupported) {
  71742. var targetStore;
  71743. if (url.indexOf(".babylon") !== -1) {
  71744. targetStore = "scenes";
  71745. }
  71746. else {
  71747. targetStore = "textures";
  71748. }
  71749. // Create XHR
  71750. var xhr = new XMLHttpRequest();
  71751. var fileData;
  71752. xhr.open("GET", url + "?" + Date.now(), true);
  71753. if (useArrayBuffer) {
  71754. xhr.responseType = "arraybuffer";
  71755. }
  71756. if (progressCallback) {
  71757. xhr.onprogress = progressCallback;
  71758. }
  71759. xhr.addEventListener("load", function () {
  71760. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  71761. // Blob as response (XHR2)
  71762. //fileData = xhr.responseText;
  71763. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  71764. if (!_this.hasReachedQuota && _this.db) {
  71765. // Open a transaction to the database
  71766. var transaction = _this.db.transaction([targetStore], "readwrite");
  71767. // the transaction could abort because of a QuotaExceededError error
  71768. transaction.onabort = function (event) {
  71769. try {
  71770. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71771. var error = event.srcElement['error'];
  71772. if (error && error.name === "QuotaExceededError") {
  71773. _this.hasReachedQuota = true;
  71774. }
  71775. }
  71776. catch (ex) { }
  71777. callback(fileData);
  71778. };
  71779. transaction.oncomplete = function (event) {
  71780. callback(fileData);
  71781. };
  71782. var newFile;
  71783. if (targetStore === "scenes") {
  71784. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  71785. }
  71786. else {
  71787. newFile = { textureUrl: url, data: fileData };
  71788. }
  71789. try {
  71790. // Put the scene into the database
  71791. var addRequest = transaction.objectStore(targetStore).put(newFile);
  71792. addRequest.onsuccess = function (event) {
  71793. };
  71794. addRequest.onerror = function (event) {
  71795. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  71796. };
  71797. }
  71798. catch (ex) {
  71799. callback(fileData);
  71800. }
  71801. }
  71802. else {
  71803. callback(fileData);
  71804. }
  71805. }
  71806. else {
  71807. if (xhr.status >= 400 && errorCallback) {
  71808. errorCallback(xhr);
  71809. }
  71810. else {
  71811. callback();
  71812. }
  71813. }
  71814. }, false);
  71815. xhr.addEventListener("error", function (event) {
  71816. BABYLON.Tools.Error("error on XHR request.");
  71817. callback();
  71818. }, false);
  71819. xhr.send();
  71820. }
  71821. else {
  71822. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71823. callback();
  71824. }
  71825. };
  71826. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  71827. Database.IsUASupportingBlobStorage = true;
  71828. /** Gets a boolean indicating if Database storate is enabled */
  71829. Database.IDBStorageEnabled = true;
  71830. Database._ParseURL = function (url) {
  71831. var a = document.createElement('a');
  71832. a.href = url;
  71833. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  71834. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  71835. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  71836. return absLocation;
  71837. };
  71838. Database._ReturnFullUrlLocation = function (url) {
  71839. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  71840. return (Database._ParseURL(window.location.href) + url);
  71841. }
  71842. else {
  71843. return url;
  71844. }
  71845. };
  71846. return Database;
  71847. }());
  71848. BABYLON.Database = Database;
  71849. })(BABYLON || (BABYLON = {}));
  71850. //# sourceMappingURL=babylon.database.js.map
  71851. var BABYLON;
  71852. (function (BABYLON) {
  71853. var FresnelParameters = /** @class */ (function () {
  71854. function FresnelParameters() {
  71855. this._isEnabled = true;
  71856. this.leftColor = BABYLON.Color3.White();
  71857. this.rightColor = BABYLON.Color3.Black();
  71858. this.bias = 0;
  71859. this.power = 1;
  71860. }
  71861. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  71862. get: function () {
  71863. return this._isEnabled;
  71864. },
  71865. set: function (value) {
  71866. if (this._isEnabled === value) {
  71867. return;
  71868. }
  71869. this._isEnabled = value;
  71870. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  71871. },
  71872. enumerable: true,
  71873. configurable: true
  71874. });
  71875. FresnelParameters.prototype.clone = function () {
  71876. var newFresnelParameters = new FresnelParameters();
  71877. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  71878. return newFresnelParameters;
  71879. };
  71880. FresnelParameters.prototype.serialize = function () {
  71881. var serializationObject = {};
  71882. serializationObject.isEnabled = this.isEnabled;
  71883. serializationObject.leftColor = this.leftColor.asArray();
  71884. serializationObject.rightColor = this.rightColor.asArray();
  71885. serializationObject.bias = this.bias;
  71886. serializationObject.power = this.power;
  71887. return serializationObject;
  71888. };
  71889. FresnelParameters.Parse = function (parsedFresnelParameters) {
  71890. var fresnelParameters = new FresnelParameters();
  71891. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  71892. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  71893. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  71894. fresnelParameters.bias = parsedFresnelParameters.bias;
  71895. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  71896. return fresnelParameters;
  71897. };
  71898. return FresnelParameters;
  71899. }());
  71900. BABYLON.FresnelParameters = FresnelParameters;
  71901. })(BABYLON || (BABYLON = {}));
  71902. //# sourceMappingURL=babylon.fresnelParameters.js.map
  71903. var BABYLON;
  71904. (function (BABYLON) {
  71905. var MultiMaterial = /** @class */ (function (_super) {
  71906. __extends(MultiMaterial, _super);
  71907. function MultiMaterial(name, scene) {
  71908. var _this = _super.call(this, name, scene, true) || this;
  71909. scene.multiMaterials.push(_this);
  71910. _this.subMaterials = new Array();
  71911. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  71912. return _this;
  71913. }
  71914. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  71915. get: function () {
  71916. return this._subMaterials;
  71917. },
  71918. set: function (value) {
  71919. this._subMaterials = value;
  71920. this._hookArray(value);
  71921. },
  71922. enumerable: true,
  71923. configurable: true
  71924. });
  71925. MultiMaterial.prototype._hookArray = function (array) {
  71926. var _this = this;
  71927. var oldPush = array.push;
  71928. array.push = function () {
  71929. var items = [];
  71930. for (var _i = 0; _i < arguments.length; _i++) {
  71931. items[_i] = arguments[_i];
  71932. }
  71933. var result = oldPush.apply(array, items);
  71934. _this._markAllSubMeshesAsTexturesDirty();
  71935. return result;
  71936. };
  71937. var oldSplice = array.splice;
  71938. array.splice = function (index, deleteCount) {
  71939. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71940. _this._markAllSubMeshesAsTexturesDirty();
  71941. return deleted;
  71942. };
  71943. };
  71944. // Properties
  71945. MultiMaterial.prototype.getSubMaterial = function (index) {
  71946. if (index < 0 || index >= this.subMaterials.length) {
  71947. return this.getScene().defaultMaterial;
  71948. }
  71949. return this.subMaterials[index];
  71950. };
  71951. MultiMaterial.prototype.getActiveTextures = function () {
  71952. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  71953. if (subMaterial) {
  71954. return subMaterial.getActiveTextures();
  71955. }
  71956. else {
  71957. return [];
  71958. }
  71959. }));
  71960. var _a;
  71961. };
  71962. // Methods
  71963. MultiMaterial.prototype.getClassName = function () {
  71964. return "MultiMaterial";
  71965. };
  71966. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  71967. for (var index = 0; index < this.subMaterials.length; index++) {
  71968. var subMaterial = this.subMaterials[index];
  71969. if (subMaterial) {
  71970. if (subMaterial.storeEffectOnSubMeshes) {
  71971. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  71972. return false;
  71973. }
  71974. continue;
  71975. }
  71976. if (!subMaterial.isReady(mesh)) {
  71977. return false;
  71978. }
  71979. }
  71980. }
  71981. return true;
  71982. };
  71983. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  71984. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  71985. for (var index = 0; index < this.subMaterials.length; index++) {
  71986. var subMaterial = null;
  71987. var current = this.subMaterials[index];
  71988. if (cloneChildren && current) {
  71989. subMaterial = current.clone(name + "-" + current.name);
  71990. }
  71991. else {
  71992. subMaterial = this.subMaterials[index];
  71993. }
  71994. newMultiMaterial.subMaterials.push(subMaterial);
  71995. }
  71996. return newMultiMaterial;
  71997. };
  71998. MultiMaterial.prototype.serialize = function () {
  71999. var serializationObject = {};
  72000. serializationObject.name = this.name;
  72001. serializationObject.id = this.id;
  72002. if (BABYLON.Tags) {
  72003. serializationObject.tags = BABYLON.Tags.GetTags(this);
  72004. }
  72005. serializationObject.materials = [];
  72006. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  72007. var subMat = this.subMaterials[matIndex];
  72008. if (subMat) {
  72009. serializationObject.materials.push(subMat.id);
  72010. }
  72011. else {
  72012. serializationObject.materials.push(null);
  72013. }
  72014. }
  72015. return serializationObject;
  72016. };
  72017. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  72018. var scene = this.getScene();
  72019. if (!scene) {
  72020. return;
  72021. }
  72022. var index = scene.multiMaterials.indexOf(this);
  72023. if (index >= 0) {
  72024. scene.multiMaterials.splice(index, 1);
  72025. }
  72026. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  72027. };
  72028. return MultiMaterial;
  72029. }(BABYLON.Material));
  72030. BABYLON.MultiMaterial = MultiMaterial;
  72031. })(BABYLON || (BABYLON = {}));
  72032. //# sourceMappingURL=babylon.multiMaterial.js.map
  72033. var BABYLON;
  72034. (function (BABYLON) {
  72035. var FreeCameraTouchInput = /** @class */ (function () {
  72036. function FreeCameraTouchInput() {
  72037. this._offsetX = null;
  72038. this._offsetY = null;
  72039. this._pointerPressed = new Array();
  72040. this.touchAngularSensibility = 200000.0;
  72041. this.touchMoveSensibility = 250.0;
  72042. }
  72043. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  72044. var _this = this;
  72045. var previousPosition = null;
  72046. if (this._pointerInput === undefined) {
  72047. this._onLostFocus = function (evt) {
  72048. _this._offsetX = null;
  72049. _this._offsetY = null;
  72050. };
  72051. this._pointerInput = function (p, s) {
  72052. var evt = p.event;
  72053. if (evt.pointerType === "mouse") {
  72054. return;
  72055. }
  72056. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72057. if (!noPreventDefault) {
  72058. evt.preventDefault();
  72059. }
  72060. _this._pointerPressed.push(evt.pointerId);
  72061. if (_this._pointerPressed.length !== 1) {
  72062. return;
  72063. }
  72064. previousPosition = {
  72065. x: evt.clientX,
  72066. y: evt.clientY
  72067. };
  72068. }
  72069. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  72070. if (!noPreventDefault) {
  72071. evt.preventDefault();
  72072. }
  72073. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72074. if (index === -1) {
  72075. return;
  72076. }
  72077. _this._pointerPressed.splice(index, 1);
  72078. if (index != 0) {
  72079. return;
  72080. }
  72081. previousPosition = null;
  72082. _this._offsetX = null;
  72083. _this._offsetY = null;
  72084. }
  72085. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  72086. if (!noPreventDefault) {
  72087. evt.preventDefault();
  72088. }
  72089. if (!previousPosition) {
  72090. return;
  72091. }
  72092. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72093. if (index != 0) {
  72094. return;
  72095. }
  72096. _this._offsetX = evt.clientX - previousPosition.x;
  72097. _this._offsetY = -(evt.clientY - previousPosition.y);
  72098. }
  72099. };
  72100. }
  72101. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  72102. if (this._onLostFocus) {
  72103. element.addEventListener("blur", this._onLostFocus);
  72104. }
  72105. };
  72106. FreeCameraTouchInput.prototype.detachControl = function (element) {
  72107. if (this._pointerInput && element) {
  72108. if (this._observer) {
  72109. this.camera.getScene().onPointerObservable.remove(this._observer);
  72110. this._observer = null;
  72111. }
  72112. if (this._onLostFocus) {
  72113. element.removeEventListener("blur", this._onLostFocus);
  72114. this._onLostFocus = null;
  72115. }
  72116. this._pointerPressed = [];
  72117. this._offsetX = null;
  72118. this._offsetY = null;
  72119. }
  72120. };
  72121. FreeCameraTouchInput.prototype.checkInputs = function () {
  72122. if (this._offsetX && this._offsetY) {
  72123. var camera = this.camera;
  72124. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  72125. if (this._pointerPressed.length > 1) {
  72126. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  72127. }
  72128. else {
  72129. var speed = camera._computeLocalCameraSpeed();
  72130. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  72131. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  72132. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  72133. }
  72134. }
  72135. };
  72136. FreeCameraTouchInput.prototype.getClassName = function () {
  72137. return "FreeCameraTouchInput";
  72138. };
  72139. FreeCameraTouchInput.prototype.getSimpleName = function () {
  72140. return "touch";
  72141. };
  72142. __decorate([
  72143. BABYLON.serialize()
  72144. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  72145. __decorate([
  72146. BABYLON.serialize()
  72147. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  72148. return FreeCameraTouchInput;
  72149. }());
  72150. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  72151. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  72152. })(BABYLON || (BABYLON = {}));
  72153. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  72154. var BABYLON;
  72155. (function (BABYLON) {
  72156. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  72157. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  72158. });
  72159. // We're mainly based on the logic defined into the FreeCamera code
  72160. var TouchCamera = /** @class */ (function (_super) {
  72161. __extends(TouchCamera, _super);
  72162. //-- end properties for backward compatibility for inputs
  72163. function TouchCamera(name, position, scene) {
  72164. var _this = _super.call(this, name, position, scene) || this;
  72165. _this.inputs.addTouch();
  72166. _this._setupInputs();
  72167. return _this;
  72168. }
  72169. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  72170. //-- Begin properties for backward compatibility for inputs
  72171. get: function () {
  72172. var touch = this.inputs.attached["touch"];
  72173. if (touch)
  72174. return touch.touchAngularSensibility;
  72175. return 0;
  72176. },
  72177. set: function (value) {
  72178. var touch = this.inputs.attached["touch"];
  72179. if (touch)
  72180. touch.touchAngularSensibility = value;
  72181. },
  72182. enumerable: true,
  72183. configurable: true
  72184. });
  72185. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  72186. get: function () {
  72187. var touch = this.inputs.attached["touch"];
  72188. if (touch)
  72189. return touch.touchMoveSensibility;
  72190. return 0;
  72191. },
  72192. set: function (value) {
  72193. var touch = this.inputs.attached["touch"];
  72194. if (touch)
  72195. touch.touchMoveSensibility = value;
  72196. },
  72197. enumerable: true,
  72198. configurable: true
  72199. });
  72200. TouchCamera.prototype.getClassName = function () {
  72201. return "TouchCamera";
  72202. };
  72203. TouchCamera.prototype._setupInputs = function () {
  72204. var mouse = this.inputs.attached["mouse"];
  72205. if (mouse) {
  72206. mouse.touchEnabled = false;
  72207. }
  72208. };
  72209. return TouchCamera;
  72210. }(BABYLON.FreeCamera));
  72211. BABYLON.TouchCamera = TouchCamera;
  72212. })(BABYLON || (BABYLON = {}));
  72213. //# sourceMappingURL=babylon.touchCamera.js.map
  72214. var BABYLON;
  72215. (function (BABYLON) {
  72216. var ProceduralTexture = /** @class */ (function (_super) {
  72217. __extends(ProceduralTexture, _super);
  72218. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  72219. if (fallbackTexture === void 0) { fallbackTexture = null; }
  72220. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72221. if (isCube === void 0) { isCube = false; }
  72222. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  72223. _this.isCube = isCube;
  72224. _this.isEnabled = true;
  72225. _this._currentRefreshId = -1;
  72226. _this._refreshRate = 1;
  72227. _this._vertexBuffers = {};
  72228. _this._uniforms = new Array();
  72229. _this._samplers = new Array();
  72230. _this._textures = {};
  72231. _this._floats = {};
  72232. _this._ints = {};
  72233. _this._floatsArrays = {};
  72234. _this._colors3 = {};
  72235. _this._colors4 = {};
  72236. _this._vectors2 = {};
  72237. _this._vectors3 = {};
  72238. _this._matrices = {};
  72239. _this._fallbackTextureUsed = false;
  72240. scene = _this.getScene();
  72241. scene.proceduralTextures.push(_this);
  72242. _this._engine = scene.getEngine();
  72243. _this.name = name;
  72244. _this.isRenderTarget = true;
  72245. _this._size = size;
  72246. _this._generateMipMaps = generateMipMaps;
  72247. _this.setFragment(fragment);
  72248. _this._fallbackTexture = fallbackTexture;
  72249. if (isCube) {
  72250. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  72251. _this.setFloat("face", 0);
  72252. }
  72253. else {
  72254. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  72255. }
  72256. // VBO
  72257. var vertices = [];
  72258. vertices.push(1, 1);
  72259. vertices.push(-1, 1);
  72260. vertices.push(-1, -1);
  72261. vertices.push(1, -1);
  72262. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72263. _this._createIndexBuffer();
  72264. return _this;
  72265. }
  72266. ProceduralTexture.prototype._createIndexBuffer = function () {
  72267. var engine = this._engine;
  72268. // Indices
  72269. var indices = [];
  72270. indices.push(0);
  72271. indices.push(1);
  72272. indices.push(2);
  72273. indices.push(0);
  72274. indices.push(2);
  72275. indices.push(3);
  72276. this._indexBuffer = engine.createIndexBuffer(indices);
  72277. };
  72278. ProceduralTexture.prototype._rebuild = function () {
  72279. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72280. if (vb) {
  72281. vb._rebuild();
  72282. }
  72283. this._createIndexBuffer();
  72284. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  72285. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  72286. }
  72287. };
  72288. ProceduralTexture.prototype.reset = function () {
  72289. if (this._effect === undefined) {
  72290. return;
  72291. }
  72292. var engine = this._engine;
  72293. engine._releaseEffect(this._effect);
  72294. };
  72295. ProceduralTexture.prototype.isReady = function () {
  72296. var _this = this;
  72297. var engine = this._engine;
  72298. var shaders;
  72299. if (!this._fragment) {
  72300. return false;
  72301. }
  72302. if (this._fallbackTextureUsed) {
  72303. return true;
  72304. }
  72305. if (this._fragment.fragmentElement !== undefined) {
  72306. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  72307. }
  72308. else {
  72309. shaders = { vertex: "procedural", fragment: this._fragment };
  72310. }
  72311. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  72312. _this.releaseInternalTexture();
  72313. if (_this._fallbackTexture) {
  72314. _this._texture = _this._fallbackTexture._texture;
  72315. if (_this._texture) {
  72316. _this._texture.incrementReferences();
  72317. }
  72318. }
  72319. _this._fallbackTextureUsed = true;
  72320. });
  72321. return this._effect.isReady();
  72322. };
  72323. ProceduralTexture.prototype.resetRefreshCounter = function () {
  72324. this._currentRefreshId = -1;
  72325. };
  72326. ProceduralTexture.prototype.setFragment = function (fragment) {
  72327. this._fragment = fragment;
  72328. };
  72329. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  72330. get: function () {
  72331. return this._refreshRate;
  72332. },
  72333. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  72334. set: function (value) {
  72335. this._refreshRate = value;
  72336. this.resetRefreshCounter();
  72337. },
  72338. enumerable: true,
  72339. configurable: true
  72340. });
  72341. ProceduralTexture.prototype._shouldRender = function () {
  72342. if (!this.isEnabled || !this.isReady() || !this._texture) {
  72343. return false;
  72344. }
  72345. if (this._fallbackTextureUsed) {
  72346. return false;
  72347. }
  72348. if (this._currentRefreshId === -1) { // At least render once
  72349. this._currentRefreshId = 1;
  72350. return true;
  72351. }
  72352. if (this.refreshRate === this._currentRefreshId) {
  72353. this._currentRefreshId = 1;
  72354. return true;
  72355. }
  72356. this._currentRefreshId++;
  72357. return false;
  72358. };
  72359. ProceduralTexture.prototype.getRenderSize = function () {
  72360. return this._size;
  72361. };
  72362. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  72363. if (this._fallbackTextureUsed) {
  72364. return;
  72365. }
  72366. this.releaseInternalTexture();
  72367. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  72368. // Update properties
  72369. this._size = size;
  72370. this._generateMipMaps = generateMipMaps;
  72371. };
  72372. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  72373. if (this._uniforms.indexOf(uniformName) === -1) {
  72374. this._uniforms.push(uniformName);
  72375. }
  72376. };
  72377. ProceduralTexture.prototype.setTexture = function (name, texture) {
  72378. if (this._samplers.indexOf(name) === -1) {
  72379. this._samplers.push(name);
  72380. }
  72381. this._textures[name] = texture;
  72382. return this;
  72383. };
  72384. ProceduralTexture.prototype.setFloat = function (name, value) {
  72385. this._checkUniform(name);
  72386. this._floats[name] = value;
  72387. return this;
  72388. };
  72389. /**
  72390. * Set the value of an uniform to an integer value
  72391. * @param name defines the name of the uniform
  72392. * @param value defines the value to set
  72393. * @returns the current procedural texture
  72394. */
  72395. ProceduralTexture.prototype.setInt = function (name, value) {
  72396. this._checkUniform(name);
  72397. this._ints[name] = value;
  72398. return this;
  72399. };
  72400. ProceduralTexture.prototype.setFloats = function (name, value) {
  72401. this._checkUniform(name);
  72402. this._floatsArrays[name] = value;
  72403. return this;
  72404. };
  72405. ProceduralTexture.prototype.setColor3 = function (name, value) {
  72406. this._checkUniform(name);
  72407. this._colors3[name] = value;
  72408. return this;
  72409. };
  72410. ProceduralTexture.prototype.setColor4 = function (name, value) {
  72411. this._checkUniform(name);
  72412. this._colors4[name] = value;
  72413. return this;
  72414. };
  72415. ProceduralTexture.prototype.setVector2 = function (name, value) {
  72416. this._checkUniform(name);
  72417. this._vectors2[name] = value;
  72418. return this;
  72419. };
  72420. ProceduralTexture.prototype.setVector3 = function (name, value) {
  72421. this._checkUniform(name);
  72422. this._vectors3[name] = value;
  72423. return this;
  72424. };
  72425. ProceduralTexture.prototype.setMatrix = function (name, value) {
  72426. this._checkUniform(name);
  72427. this._matrices[name] = value;
  72428. return this;
  72429. };
  72430. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  72431. var scene = this.getScene();
  72432. if (!scene) {
  72433. return;
  72434. }
  72435. var engine = this._engine;
  72436. // Render
  72437. engine.enableEffect(this._effect);
  72438. engine.setState(false);
  72439. // Texture
  72440. for (var name in this._textures) {
  72441. this._effect.setTexture(name, this._textures[name]);
  72442. }
  72443. // Float
  72444. for (name in this._ints) {
  72445. this._effect.setInt(name, this._ints[name]);
  72446. }
  72447. // Float
  72448. for (name in this._floats) {
  72449. this._effect.setFloat(name, this._floats[name]);
  72450. }
  72451. // Floats
  72452. for (name in this._floatsArrays) {
  72453. this._effect.setArray(name, this._floatsArrays[name]);
  72454. }
  72455. // Color3
  72456. for (name in this._colors3) {
  72457. this._effect.setColor3(name, this._colors3[name]);
  72458. }
  72459. // Color4
  72460. for (name in this._colors4) {
  72461. var color = this._colors4[name];
  72462. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  72463. }
  72464. // Vector2
  72465. for (name in this._vectors2) {
  72466. this._effect.setVector2(name, this._vectors2[name]);
  72467. }
  72468. // Vector3
  72469. for (name in this._vectors3) {
  72470. this._effect.setVector3(name, this._vectors3[name]);
  72471. }
  72472. // Matrix
  72473. for (name in this._matrices) {
  72474. this._effect.setMatrix(name, this._matrices[name]);
  72475. }
  72476. if (!this._texture) {
  72477. return;
  72478. }
  72479. if (this.isCube) {
  72480. for (var face = 0; face < 6; face++) {
  72481. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  72482. // VBOs
  72483. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72484. this._effect.setFloat("face", face);
  72485. // Clear
  72486. engine.clear(scene.clearColor, true, true, true);
  72487. // Draw order
  72488. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72489. // Mipmaps
  72490. if (face === 5) {
  72491. engine.generateMipMapsForCubemap(this._texture);
  72492. }
  72493. }
  72494. }
  72495. else {
  72496. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  72497. // VBOs
  72498. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72499. // Clear
  72500. engine.clear(scene.clearColor, true, true, true);
  72501. // Draw order
  72502. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72503. }
  72504. // Unbind
  72505. engine.unBindFramebuffer(this._texture, this.isCube);
  72506. if (this.onGenerated) {
  72507. this.onGenerated();
  72508. }
  72509. };
  72510. ProceduralTexture.prototype.clone = function () {
  72511. var textureSize = this.getSize();
  72512. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  72513. // Base texture
  72514. newTexture.hasAlpha = this.hasAlpha;
  72515. newTexture.level = this.level;
  72516. // RenderTarget Texture
  72517. newTexture.coordinatesMode = this.coordinatesMode;
  72518. return newTexture;
  72519. };
  72520. ProceduralTexture.prototype.dispose = function () {
  72521. var scene = this.getScene();
  72522. if (!scene) {
  72523. return;
  72524. }
  72525. var index = scene.proceduralTextures.indexOf(this);
  72526. if (index >= 0) {
  72527. scene.proceduralTextures.splice(index, 1);
  72528. }
  72529. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72530. if (vertexBuffer) {
  72531. vertexBuffer.dispose();
  72532. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72533. }
  72534. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  72535. this._indexBuffer = null;
  72536. }
  72537. _super.prototype.dispose.call(this);
  72538. };
  72539. __decorate([
  72540. BABYLON.serialize()
  72541. ], ProceduralTexture.prototype, "_size", void 0);
  72542. __decorate([
  72543. BABYLON.serialize()
  72544. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  72545. __decorate([
  72546. BABYLON.serialize()
  72547. ], ProceduralTexture.prototype, "isEnabled", void 0);
  72548. __decorate([
  72549. BABYLON.serialize()
  72550. ], ProceduralTexture.prototype, "refreshRate", null);
  72551. return ProceduralTexture;
  72552. }(BABYLON.Texture));
  72553. BABYLON.ProceduralTexture = ProceduralTexture;
  72554. })(BABYLON || (BABYLON = {}));
  72555. //# sourceMappingURL=babylon.proceduralTexture.js.map
  72556. var BABYLON;
  72557. (function (BABYLON) {
  72558. var CustomProceduralTexture = /** @class */ (function (_super) {
  72559. __extends(CustomProceduralTexture, _super);
  72560. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  72561. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  72562. _this._animate = true;
  72563. _this._time = 0;
  72564. _this._texturePath = texturePath;
  72565. //Try to load json
  72566. _this.loadJson(texturePath);
  72567. _this.refreshRate = 1;
  72568. return _this;
  72569. }
  72570. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  72571. var _this = this;
  72572. var noConfigFile = function () {
  72573. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  72574. try {
  72575. _this.setFragment(_this._texturePath);
  72576. }
  72577. catch (ex) {
  72578. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  72579. }
  72580. };
  72581. var configFileUrl = jsonUrl + "/config.json";
  72582. var xhr = new XMLHttpRequest();
  72583. xhr.open("GET", configFileUrl, true);
  72584. xhr.addEventListener("load", function () {
  72585. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  72586. try {
  72587. _this._config = JSON.parse(xhr.response);
  72588. _this.updateShaderUniforms();
  72589. _this.updateTextures();
  72590. _this.setFragment(_this._texturePath + "/custom");
  72591. _this._animate = _this._config.animate;
  72592. _this.refreshRate = _this._config.refreshrate;
  72593. }
  72594. catch (ex) {
  72595. noConfigFile();
  72596. }
  72597. }
  72598. else {
  72599. noConfigFile();
  72600. }
  72601. }, false);
  72602. xhr.addEventListener("error", function () {
  72603. noConfigFile();
  72604. }, false);
  72605. try {
  72606. xhr.send();
  72607. }
  72608. catch (ex) {
  72609. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  72610. }
  72611. };
  72612. CustomProceduralTexture.prototype.isReady = function () {
  72613. if (!_super.prototype.isReady.call(this)) {
  72614. return false;
  72615. }
  72616. for (var name in this._textures) {
  72617. var texture = this._textures[name];
  72618. if (!texture.isReady()) {
  72619. return false;
  72620. }
  72621. }
  72622. return true;
  72623. };
  72624. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  72625. var scene = this.getScene();
  72626. if (this._animate && scene) {
  72627. this._time += scene.getAnimationRatio() * 0.03;
  72628. this.updateShaderUniforms();
  72629. }
  72630. _super.prototype.render.call(this, useCameraPostProcess);
  72631. };
  72632. CustomProceduralTexture.prototype.updateTextures = function () {
  72633. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  72634. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  72635. }
  72636. };
  72637. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  72638. if (this._config) {
  72639. for (var j = 0; j < this._config.uniforms.length; j++) {
  72640. var uniform = this._config.uniforms[j];
  72641. switch (uniform.type) {
  72642. case "float":
  72643. this.setFloat(uniform.name, uniform.value);
  72644. break;
  72645. case "color3":
  72646. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  72647. break;
  72648. case "color4":
  72649. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  72650. break;
  72651. case "vector2":
  72652. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  72653. break;
  72654. case "vector3":
  72655. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  72656. break;
  72657. }
  72658. }
  72659. }
  72660. this.setFloat("time", this._time);
  72661. };
  72662. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  72663. get: function () {
  72664. return this._animate;
  72665. },
  72666. set: function (value) {
  72667. this._animate = value;
  72668. },
  72669. enumerable: true,
  72670. configurable: true
  72671. });
  72672. return CustomProceduralTexture;
  72673. }(BABYLON.ProceduralTexture));
  72674. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  72675. })(BABYLON || (BABYLON = {}));
  72676. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  72677. var BABYLON;
  72678. (function (BABYLON) {
  72679. var FreeCameraGamepadInput = /** @class */ (function () {
  72680. function FreeCameraGamepadInput() {
  72681. this.gamepadAngularSensibility = 200;
  72682. this.gamepadMoveSensibility = 40;
  72683. // private members
  72684. this._cameraTransform = BABYLON.Matrix.Identity();
  72685. this._deltaTransform = BABYLON.Vector3.Zero();
  72686. this._vector3 = BABYLON.Vector3.Zero();
  72687. this._vector2 = BABYLON.Vector2.Zero();
  72688. }
  72689. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  72690. var _this = this;
  72691. var manager = this.camera.getScene().gamepadManager;
  72692. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72693. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72694. // prioritize XBOX gamepads.
  72695. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  72696. _this.gamepad = gamepad;
  72697. }
  72698. }
  72699. });
  72700. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72701. if (_this.gamepad === gamepad) {
  72702. _this.gamepad = null;
  72703. }
  72704. });
  72705. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  72706. };
  72707. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  72708. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72709. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72710. this.gamepad = null;
  72711. };
  72712. FreeCameraGamepadInput.prototype.checkInputs = function () {
  72713. if (this.gamepad && this.gamepad.leftStick) {
  72714. var camera = this.camera;
  72715. var LSValues = this.gamepad.leftStick;
  72716. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  72717. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72718. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  72719. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  72720. var RSValues = this.gamepad.rightStick;
  72721. if (RSValues) {
  72722. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  72723. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  72724. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  72725. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  72726. }
  72727. else {
  72728. RSValues = { x: 0, y: 0 };
  72729. }
  72730. if (!camera.rotationQuaternion) {
  72731. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  72732. }
  72733. else {
  72734. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  72735. }
  72736. var speed = camera._computeLocalCameraSpeed() * 50.0;
  72737. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  72738. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  72739. camera.cameraDirection.addInPlace(this._deltaTransform);
  72740. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  72741. camera.cameraRotation.addInPlace(this._vector2);
  72742. }
  72743. };
  72744. FreeCameraGamepadInput.prototype.getClassName = function () {
  72745. return "FreeCameraGamepadInput";
  72746. };
  72747. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  72748. return "gamepad";
  72749. };
  72750. __decorate([
  72751. BABYLON.serialize()
  72752. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  72753. __decorate([
  72754. BABYLON.serialize()
  72755. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72756. return FreeCameraGamepadInput;
  72757. }());
  72758. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  72759. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  72760. })(BABYLON || (BABYLON = {}));
  72761. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  72762. var BABYLON;
  72763. (function (BABYLON) {
  72764. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  72765. function ArcRotateCameraGamepadInput() {
  72766. this.gamepadRotationSensibility = 80;
  72767. this.gamepadMoveSensibility = 40;
  72768. }
  72769. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  72770. var _this = this;
  72771. var manager = this.camera.getScene().gamepadManager;
  72772. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72773. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72774. // prioritize XBOX gamepads.
  72775. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  72776. _this.gamepad = gamepad;
  72777. }
  72778. }
  72779. });
  72780. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72781. if (_this.gamepad === gamepad) {
  72782. _this.gamepad = null;
  72783. }
  72784. });
  72785. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  72786. };
  72787. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  72788. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72789. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72790. this.gamepad = null;
  72791. };
  72792. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  72793. if (this.gamepad) {
  72794. var camera = this.camera;
  72795. var RSValues = this.gamepad.rightStick;
  72796. if (RSValues) {
  72797. if (RSValues.x != 0) {
  72798. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  72799. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  72800. camera.inertialAlphaOffset += normalizedRX;
  72801. }
  72802. }
  72803. if (RSValues.y != 0) {
  72804. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  72805. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  72806. camera.inertialBetaOffset += normalizedRY;
  72807. }
  72808. }
  72809. }
  72810. var LSValues = this.gamepad.leftStick;
  72811. if (LSValues && LSValues.y != 0) {
  72812. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72813. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  72814. this.camera.inertialRadiusOffset -= normalizedLY;
  72815. }
  72816. }
  72817. }
  72818. };
  72819. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  72820. return "ArcRotateCameraGamepadInput";
  72821. };
  72822. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  72823. return "gamepad";
  72824. };
  72825. __decorate([
  72826. BABYLON.serialize()
  72827. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  72828. __decorate([
  72829. BABYLON.serialize()
  72830. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72831. return ArcRotateCameraGamepadInput;
  72832. }());
  72833. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  72834. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  72835. })(BABYLON || (BABYLON = {}));
  72836. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  72837. var BABYLON;
  72838. (function (BABYLON) {
  72839. var GamepadManager = /** @class */ (function () {
  72840. function GamepadManager(_scene) {
  72841. var _this = this;
  72842. this._scene = _scene;
  72843. this._babylonGamepads = [];
  72844. this._oneGamepadConnected = false;
  72845. this._isMonitoring = false;
  72846. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  72847. if (!BABYLON.Tools.IsWindowObjectExist()) {
  72848. this._gamepadEventSupported = false;
  72849. }
  72850. else {
  72851. this._gamepadEventSupported = 'GamepadEvent' in window;
  72852. this._gamepadSupport = (navigator.getGamepads ||
  72853. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  72854. }
  72855. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  72856. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  72857. for (var i in _this._babylonGamepads) {
  72858. var gamepad = _this._babylonGamepads[i];
  72859. if (gamepad && gamepad._isConnected) {
  72860. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  72861. }
  72862. }
  72863. });
  72864. this._onGamepadConnectedEvent = function (evt) {
  72865. var gamepad = evt.gamepad;
  72866. if (gamepad.index in _this._babylonGamepads) {
  72867. if (_this._babylonGamepads[gamepad.index].isConnected) {
  72868. return;
  72869. }
  72870. }
  72871. var newGamepad;
  72872. if (_this._babylonGamepads[gamepad.index]) {
  72873. newGamepad = _this._babylonGamepads[gamepad.index];
  72874. newGamepad.browserGamepad = gamepad;
  72875. newGamepad._isConnected = true;
  72876. }
  72877. else {
  72878. newGamepad = _this._addNewGamepad(gamepad);
  72879. }
  72880. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72881. _this._startMonitoringGamepads();
  72882. };
  72883. this._onGamepadDisconnectedEvent = function (evt) {
  72884. var gamepad = evt.gamepad;
  72885. // Remove the gamepad from the list of gamepads to monitor.
  72886. for (var i in _this._babylonGamepads) {
  72887. if (_this._babylonGamepads[i].index === gamepad.index) {
  72888. var disconnectedGamepad = _this._babylonGamepads[i];
  72889. disconnectedGamepad._isConnected = false;
  72890. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  72891. break;
  72892. }
  72893. }
  72894. };
  72895. if (this._gamepadSupport) {
  72896. //first add already-connected gamepads
  72897. this._updateGamepadObjects();
  72898. if (this._babylonGamepads.length) {
  72899. this._startMonitoringGamepads();
  72900. }
  72901. // Checking if the gamepad connected event is supported (like in Firefox)
  72902. if (this._gamepadEventSupported) {
  72903. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  72904. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  72905. }
  72906. else {
  72907. this._startMonitoringGamepads();
  72908. }
  72909. }
  72910. }
  72911. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  72912. get: function () {
  72913. return this._babylonGamepads;
  72914. },
  72915. enumerable: true,
  72916. configurable: true
  72917. });
  72918. GamepadManager.prototype.getGamepadByType = function (type) {
  72919. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  72920. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  72921. var gamepad = _a[_i];
  72922. if (gamepad && gamepad.type === type) {
  72923. return gamepad;
  72924. }
  72925. }
  72926. return null;
  72927. };
  72928. GamepadManager.prototype.dispose = function () {
  72929. if (this._gamepadEventSupported) {
  72930. if (this._onGamepadConnectedEvent) {
  72931. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  72932. }
  72933. if (this._onGamepadDisconnectedEvent) {
  72934. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  72935. }
  72936. this._onGamepadConnectedEvent = null;
  72937. this._onGamepadDisconnectedEvent = null;
  72938. }
  72939. this._babylonGamepads.forEach(function (gamepad) {
  72940. gamepad.dispose();
  72941. });
  72942. this.onGamepadConnectedObservable.clear();
  72943. this.onGamepadDisconnectedObservable.clear();
  72944. this._oneGamepadConnected = false;
  72945. this._stopMonitoringGamepads();
  72946. this._babylonGamepads = [];
  72947. };
  72948. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  72949. if (!this._oneGamepadConnected) {
  72950. this._oneGamepadConnected = true;
  72951. }
  72952. var newGamepad;
  72953. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  72954. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  72955. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  72956. }
  72957. // if pose is supported, use the (WebVR) pose enabled controller
  72958. else if (gamepad.pose) {
  72959. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  72960. }
  72961. else {
  72962. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  72963. }
  72964. this._babylonGamepads[newGamepad.index] = newGamepad;
  72965. return newGamepad;
  72966. };
  72967. GamepadManager.prototype._startMonitoringGamepads = function () {
  72968. if (!this._isMonitoring) {
  72969. this._isMonitoring = true;
  72970. //back-comp
  72971. if (!this._scene) {
  72972. this._checkGamepadsStatus();
  72973. }
  72974. }
  72975. };
  72976. GamepadManager.prototype._stopMonitoringGamepads = function () {
  72977. this._isMonitoring = false;
  72978. };
  72979. GamepadManager.prototype._checkGamepadsStatus = function () {
  72980. var _this = this;
  72981. // Hack to be compatible Chrome
  72982. this._updateGamepadObjects();
  72983. for (var i in this._babylonGamepads) {
  72984. var gamepad = this._babylonGamepads[i];
  72985. if (!gamepad || !gamepad.isConnected) {
  72986. continue;
  72987. }
  72988. gamepad.update();
  72989. }
  72990. if (this._isMonitoring && !this._scene) {
  72991. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  72992. }
  72993. };
  72994. // This function is called only on Chrome, which does not properly support
  72995. // connection/disconnection events and forces you to recopy again the gamepad object
  72996. GamepadManager.prototype._updateGamepadObjects = function () {
  72997. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  72998. for (var i = 0; i < gamepads.length; i++) {
  72999. var gamepad = gamepads[i];
  73000. if (gamepad) {
  73001. if (!this._babylonGamepads[gamepad.index]) {
  73002. var newGamepad = this._addNewGamepad(gamepad);
  73003. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73004. }
  73005. else {
  73006. // Forced to copy again this object for Chrome for unknown reason
  73007. this._babylonGamepads[i].browserGamepad = gamepad;
  73008. if (!this._babylonGamepads[i].isConnected) {
  73009. this._babylonGamepads[i]._isConnected = true;
  73010. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  73011. }
  73012. }
  73013. }
  73014. }
  73015. };
  73016. return GamepadManager;
  73017. }());
  73018. BABYLON.GamepadManager = GamepadManager;
  73019. })(BABYLON || (BABYLON = {}));
  73020. //# sourceMappingURL=babylon.gamepadManager.js.map
  73021. var BABYLON;
  73022. (function (BABYLON) {
  73023. var StickValues = /** @class */ (function () {
  73024. function StickValues(x, y) {
  73025. this.x = x;
  73026. this.y = y;
  73027. }
  73028. return StickValues;
  73029. }());
  73030. BABYLON.StickValues = StickValues;
  73031. var Gamepad = /** @class */ (function () {
  73032. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  73033. if (leftStickX === void 0) { leftStickX = 0; }
  73034. if (leftStickY === void 0) { leftStickY = 1; }
  73035. if (rightStickX === void 0) { rightStickX = 2; }
  73036. if (rightStickY === void 0) { rightStickY = 3; }
  73037. this.id = id;
  73038. this.index = index;
  73039. this.browserGamepad = browserGamepad;
  73040. this._isConnected = true;
  73041. this._invertLeftStickY = false;
  73042. this.type = Gamepad.GAMEPAD;
  73043. this._leftStickAxisX = leftStickX;
  73044. this._leftStickAxisY = leftStickY;
  73045. this._rightStickAxisX = rightStickX;
  73046. this._rightStickAxisY = rightStickY;
  73047. if (this.browserGamepad.axes.length >= 2) {
  73048. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73049. }
  73050. if (this.browserGamepad.axes.length >= 4) {
  73051. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73052. }
  73053. }
  73054. Object.defineProperty(Gamepad.prototype, "isConnected", {
  73055. get: function () {
  73056. return this._isConnected;
  73057. },
  73058. enumerable: true,
  73059. configurable: true
  73060. });
  73061. Gamepad.prototype.onleftstickchanged = function (callback) {
  73062. this._onleftstickchanged = callback;
  73063. };
  73064. Gamepad.prototype.onrightstickchanged = function (callback) {
  73065. this._onrightstickchanged = callback;
  73066. };
  73067. Object.defineProperty(Gamepad.prototype, "leftStick", {
  73068. get: function () {
  73069. return this._leftStick;
  73070. },
  73071. set: function (newValues) {
  73072. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  73073. this._onleftstickchanged(newValues);
  73074. }
  73075. this._leftStick = newValues;
  73076. },
  73077. enumerable: true,
  73078. configurable: true
  73079. });
  73080. Object.defineProperty(Gamepad.prototype, "rightStick", {
  73081. get: function () {
  73082. return this._rightStick;
  73083. },
  73084. set: function (newValues) {
  73085. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  73086. this._onrightstickchanged(newValues);
  73087. }
  73088. this._rightStick = newValues;
  73089. },
  73090. enumerable: true,
  73091. configurable: true
  73092. });
  73093. Gamepad.prototype.update = function () {
  73094. if (this._leftStick) {
  73095. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73096. if (this._invertLeftStickY) {
  73097. this.leftStick.y *= -1;
  73098. }
  73099. }
  73100. if (this._rightStick) {
  73101. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73102. }
  73103. };
  73104. Gamepad.prototype.dispose = function () {
  73105. };
  73106. Gamepad.GAMEPAD = 0;
  73107. Gamepad.GENERIC = 1;
  73108. Gamepad.XBOX = 2;
  73109. Gamepad.POSE_ENABLED = 3;
  73110. return Gamepad;
  73111. }());
  73112. BABYLON.Gamepad = Gamepad;
  73113. var GenericPad = /** @class */ (function (_super) {
  73114. __extends(GenericPad, _super);
  73115. function GenericPad(id, index, browserGamepad) {
  73116. var _this = _super.call(this, id, index, browserGamepad) || this;
  73117. _this.onButtonDownObservable = new BABYLON.Observable();
  73118. _this.onButtonUpObservable = new BABYLON.Observable();
  73119. _this.type = Gamepad.GENERIC;
  73120. _this._buttons = new Array(browserGamepad.buttons.length);
  73121. return _this;
  73122. }
  73123. GenericPad.prototype.onbuttondown = function (callback) {
  73124. this._onbuttondown = callback;
  73125. };
  73126. GenericPad.prototype.onbuttonup = function (callback) {
  73127. this._onbuttonup = callback;
  73128. };
  73129. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  73130. if (newValue !== currentValue) {
  73131. if (newValue === 1) {
  73132. if (this._onbuttondown) {
  73133. this._onbuttondown(buttonIndex);
  73134. }
  73135. this.onButtonDownObservable.notifyObservers(buttonIndex);
  73136. }
  73137. if (newValue === 0) {
  73138. if (this._onbuttonup) {
  73139. this._onbuttonup(buttonIndex);
  73140. }
  73141. this.onButtonUpObservable.notifyObservers(buttonIndex);
  73142. }
  73143. }
  73144. return newValue;
  73145. };
  73146. GenericPad.prototype.update = function () {
  73147. _super.prototype.update.call(this);
  73148. for (var index = 0; index < this._buttons.length; index++) {
  73149. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  73150. }
  73151. };
  73152. GenericPad.prototype.dispose = function () {
  73153. _super.prototype.dispose.call(this);
  73154. this.onButtonDownObservable.clear();
  73155. this.onButtonUpObservable.clear();
  73156. };
  73157. return GenericPad;
  73158. }(Gamepad));
  73159. BABYLON.GenericPad = GenericPad;
  73160. })(BABYLON || (BABYLON = {}));
  73161. //# sourceMappingURL=babylon.gamepad.js.map
  73162. var BABYLON;
  73163. (function (BABYLON) {
  73164. /**
  73165. * Defines supported buttons for XBox360 compatible gamepads
  73166. */
  73167. var Xbox360Button;
  73168. (function (Xbox360Button) {
  73169. /** A */
  73170. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  73171. /** B */
  73172. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  73173. /** X */
  73174. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  73175. /** Y */
  73176. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  73177. /** Start */
  73178. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  73179. /** Back */
  73180. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  73181. /** Left button */
  73182. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  73183. /** Right button */
  73184. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  73185. /** Left stick */
  73186. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  73187. /** Right stick */
  73188. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  73189. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  73190. /** Defines values for XBox360 DPad */
  73191. var Xbox360Dpad;
  73192. (function (Xbox360Dpad) {
  73193. /** Up */
  73194. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  73195. /** Down */
  73196. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  73197. /** Left */
  73198. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  73199. /** Right */
  73200. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  73201. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  73202. /**
  73203. * Defines a XBox360 gamepad
  73204. */
  73205. var Xbox360Pad = /** @class */ (function (_super) {
  73206. __extends(Xbox360Pad, _super);
  73207. /**
  73208. * Creates a new XBox360 gamepad object
  73209. * @param id defines the id of this gamepad
  73210. * @param index defines its index
  73211. * @param gamepad defines the internal HTML gamepad object
  73212. * @param xboxOne defines if it is a XBox One gamepad
  73213. */
  73214. function Xbox360Pad(id, index, gamepad, xboxOne) {
  73215. if (xboxOne === void 0) { xboxOne = false; }
  73216. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  73217. _this._leftTrigger = 0;
  73218. _this._rightTrigger = 0;
  73219. /** Observable raised when a button is pressed */
  73220. _this.onButtonDownObservable = new BABYLON.Observable();
  73221. /** Observable raised when a button is released */
  73222. _this.onButtonUpObservable = new BABYLON.Observable();
  73223. /** Observable raised when a pad is pressed */
  73224. _this.onPadDownObservable = new BABYLON.Observable();
  73225. /** Observable raised when a pad is released */
  73226. _this.onPadUpObservable = new BABYLON.Observable();
  73227. _this._buttonA = 0;
  73228. _this._buttonB = 0;
  73229. _this._buttonX = 0;
  73230. _this._buttonY = 0;
  73231. _this._buttonBack = 0;
  73232. _this._buttonStart = 0;
  73233. _this._buttonLB = 0;
  73234. _this._buttonRB = 0;
  73235. _this._buttonLeftStick = 0;
  73236. _this._buttonRightStick = 0;
  73237. _this._dPadUp = 0;
  73238. _this._dPadDown = 0;
  73239. _this._dPadLeft = 0;
  73240. _this._dPadRight = 0;
  73241. _this._isXboxOnePad = false;
  73242. _this.type = BABYLON.Gamepad.XBOX;
  73243. _this._isXboxOnePad = xboxOne;
  73244. return _this;
  73245. }
  73246. /**
  73247. * Defines the callback to call when left trigger is pressed
  73248. * @param callback defines the callback to use
  73249. */
  73250. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  73251. this._onlefttriggerchanged = callback;
  73252. };
  73253. /**
  73254. * Defines the callback to call when right trigger is pressed
  73255. * @param callback defines the callback to use
  73256. */
  73257. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  73258. this._onrighttriggerchanged = callback;
  73259. };
  73260. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  73261. /**
  73262. * Gets or sets left trigger value
  73263. */
  73264. get: function () {
  73265. return this._leftTrigger;
  73266. },
  73267. set: function (newValue) {
  73268. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  73269. this._onlefttriggerchanged(newValue);
  73270. }
  73271. this._leftTrigger = newValue;
  73272. },
  73273. enumerable: true,
  73274. configurable: true
  73275. });
  73276. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  73277. /**
  73278. * Gets or sets right trigger value
  73279. */
  73280. get: function () {
  73281. return this._rightTrigger;
  73282. },
  73283. set: function (newValue) {
  73284. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  73285. this._onrighttriggerchanged(newValue);
  73286. }
  73287. this._rightTrigger = newValue;
  73288. },
  73289. enumerable: true,
  73290. configurable: true
  73291. });
  73292. /**
  73293. * Defines the callback to call when a button is pressed
  73294. * @param callback defines the callback to use
  73295. */
  73296. Xbox360Pad.prototype.onbuttondown = function (callback) {
  73297. this._onbuttondown = callback;
  73298. };
  73299. /**
  73300. * Defines the callback to call when a button is released
  73301. * @param callback defines the callback to use
  73302. */
  73303. Xbox360Pad.prototype.onbuttonup = function (callback) {
  73304. this._onbuttonup = callback;
  73305. };
  73306. /**
  73307. * Defines the callback to call when a pad is pressed
  73308. * @param callback defines the callback to use
  73309. */
  73310. Xbox360Pad.prototype.ondpaddown = function (callback) {
  73311. this._ondpaddown = callback;
  73312. };
  73313. /**
  73314. * Defines the callback to call when a pad is released
  73315. * @param callback defines the callback to use
  73316. */
  73317. Xbox360Pad.prototype.ondpadup = function (callback) {
  73318. this._ondpadup = callback;
  73319. };
  73320. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  73321. if (newValue !== currentValue) {
  73322. if (newValue === 1) {
  73323. if (this._onbuttondown) {
  73324. this._onbuttondown(buttonType);
  73325. }
  73326. this.onButtonDownObservable.notifyObservers(buttonType);
  73327. }
  73328. if (newValue === 0) {
  73329. if (this._onbuttonup) {
  73330. this._onbuttonup(buttonType);
  73331. }
  73332. this.onButtonUpObservable.notifyObservers(buttonType);
  73333. }
  73334. }
  73335. return newValue;
  73336. };
  73337. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  73338. if (newValue !== currentValue) {
  73339. if (newValue === 1) {
  73340. if (this._ondpaddown) {
  73341. this._ondpaddown(buttonType);
  73342. }
  73343. this.onPadDownObservable.notifyObservers(buttonType);
  73344. }
  73345. if (newValue === 0) {
  73346. if (this._ondpadup) {
  73347. this._ondpadup(buttonType);
  73348. }
  73349. this.onPadUpObservable.notifyObservers(buttonType);
  73350. }
  73351. }
  73352. return newValue;
  73353. };
  73354. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  73355. /** Gets or sets value of A button */
  73356. get: function () {
  73357. return this._buttonA;
  73358. },
  73359. set: function (value) {
  73360. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  73361. },
  73362. enumerable: true,
  73363. configurable: true
  73364. });
  73365. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  73366. /** Gets or sets value of B button */
  73367. get: function () {
  73368. return this._buttonB;
  73369. },
  73370. set: function (value) {
  73371. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  73372. },
  73373. enumerable: true,
  73374. configurable: true
  73375. });
  73376. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  73377. /** Gets or sets value of X button */
  73378. get: function () {
  73379. return this._buttonX;
  73380. },
  73381. set: function (value) {
  73382. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  73383. },
  73384. enumerable: true,
  73385. configurable: true
  73386. });
  73387. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  73388. /** Gets or sets value of Y button */
  73389. get: function () {
  73390. return this._buttonY;
  73391. },
  73392. set: function (value) {
  73393. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  73394. },
  73395. enumerable: true,
  73396. configurable: true
  73397. });
  73398. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  73399. /** Gets or sets value of Start button */
  73400. get: function () {
  73401. return this._buttonStart;
  73402. },
  73403. set: function (value) {
  73404. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  73405. },
  73406. enumerable: true,
  73407. configurable: true
  73408. });
  73409. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  73410. /** Gets or sets value of Back button */
  73411. get: function () {
  73412. return this._buttonBack;
  73413. },
  73414. set: function (value) {
  73415. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  73416. },
  73417. enumerable: true,
  73418. configurable: true
  73419. });
  73420. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  73421. /** Gets or sets value of Left button */
  73422. get: function () {
  73423. return this._buttonLB;
  73424. },
  73425. set: function (value) {
  73426. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  73427. },
  73428. enumerable: true,
  73429. configurable: true
  73430. });
  73431. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  73432. /** Gets or sets value of Right button */
  73433. get: function () {
  73434. return this._buttonRB;
  73435. },
  73436. set: function (value) {
  73437. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  73438. },
  73439. enumerable: true,
  73440. configurable: true
  73441. });
  73442. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  73443. /** Gets or sets value of left stick */
  73444. get: function () {
  73445. return this._buttonLeftStick;
  73446. },
  73447. set: function (value) {
  73448. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  73449. },
  73450. enumerable: true,
  73451. configurable: true
  73452. });
  73453. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  73454. /** Gets or sets value of right stick */
  73455. get: function () {
  73456. return this._buttonRightStick;
  73457. },
  73458. set: function (value) {
  73459. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  73460. },
  73461. enumerable: true,
  73462. configurable: true
  73463. });
  73464. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  73465. /** Gets or sets value of DPad up */
  73466. get: function () {
  73467. return this._dPadUp;
  73468. },
  73469. set: function (value) {
  73470. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  73471. },
  73472. enumerable: true,
  73473. configurable: true
  73474. });
  73475. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  73476. /** Gets or sets value of DPad down */
  73477. get: function () {
  73478. return this._dPadDown;
  73479. },
  73480. set: function (value) {
  73481. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  73482. },
  73483. enumerable: true,
  73484. configurable: true
  73485. });
  73486. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  73487. /** Gets or sets value of DPad left */
  73488. get: function () {
  73489. return this._dPadLeft;
  73490. },
  73491. set: function (value) {
  73492. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  73493. },
  73494. enumerable: true,
  73495. configurable: true
  73496. });
  73497. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  73498. /** Gets or sets value of DPad right */
  73499. get: function () {
  73500. return this._dPadRight;
  73501. },
  73502. set: function (value) {
  73503. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  73504. },
  73505. enumerable: true,
  73506. configurable: true
  73507. });
  73508. /**
  73509. * Force the gamepad to synchronize with device values
  73510. */
  73511. Xbox360Pad.prototype.update = function () {
  73512. _super.prototype.update.call(this);
  73513. if (this._isXboxOnePad) {
  73514. this.buttonA = this.browserGamepad.buttons[0].value;
  73515. this.buttonB = this.browserGamepad.buttons[1].value;
  73516. this.buttonX = this.browserGamepad.buttons[2].value;
  73517. this.buttonY = this.browserGamepad.buttons[3].value;
  73518. this.buttonLB = this.browserGamepad.buttons[4].value;
  73519. this.buttonRB = this.browserGamepad.buttons[5].value;
  73520. this.leftTrigger = this.browserGamepad.axes[2];
  73521. this.rightTrigger = this.browserGamepad.axes[5];
  73522. this.buttonBack = this.browserGamepad.buttons[9].value;
  73523. this.buttonStart = this.browserGamepad.buttons[8].value;
  73524. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  73525. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  73526. this.dPadUp = this.browserGamepad.buttons[11].value;
  73527. this.dPadDown = this.browserGamepad.buttons[12].value;
  73528. this.dPadLeft = this.browserGamepad.buttons[13].value;
  73529. this.dPadRight = this.browserGamepad.buttons[14].value;
  73530. }
  73531. else {
  73532. this.buttonA = this.browserGamepad.buttons[0].value;
  73533. this.buttonB = this.browserGamepad.buttons[1].value;
  73534. this.buttonX = this.browserGamepad.buttons[2].value;
  73535. this.buttonY = this.browserGamepad.buttons[3].value;
  73536. this.buttonLB = this.browserGamepad.buttons[4].value;
  73537. this.buttonRB = this.browserGamepad.buttons[5].value;
  73538. this.leftTrigger = this.browserGamepad.buttons[6].value;
  73539. this.rightTrigger = this.browserGamepad.buttons[7].value;
  73540. this.buttonBack = this.browserGamepad.buttons[8].value;
  73541. this.buttonStart = this.browserGamepad.buttons[9].value;
  73542. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  73543. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  73544. this.dPadUp = this.browserGamepad.buttons[12].value;
  73545. this.dPadDown = this.browserGamepad.buttons[13].value;
  73546. this.dPadLeft = this.browserGamepad.buttons[14].value;
  73547. this.dPadRight = this.browserGamepad.buttons[15].value;
  73548. }
  73549. };
  73550. Xbox360Pad.prototype.dispose = function () {
  73551. _super.prototype.dispose.call(this);
  73552. this.onButtonDownObservable.clear();
  73553. this.onButtonUpObservable.clear();
  73554. this.onPadDownObservable.clear();
  73555. this.onPadUpObservable.clear();
  73556. };
  73557. return Xbox360Pad;
  73558. }(BABYLON.Gamepad));
  73559. BABYLON.Xbox360Pad = Xbox360Pad;
  73560. })(BABYLON || (BABYLON = {}));
  73561. //# sourceMappingURL=babylon.xboxGamepad.js.map
  73562. var BABYLON;
  73563. (function (BABYLON) {
  73564. /**
  73565. * Defines the types of pose enabled controllers that are supported
  73566. */
  73567. var PoseEnabledControllerType;
  73568. (function (PoseEnabledControllerType) {
  73569. /**
  73570. * HTC Vive
  73571. */
  73572. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  73573. /**
  73574. * Oculus Rift
  73575. */
  73576. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  73577. /**
  73578. * Windows mixed reality
  73579. */
  73580. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  73581. /**
  73582. * Samsung gear VR
  73583. */
  73584. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  73585. /**
  73586. * Google Daydream
  73587. */
  73588. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  73589. /**
  73590. * Generic
  73591. */
  73592. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  73593. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  73594. /**
  73595. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  73596. */
  73597. var PoseEnabledControllerHelper = /** @class */ (function () {
  73598. function PoseEnabledControllerHelper() {
  73599. }
  73600. /**
  73601. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  73602. * @param vrGamepad the gamepad to initialized
  73603. * @returns a vr controller of the type the gamepad identified as
  73604. */
  73605. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  73606. // Oculus Touch
  73607. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  73608. return new BABYLON.OculusTouchController(vrGamepad);
  73609. }
  73610. // Windows Mixed Reality controllers
  73611. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  73612. return new BABYLON.WindowsMotionController(vrGamepad);
  73613. }
  73614. // HTC Vive
  73615. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  73616. return new BABYLON.ViveController(vrGamepad);
  73617. }
  73618. // Samsung/Oculus Gear VR or Oculus Go
  73619. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  73620. return new BABYLON.GearVRController(vrGamepad);
  73621. }
  73622. // Google Daydream
  73623. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  73624. return new BABYLON.DaydreamController(vrGamepad);
  73625. }
  73626. // Generic
  73627. else {
  73628. return new BABYLON.GenericController(vrGamepad);
  73629. }
  73630. };
  73631. return PoseEnabledControllerHelper;
  73632. }());
  73633. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  73634. /**
  73635. * Defines the PoseEnabledController object that contains state of a vr capable controller
  73636. */
  73637. var PoseEnabledController = /** @class */ (function (_super) {
  73638. __extends(PoseEnabledController, _super);
  73639. /**
  73640. * Creates a new PoseEnabledController from a gamepad
  73641. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  73642. */
  73643. function PoseEnabledController(browserGamepad) {
  73644. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  73645. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  73646. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  73647. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  73648. /**
  73649. * The device position in babylon space
  73650. */
  73651. _this.devicePosition = BABYLON.Vector3.Zero();
  73652. /**
  73653. * The device rotation in babylon space
  73654. */
  73655. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  73656. /**
  73657. * The scale factor of the device in babylon space
  73658. */
  73659. _this.deviceScaleFactor = 1;
  73660. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  73661. /**
  73662. * Internal, matrix used to convert room space to babylon space
  73663. */
  73664. _this._deviceToWorld = BABYLON.Matrix.Identity();
  73665. /**
  73666. * Node to be used when casting a ray from the controller
  73667. */
  73668. _this._pointingPoseNode = null;
  73669. _this._workingMatrix = BABYLON.Matrix.Identity();
  73670. /**
  73671. * @hidden
  73672. */
  73673. _this._meshAttachedObservable = new BABYLON.Observable();
  73674. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  73675. _this.controllerType = PoseEnabledControllerType.GENERIC;
  73676. _this.position = BABYLON.Vector3.Zero();
  73677. _this.rotationQuaternion = new BABYLON.Quaternion();
  73678. _this._calculatedPosition = BABYLON.Vector3.Zero();
  73679. _this._calculatedRotation = new BABYLON.Quaternion();
  73680. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  73681. return _this;
  73682. }
  73683. /**
  73684. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  73685. */
  73686. PoseEnabledController.prototype.update = function () {
  73687. _super.prototype.update.call(this);
  73688. this._updatePoseAndMesh();
  73689. };
  73690. /**
  73691. * Updates only the pose device and mesh without doing any button event checking
  73692. */
  73693. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  73694. var pose = this.browserGamepad.pose;
  73695. this.updateFromDevice(pose);
  73696. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  73697. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  73698. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  73699. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  73700. if (this._mesh) {
  73701. this._mesh.position.copyFrom(this.devicePosition);
  73702. if (this._mesh.rotationQuaternion) {
  73703. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  73704. }
  73705. }
  73706. };
  73707. /**
  73708. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  73709. * @param poseData raw pose fromthe device
  73710. */
  73711. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  73712. if (poseData) {
  73713. this.rawPose = poseData;
  73714. if (poseData.position) {
  73715. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  73716. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  73717. this._deviceRoomPosition.z *= -1;
  73718. }
  73719. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  73720. this._calculatedPosition.addInPlace(this.position);
  73721. }
  73722. var pose = this.rawPose;
  73723. if (poseData.orientation && pose.orientation) {
  73724. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  73725. if (this._mesh) {
  73726. if (this._mesh.getScene().useRightHandedSystem) {
  73727. this._deviceRoomRotationQuaternion.z *= -1;
  73728. this._deviceRoomRotationQuaternion.w *= -1;
  73729. }
  73730. else {
  73731. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  73732. }
  73733. }
  73734. // if the camera is set, rotate to the camera's rotation
  73735. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  73736. }
  73737. }
  73738. };
  73739. /**
  73740. * Attaches a mesh to the controller
  73741. * @param mesh the mesh to be attached
  73742. */
  73743. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  73744. if (this._mesh) {
  73745. this._mesh.parent = null;
  73746. }
  73747. this._mesh = mesh;
  73748. if (this._poseControlledCamera) {
  73749. this._mesh.parent = this._poseControlledCamera;
  73750. }
  73751. if (!this._mesh.rotationQuaternion) {
  73752. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  73753. }
  73754. // 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
  73755. this._updatePoseAndMesh();
  73756. if (this._pointingPoseNode) {
  73757. var parents = [];
  73758. var obj = this._pointingPoseNode;
  73759. while (obj.parent) {
  73760. parents.push(obj.parent);
  73761. obj = obj.parent;
  73762. }
  73763. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  73764. }
  73765. this._meshAttachedObservable.notifyObservers(mesh);
  73766. };
  73767. /**
  73768. * Attaches the controllers mesh to a camera
  73769. * @param camera the camera the mesh should be attached to
  73770. */
  73771. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  73772. this._poseControlledCamera = camera;
  73773. if (this._mesh) {
  73774. this._mesh.parent = this._poseControlledCamera;
  73775. }
  73776. };
  73777. /**
  73778. * Disposes of the controller
  73779. */
  73780. PoseEnabledController.prototype.dispose = function () {
  73781. if (this._mesh) {
  73782. this._mesh.dispose();
  73783. }
  73784. this._mesh = null;
  73785. _super.prototype.dispose.call(this);
  73786. };
  73787. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  73788. /**
  73789. * The mesh that is attached to the controller
  73790. */
  73791. get: function () {
  73792. return this._mesh;
  73793. },
  73794. enumerable: true,
  73795. configurable: true
  73796. });
  73797. /**
  73798. * Gets the ray of the controller in the direction the controller is pointing
  73799. * @param length the length the resulting ray should be
  73800. * @returns a ray in the direction the controller is pointing
  73801. */
  73802. PoseEnabledController.prototype.getForwardRay = function (length) {
  73803. if (length === void 0) { length = 100; }
  73804. if (!this.mesh) {
  73805. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  73806. }
  73807. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  73808. var origin = m.getTranslation();
  73809. var forward = new BABYLON.Vector3(0, 0, -1);
  73810. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73811. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73812. return new BABYLON.Ray(origin, direction, length);
  73813. };
  73814. /**
  73815. * Name of the child mesh that can be used to cast a ray from the controller
  73816. */
  73817. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  73818. return PoseEnabledController;
  73819. }(BABYLON.Gamepad));
  73820. BABYLON.PoseEnabledController = PoseEnabledController;
  73821. })(BABYLON || (BABYLON = {}));
  73822. //# sourceMappingURL=babylon.poseEnabledController.js.map
  73823. var BABYLON;
  73824. (function (BABYLON) {
  73825. /**
  73826. * Defines the WebVRController object that represents controllers tracked in 3D space
  73827. */
  73828. var WebVRController = /** @class */ (function (_super) {
  73829. __extends(WebVRController, _super);
  73830. /**
  73831. * Creates a new WebVRController from a gamepad
  73832. * @param vrGamepad the gamepad that the WebVRController should be created from
  73833. */
  73834. function WebVRController(vrGamepad) {
  73835. var _this = _super.call(this, vrGamepad) || this;
  73836. // Observables
  73837. /**
  73838. * Fired when the trigger state has changed
  73839. */
  73840. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  73841. /**
  73842. * Fired when the main button state has changed
  73843. */
  73844. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  73845. /**
  73846. * Fired when the secondary button state has changed
  73847. */
  73848. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  73849. /**
  73850. * Fired when the pad state has changed
  73851. */
  73852. _this.onPadStateChangedObservable = new BABYLON.Observable();
  73853. /**
  73854. * Fired when controllers stick values have changed
  73855. */
  73856. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  73857. /**
  73858. * X and Y axis corrisponding to the controllers joystick
  73859. */
  73860. _this.pad = { x: 0, y: 0 };
  73861. // avoid GC, store state in a tmp object
  73862. _this._changes = {
  73863. pressChanged: false,
  73864. touchChanged: false,
  73865. valueChanged: false,
  73866. changed: false
  73867. };
  73868. _this._buttons = new Array(vrGamepad.buttons.length);
  73869. _this.hand = vrGamepad.hand;
  73870. return _this;
  73871. }
  73872. /**
  73873. * Fired when a controller button's state has changed
  73874. * @param callback the callback containing the button that was modified
  73875. */
  73876. WebVRController.prototype.onButtonStateChange = function (callback) {
  73877. this._onButtonStateChange = callback;
  73878. };
  73879. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  73880. /**
  73881. * The default controller model for the controller
  73882. */
  73883. get: function () {
  73884. return this._defaultModel;
  73885. },
  73886. enumerable: true,
  73887. configurable: true
  73888. });
  73889. /**
  73890. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  73891. */
  73892. WebVRController.prototype.update = function () {
  73893. _super.prototype.update.call(this);
  73894. for (var index = 0; index < this._buttons.length; index++) {
  73895. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  73896. }
  73897. ;
  73898. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  73899. this.pad.x = this.leftStick.x;
  73900. this.pad.y = this.leftStick.y;
  73901. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  73902. }
  73903. };
  73904. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  73905. if (!newState) {
  73906. newState = {
  73907. pressed: false,
  73908. touched: false,
  73909. value: 0
  73910. };
  73911. }
  73912. if (!currentState) {
  73913. this._buttons[buttonIndex] = {
  73914. pressed: newState.pressed,
  73915. touched: newState.touched,
  73916. value: newState.value
  73917. };
  73918. return;
  73919. }
  73920. this._checkChanges(newState, currentState);
  73921. if (this._changes.changed) {
  73922. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  73923. this._handleButtonChange(buttonIndex, newState, this._changes);
  73924. }
  73925. this._buttons[buttonIndex].pressed = newState.pressed;
  73926. this._buttons[buttonIndex].touched = newState.touched;
  73927. // oculus triggers are never 0, thou not touched.
  73928. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  73929. };
  73930. WebVRController.prototype._checkChanges = function (newState, currentState) {
  73931. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  73932. this._changes.touchChanged = newState.touched !== currentState.touched;
  73933. this._changes.valueChanged = newState.value !== currentState.value;
  73934. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  73935. return this._changes;
  73936. };
  73937. /**
  73938. * Disposes of th webVRCOntroller
  73939. */
  73940. WebVRController.prototype.dispose = function () {
  73941. _super.prototype.dispose.call(this);
  73942. this.onTriggerStateChangedObservable.clear();
  73943. this.onMainButtonStateChangedObservable.clear();
  73944. this.onSecondaryButtonStateChangedObservable.clear();
  73945. this.onPadStateChangedObservable.clear();
  73946. this.onPadValuesChangedObservable.clear();
  73947. };
  73948. return WebVRController;
  73949. }(BABYLON.PoseEnabledController));
  73950. BABYLON.WebVRController = WebVRController;
  73951. })(BABYLON || (BABYLON = {}));
  73952. //# sourceMappingURL=babylon.webVRController.js.map
  73953. var BABYLON;
  73954. (function (BABYLON) {
  73955. /**
  73956. * Oculus Touch Controller
  73957. */
  73958. var OculusTouchController = /** @class */ (function (_super) {
  73959. __extends(OculusTouchController, _super);
  73960. /**
  73961. * Creates a new OculusTouchController from a gamepad
  73962. * @param vrGamepad the gamepad that the controller should be created from
  73963. */
  73964. function OculusTouchController(vrGamepad) {
  73965. var _this = _super.call(this, vrGamepad) || this;
  73966. /**
  73967. * Fired when the secondary trigger on this controller is modified
  73968. */
  73969. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  73970. /**
  73971. * Fired when the thumb rest on this controller is modified
  73972. */
  73973. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  73974. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  73975. return _this;
  73976. }
  73977. /**
  73978. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73979. * @param scene scene in which to add meshes
  73980. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73981. */
  73982. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73983. var _this = this;
  73984. var meshName;
  73985. // Hand
  73986. if (this.hand === 'left') {
  73987. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  73988. }
  73989. else { // Right is the default if no hand is specified
  73990. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  73991. }
  73992. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  73993. /*
  73994. Parent Mesh name: oculus_touch_left
  73995. - body
  73996. - trigger
  73997. - thumbstick
  73998. - grip
  73999. - button_y
  74000. - button_x
  74001. - button_enter
  74002. */
  74003. _this._defaultModel = newMeshes[1];
  74004. _this.attachToMesh(_this._defaultModel);
  74005. if (meshLoaded) {
  74006. meshLoaded(_this._defaultModel);
  74007. }
  74008. });
  74009. };
  74010. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  74011. /**
  74012. * Fired when the A button on this controller is modified
  74013. */
  74014. get: function () {
  74015. if (this.hand === 'right') {
  74016. return this.onMainButtonStateChangedObservable;
  74017. }
  74018. else {
  74019. throw new Error('No A button on left hand');
  74020. }
  74021. },
  74022. enumerable: true,
  74023. configurable: true
  74024. });
  74025. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  74026. /**
  74027. * Fired when the B button on this controller is modified
  74028. */
  74029. get: function () {
  74030. if (this.hand === 'right') {
  74031. return this.onSecondaryButtonStateChangedObservable;
  74032. }
  74033. else {
  74034. throw new Error('No B button on left hand');
  74035. }
  74036. },
  74037. enumerable: true,
  74038. configurable: true
  74039. });
  74040. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  74041. /**
  74042. * Fired when the X button on this controller is modified
  74043. */
  74044. get: function () {
  74045. if (this.hand === 'left') {
  74046. return this.onMainButtonStateChangedObservable;
  74047. }
  74048. else {
  74049. throw new Error('No X button on right hand');
  74050. }
  74051. },
  74052. enumerable: true,
  74053. configurable: true
  74054. });
  74055. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  74056. /**
  74057. * Fired when the Y button on this controller is modified
  74058. */
  74059. get: function () {
  74060. if (this.hand === 'left') {
  74061. return this.onSecondaryButtonStateChangedObservable;
  74062. }
  74063. else {
  74064. throw new Error('No Y button on right hand');
  74065. }
  74066. },
  74067. enumerable: true,
  74068. configurable: true
  74069. });
  74070. /**
  74071. * Called once for each button that changed state since the last frame
  74072. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  74073. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  74074. * 2) secondary trigger (same)
  74075. * 3) A (right) X (left), touch, pressed = value
  74076. * 4) B / Y
  74077. * 5) thumb rest
  74078. * @param buttonIdx Which button index changed
  74079. * @param state New state of the button
  74080. * @param changes Which properties on the state changed since last frame
  74081. */
  74082. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74083. var notifyObject = state; //{ state: state, changes: changes };
  74084. var triggerDirection = this.hand === 'right' ? -1 : 1;
  74085. switch (buttonIdx) {
  74086. case 0:
  74087. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  74088. return;
  74089. case 1: // index trigger
  74090. if (this._defaultModel) {
  74091. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  74092. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  74093. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  74094. }
  74095. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  74096. return;
  74097. case 2: // secondary trigger
  74098. if (this._defaultModel) {
  74099. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  74100. }
  74101. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  74102. return;
  74103. case 3:
  74104. if (this._defaultModel) {
  74105. if (notifyObject.pressed) {
  74106. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  74107. }
  74108. else {
  74109. (this._defaultModel.getChildren()[1]).position.y = 0;
  74110. }
  74111. }
  74112. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  74113. return;
  74114. case 4:
  74115. if (this._defaultModel) {
  74116. if (notifyObject.pressed) {
  74117. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  74118. }
  74119. else {
  74120. (this._defaultModel.getChildren()[2]).position.y = 0;
  74121. }
  74122. }
  74123. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  74124. return;
  74125. case 5:
  74126. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  74127. return;
  74128. }
  74129. };
  74130. /**
  74131. * Base Url for the controller model.
  74132. */
  74133. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  74134. /**
  74135. * File name for the left controller model.
  74136. */
  74137. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  74138. /**
  74139. * File name for the right controller model.
  74140. */
  74141. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  74142. return OculusTouchController;
  74143. }(BABYLON.WebVRController));
  74144. BABYLON.OculusTouchController = OculusTouchController;
  74145. })(BABYLON || (BABYLON = {}));
  74146. //# sourceMappingURL=babylon.oculusTouchController.js.map
  74147. var BABYLON;
  74148. (function (BABYLON) {
  74149. /**
  74150. * Vive Controller
  74151. */
  74152. var ViveController = /** @class */ (function (_super) {
  74153. __extends(ViveController, _super);
  74154. /**
  74155. * Creates a new ViveController from a gamepad
  74156. * @param vrGamepad the gamepad that the controller should be created from
  74157. */
  74158. function ViveController(vrGamepad) {
  74159. var _this = _super.call(this, vrGamepad) || this;
  74160. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  74161. _this._invertLeftStickY = true;
  74162. return _this;
  74163. }
  74164. /**
  74165. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74166. * @param scene scene in which to add meshes
  74167. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74168. */
  74169. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74170. var _this = this;
  74171. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  74172. /*
  74173. Parent Mesh name: ViveWand
  74174. - body
  74175. - r_gripper
  74176. - l_gripper
  74177. - menu_button
  74178. - system_button
  74179. - trackpad
  74180. - trigger
  74181. - LED
  74182. */
  74183. _this._defaultModel = newMeshes[1];
  74184. _this.attachToMesh(_this._defaultModel);
  74185. if (meshLoaded) {
  74186. meshLoaded(_this._defaultModel);
  74187. }
  74188. });
  74189. };
  74190. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  74191. /**
  74192. * Fired when the left button on this controller is modified
  74193. */
  74194. get: function () {
  74195. return this.onMainButtonStateChangedObservable;
  74196. },
  74197. enumerable: true,
  74198. configurable: true
  74199. });
  74200. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  74201. /**
  74202. * Fired when the right button on this controller is modified
  74203. */
  74204. get: function () {
  74205. return this.onMainButtonStateChangedObservable;
  74206. },
  74207. enumerable: true,
  74208. configurable: true
  74209. });
  74210. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  74211. /**
  74212. * Fired when the menu button on this controller is modified
  74213. */
  74214. get: function () {
  74215. return this.onSecondaryButtonStateChangedObservable;
  74216. },
  74217. enumerable: true,
  74218. configurable: true
  74219. });
  74220. /**
  74221. * Called once for each button that changed state since the last frame
  74222. * Vive mapping:
  74223. * 0: touchpad
  74224. * 1: trigger
  74225. * 2: left AND right buttons
  74226. * 3: menu button
  74227. * @param buttonIdx Which button index changed
  74228. * @param state New state of the button
  74229. * @param changes Which properties on the state changed since last frame
  74230. */
  74231. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74232. var notifyObject = state; //{ state: state, changes: changes };
  74233. switch (buttonIdx) {
  74234. case 0:
  74235. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  74236. return;
  74237. case 1: // index trigger
  74238. if (this._defaultModel) {
  74239. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  74240. }
  74241. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  74242. return;
  74243. case 2: // left AND right button
  74244. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  74245. return;
  74246. case 3:
  74247. if (this._defaultModel) {
  74248. if (notifyObject.pressed) {
  74249. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  74250. }
  74251. else {
  74252. (this._defaultModel.getChildren()[2]).position.y = 0;
  74253. }
  74254. }
  74255. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  74256. return;
  74257. }
  74258. };
  74259. /**
  74260. * Base Url for the controller model.
  74261. */
  74262. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  74263. /**
  74264. * File name for the controller model.
  74265. */
  74266. ViveController.MODEL_FILENAME = 'wand.babylon';
  74267. return ViveController;
  74268. }(BABYLON.WebVRController));
  74269. BABYLON.ViveController = ViveController;
  74270. })(BABYLON || (BABYLON = {}));
  74271. //# sourceMappingURL=babylon.viveController.js.map
  74272. var BABYLON;
  74273. (function (BABYLON) {
  74274. /**
  74275. * Generic Controller
  74276. */
  74277. var GenericController = /** @class */ (function (_super) {
  74278. __extends(GenericController, _super);
  74279. /**
  74280. * Creates a new GenericController from a gamepad
  74281. * @param vrGamepad the gamepad that the controller should be created from
  74282. */
  74283. function GenericController(vrGamepad) {
  74284. return _super.call(this, vrGamepad) || this;
  74285. }
  74286. /**
  74287. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74288. * @param scene scene in which to add meshes
  74289. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74290. */
  74291. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74292. var _this = this;
  74293. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  74294. _this._defaultModel = newMeshes[1];
  74295. _this.attachToMesh(_this._defaultModel);
  74296. if (meshLoaded) {
  74297. meshLoaded(_this._defaultModel);
  74298. }
  74299. });
  74300. };
  74301. /**
  74302. * Called once for each button that changed state since the last frame
  74303. * @param buttonIdx Which button index changed
  74304. * @param state New state of the button
  74305. * @param changes Which properties on the state changed since last frame
  74306. */
  74307. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74308. console.log("Button id: " + buttonIdx + "state: ");
  74309. console.dir(state);
  74310. };
  74311. /**
  74312. * Base Url for the controller model.
  74313. */
  74314. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74315. /**
  74316. * File name for the controller model.
  74317. */
  74318. GenericController.MODEL_FILENAME = 'generic.babylon';
  74319. return GenericController;
  74320. }(BABYLON.WebVRController));
  74321. BABYLON.GenericController = GenericController;
  74322. })(BABYLON || (BABYLON = {}));
  74323. //# sourceMappingURL=babylon.genericController.js.map
  74324. var BABYLON;
  74325. (function (BABYLON) {
  74326. /**
  74327. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  74328. */
  74329. var LoadedMeshInfo = /** @class */ (function () {
  74330. function LoadedMeshInfo() {
  74331. /**
  74332. * Map of the button meshes contained in the controller
  74333. */
  74334. this.buttonMeshes = {};
  74335. /**
  74336. * Map of the axis meshes contained in the controller
  74337. */
  74338. this.axisMeshes = {};
  74339. }
  74340. return LoadedMeshInfo;
  74341. }());
  74342. /**
  74343. * Defines the WindowsMotionController object that the state of the windows motion controller
  74344. */
  74345. var WindowsMotionController = /** @class */ (function (_super) {
  74346. __extends(WindowsMotionController, _super);
  74347. /**
  74348. * Creates a new WindowsMotionController from a gamepad
  74349. * @param vrGamepad the gamepad that the controller should be created from
  74350. */
  74351. function WindowsMotionController(vrGamepad) {
  74352. var _this = _super.call(this, vrGamepad) || this;
  74353. _this._mapping = {
  74354. // Semantic button names
  74355. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  74356. // A mapping of the button name to glTF model node name
  74357. // that should be transformed by button value.
  74358. buttonMeshNames: {
  74359. 'trigger': 'SELECT',
  74360. 'menu': 'MENU',
  74361. 'grip': 'GRASP',
  74362. 'thumbstick': 'THUMBSTICK_PRESS',
  74363. 'trackpad': 'TOUCHPAD_PRESS'
  74364. },
  74365. // This mapping is used to translate from the Motion Controller to Babylon semantics
  74366. buttonObservableNames: {
  74367. 'trigger': 'onTriggerStateChangedObservable',
  74368. 'menu': 'onSecondaryButtonStateChangedObservable',
  74369. 'grip': 'onMainButtonStateChangedObservable',
  74370. 'thumbstick': 'onPadStateChangedObservable',
  74371. 'trackpad': 'onTrackpadChangedObservable'
  74372. },
  74373. // A mapping of the axis name to glTF model node name
  74374. // that should be transformed by axis value.
  74375. // This array mirrors the browserGamepad.axes array, such that
  74376. // the mesh corresponding to axis 0 is in this array index 0.
  74377. axisMeshNames: [
  74378. 'THUMBSTICK_X',
  74379. 'THUMBSTICK_Y',
  74380. 'TOUCHPAD_TOUCH_X',
  74381. 'TOUCHPAD_TOUCH_Y'
  74382. ],
  74383. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  74384. };
  74385. /**
  74386. * Fired when the trackpad on this controller is clicked
  74387. */
  74388. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  74389. /**
  74390. * Fired when the trackpad on this controller is modified
  74391. */
  74392. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  74393. /**
  74394. * The current x and y values of this controller's trackpad
  74395. */
  74396. _this.trackpad = { x: 0, y: 0 };
  74397. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  74398. _this._loadedMeshInfo = null;
  74399. return _this;
  74400. }
  74401. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  74402. /**
  74403. * Fired when the trigger on this controller is modified
  74404. */
  74405. get: function () {
  74406. return this.onTriggerStateChangedObservable;
  74407. },
  74408. enumerable: true,
  74409. configurable: true
  74410. });
  74411. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  74412. /**
  74413. * Fired when the menu button on this controller is modified
  74414. */
  74415. get: function () {
  74416. return this.onSecondaryButtonStateChangedObservable;
  74417. },
  74418. enumerable: true,
  74419. configurable: true
  74420. });
  74421. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  74422. /**
  74423. * Fired when the grip button on this controller is modified
  74424. */
  74425. get: function () {
  74426. return this.onMainButtonStateChangedObservable;
  74427. },
  74428. enumerable: true,
  74429. configurable: true
  74430. });
  74431. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  74432. /**
  74433. * Fired when the thumbstick button on this controller is modified
  74434. */
  74435. get: function () {
  74436. return this.onPadStateChangedObservable;
  74437. },
  74438. enumerable: true,
  74439. configurable: true
  74440. });
  74441. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  74442. /**
  74443. * Fired when the touchpad button on this controller is modified
  74444. */
  74445. get: function () {
  74446. return this.onTrackpadChangedObservable;
  74447. },
  74448. enumerable: true,
  74449. configurable: true
  74450. });
  74451. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  74452. /**
  74453. * Fired when the touchpad values on this controller are modified
  74454. */
  74455. get: function () {
  74456. return this.onTrackpadValuesChangedObservable;
  74457. },
  74458. enumerable: true,
  74459. configurable: true
  74460. });
  74461. WindowsMotionController.prototype._updateTrackpad = function () {
  74462. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  74463. this.trackpad.x = this.browserGamepad["axes"][2];
  74464. this.trackpad.y = this.browserGamepad["axes"][3];
  74465. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  74466. }
  74467. };
  74468. /**
  74469. * Called once per frame by the engine.
  74470. */
  74471. WindowsMotionController.prototype.update = function () {
  74472. _super.prototype.update.call(this);
  74473. if (this.browserGamepad.axes) {
  74474. this._updateTrackpad();
  74475. // Only need to animate axes if there is a loaded mesh
  74476. if (this._loadedMeshInfo) {
  74477. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  74478. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  74479. }
  74480. }
  74481. }
  74482. };
  74483. /**
  74484. * Called once for each button that changed state since the last frame
  74485. * @param buttonIdx Which button index changed
  74486. * @param state New state of the button
  74487. * @param changes Which properties on the state changed since last frame
  74488. */
  74489. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74490. var buttonName = this._mapping.buttons[buttonIdx];
  74491. if (!buttonName) {
  74492. return;
  74493. }
  74494. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  74495. this._updateTrackpad();
  74496. // Only emit events for buttons that we know how to map from index to name
  74497. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  74498. if (observable) {
  74499. observable.notifyObservers(state);
  74500. }
  74501. this._lerpButtonTransform(buttonName, state.value);
  74502. };
  74503. /**
  74504. * Moves the buttons on the controller mesh based on their current state
  74505. * @param buttonName the name of the button to move
  74506. * @param buttonValue the value of the button which determines the buttons new position
  74507. */
  74508. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  74509. // If there is no loaded mesh, there is nothing to transform.
  74510. if (!this._loadedMeshInfo) {
  74511. return;
  74512. }
  74513. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  74514. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  74515. return;
  74516. }
  74517. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  74518. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  74519. };
  74520. /**
  74521. * Moves the axis on the controller mesh based on its current state
  74522. * @param axis the index of the axis
  74523. * @param axisValue the value of the axis which determines the meshes new position
  74524. * @hidden
  74525. */
  74526. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  74527. if (!this._loadedMeshInfo) {
  74528. return;
  74529. }
  74530. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  74531. if (!meshInfo) {
  74532. return;
  74533. }
  74534. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  74535. return;
  74536. }
  74537. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  74538. var lerpValue = axisValue * 0.5 + 0.5;
  74539. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  74540. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  74541. };
  74542. /**
  74543. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74544. * @param scene scene in which to add meshes
  74545. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74546. */
  74547. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  74548. var _this = this;
  74549. if (forceDefault === void 0) { forceDefault = false; }
  74550. var path;
  74551. var filename;
  74552. // Checking if GLB loader is present
  74553. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  74554. // Determine the device specific folder based on the ID suffix
  74555. var device = 'default';
  74556. if (this.id && !forceDefault) {
  74557. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  74558. device = ((match && match[0]) || device);
  74559. }
  74560. // Hand
  74561. if (this.hand === 'left') {
  74562. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  74563. }
  74564. else { // Right is the default if no hand is specified
  74565. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  74566. }
  74567. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  74568. }
  74569. else {
  74570. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  74571. path = BABYLON.GenericController.MODEL_BASE_URL;
  74572. filename = BABYLON.GenericController.MODEL_FILENAME;
  74573. }
  74574. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  74575. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  74576. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  74577. if (!_this._loadedMeshInfo) {
  74578. return;
  74579. }
  74580. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  74581. _this.attachToMesh(_this._defaultModel);
  74582. if (meshLoaded) {
  74583. meshLoaded(_this._defaultModel);
  74584. }
  74585. }, null, function (scene, message) {
  74586. BABYLON.Tools.Log(message);
  74587. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  74588. if (!forceDefault) {
  74589. _this.initControllerMesh(scene, meshLoaded, true);
  74590. }
  74591. });
  74592. };
  74593. /**
  74594. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  74595. * can be transformed by button presses and axes values, based on this._mapping.
  74596. *
  74597. * @param scene scene in which the meshes exist
  74598. * @param meshes list of meshes that make up the controller model to process
  74599. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  74600. */
  74601. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  74602. var loadedMeshInfo = null;
  74603. // Create a new mesh to contain the glTF hierarchy
  74604. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  74605. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  74606. var childMesh = null;
  74607. for (var i = 0; i < meshes.length; i++) {
  74608. var mesh = meshes[i];
  74609. if (!mesh.parent) {
  74610. // Exclude controller meshes from picking results
  74611. mesh.isPickable = false;
  74612. // Handle root node, attach to the new parentMesh
  74613. childMesh = mesh;
  74614. break;
  74615. }
  74616. }
  74617. if (childMesh) {
  74618. childMesh.setParent(parentMesh);
  74619. // Create our mesh info. Note that this method will always return non-null.
  74620. loadedMeshInfo = this.createMeshInfo(parentMesh);
  74621. }
  74622. else {
  74623. BABYLON.Tools.Warn('Could not find root node in model file.');
  74624. }
  74625. return loadedMeshInfo;
  74626. };
  74627. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  74628. var loadedMeshInfo = new LoadedMeshInfo();
  74629. var i;
  74630. loadedMeshInfo.rootNode = rootNode;
  74631. // Reset the caches
  74632. loadedMeshInfo.buttonMeshes = {};
  74633. loadedMeshInfo.axisMeshes = {};
  74634. // Button Meshes
  74635. for (i = 0; i < this._mapping.buttons.length; i++) {
  74636. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  74637. if (!buttonMeshName) {
  74638. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  74639. continue;
  74640. }
  74641. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  74642. if (!buttonMesh) {
  74643. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  74644. continue;
  74645. }
  74646. var buttonMeshInfo = {
  74647. index: i,
  74648. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  74649. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  74650. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  74651. };
  74652. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  74653. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  74654. }
  74655. else {
  74656. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  74657. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  74658. '(VALUE: ' + !!buttonMeshInfo.value +
  74659. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  74660. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  74661. ')');
  74662. }
  74663. }
  74664. // Axis Meshes
  74665. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  74666. var axisMeshName = this._mapping.axisMeshNames[i];
  74667. if (!axisMeshName) {
  74668. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  74669. continue;
  74670. }
  74671. var axisMesh = getChildByName(rootNode, axisMeshName);
  74672. if (!axisMesh) {
  74673. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  74674. continue;
  74675. }
  74676. var axisMeshInfo = {
  74677. index: i,
  74678. value: getImmediateChildByName(axisMesh, 'VALUE'),
  74679. min: getImmediateChildByName(axisMesh, 'MIN'),
  74680. max: getImmediateChildByName(axisMesh, 'MAX')
  74681. };
  74682. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  74683. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  74684. }
  74685. else {
  74686. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  74687. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  74688. '(VALUE: ' + !!axisMeshInfo.value +
  74689. ', MIN: ' + !!axisMeshInfo.min +
  74690. ', MAX:' + !!axisMeshInfo.max +
  74691. ')');
  74692. }
  74693. }
  74694. // Pointing Ray
  74695. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  74696. if (!loadedMeshInfo.pointingPoseNode) {
  74697. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  74698. }
  74699. else {
  74700. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  74701. }
  74702. return loadedMeshInfo;
  74703. // Look through all children recursively. This will return null if no mesh exists with the given name.
  74704. function getChildByName(node, name) {
  74705. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  74706. }
  74707. // Look through only immediate children. This will return null if no mesh exists with the given name.
  74708. function getImmediateChildByName(node, name) {
  74709. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  74710. }
  74711. };
  74712. /**
  74713. * Gets the ray of the controller in the direction the controller is pointing
  74714. * @param length the length the resulting ray should be
  74715. * @returns a ray in the direction the controller is pointing
  74716. */
  74717. WindowsMotionController.prototype.getForwardRay = function (length) {
  74718. if (length === void 0) { length = 100; }
  74719. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  74720. return _super.prototype.getForwardRay.call(this, length);
  74721. }
  74722. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  74723. var origin = m.getTranslation();
  74724. var forward = new BABYLON.Vector3(0, 0, -1);
  74725. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74726. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74727. return new BABYLON.Ray(origin, direction, length);
  74728. };
  74729. /**
  74730. * Disposes of the controller
  74731. */
  74732. WindowsMotionController.prototype.dispose = function () {
  74733. _super.prototype.dispose.call(this);
  74734. this.onTrackpadChangedObservable.clear();
  74735. };
  74736. /**
  74737. * The base url used to load the left and right controller models
  74738. */
  74739. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  74740. /**
  74741. * The name of the left controller model file
  74742. */
  74743. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  74744. /**
  74745. * The name of the right controller model file
  74746. */
  74747. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  74748. /**
  74749. * The controller name prefix for this controller type
  74750. */
  74751. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  74752. /**
  74753. * The controller id pattern for this controller type
  74754. */
  74755. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  74756. return WindowsMotionController;
  74757. }(BABYLON.WebVRController));
  74758. BABYLON.WindowsMotionController = WindowsMotionController;
  74759. })(BABYLON || (BABYLON = {}));
  74760. //# sourceMappingURL=babylon.windowsMotionController.js.map
  74761. var BABYLON;
  74762. (function (BABYLON) {
  74763. /**
  74764. * Gear VR Controller
  74765. */
  74766. var GearVRController = /** @class */ (function (_super) {
  74767. __extends(GearVRController, _super);
  74768. /**
  74769. * Creates a new GearVRController from a gamepad
  74770. * @param vrGamepad the gamepad that the controller should be created from
  74771. */
  74772. function GearVRController(vrGamepad) {
  74773. var _this = _super.call(this, vrGamepad) || this;
  74774. _this._maxRotationDistFromHeadset = Math.PI / 5;
  74775. _this._draggedRoomRotation = 0;
  74776. _this._tmpVector = new BABYLON.Vector3();
  74777. _this._buttonIndexToObservableNameMap = [
  74778. 'onTrackpadChangedObservable',
  74779. 'onTriggerStateChangedObservable' // Trigger
  74780. ];
  74781. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  74782. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  74783. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  74784. return _this;
  74785. }
  74786. /**
  74787. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74788. * @param poseData raw pose fromthe device
  74789. */
  74790. GearVRController.prototype.updateFromDevice = function (poseData) {
  74791. _super.prototype.updateFromDevice.call(this, poseData);
  74792. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  74793. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  74794. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  74795. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  74796. // Find the radian distance away that the headset is from the controllers rotation
  74797. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  74798. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  74799. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  74800. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  74801. this._draggedRoomRotation += rotationAmount;
  74802. // Rotate controller around headset
  74803. var sin = Math.sin(-rotationAmount);
  74804. var cos = Math.cos(-rotationAmount);
  74805. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  74806. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  74807. }
  74808. }
  74809. }
  74810. };
  74811. /**
  74812. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74813. * @param scene scene in which to add meshes
  74814. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74815. */
  74816. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74817. var _this = this;
  74818. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  74819. // Offset the controller so it will rotate around the users wrist
  74820. var mesh = new BABYLON.Mesh("", scene);
  74821. newMeshes[1].parent = mesh;
  74822. newMeshes[1].position.z = -0.15;
  74823. _this._defaultModel = mesh;
  74824. _this.attachToMesh(_this._defaultModel);
  74825. if (meshLoaded) {
  74826. meshLoaded(_this._defaultModel);
  74827. }
  74828. });
  74829. };
  74830. /**
  74831. * Called once for each button that changed state since the last frame
  74832. * @param buttonIdx Which button index changed
  74833. * @param state New state of the button
  74834. * @param changes Which properties on the state changed since last frame
  74835. */
  74836. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74837. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  74838. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  74839. // Only emit events for buttons that we know how to map from index to observable
  74840. var observable = this[observableName];
  74841. if (observable) {
  74842. observable.notifyObservers(state);
  74843. }
  74844. }
  74845. };
  74846. /**
  74847. * Base Url for the controller model.
  74848. */
  74849. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74850. /**
  74851. * File name for the controller model.
  74852. */
  74853. GearVRController.MODEL_FILENAME = 'generic.babylon';
  74854. /**
  74855. * Gamepad Id prefix used to identify this controller.
  74856. */
  74857. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  74858. return GearVRController;
  74859. }(BABYLON.WebVRController));
  74860. BABYLON.GearVRController = GearVRController;
  74861. })(BABYLON || (BABYLON = {}));
  74862. //# sourceMappingURL=babylon.gearVRController.js.map
  74863. var BABYLON;
  74864. (function (BABYLON) {
  74865. /**
  74866. * Google Daydream controller
  74867. */
  74868. var DaydreamController = /** @class */ (function (_super) {
  74869. __extends(DaydreamController, _super);
  74870. /**
  74871. * Creates a new DaydreamController from a gamepad
  74872. * @param vrGamepad the gamepad that the controller should be created from
  74873. */
  74874. function DaydreamController(vrGamepad) {
  74875. var _this = _super.call(this, vrGamepad) || this;
  74876. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  74877. return _this;
  74878. }
  74879. /**
  74880. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74881. * @param scene scene in which to add meshes
  74882. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74883. */
  74884. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74885. var _this = this;
  74886. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  74887. _this._defaultModel = newMeshes[1];
  74888. _this.attachToMesh(_this._defaultModel);
  74889. if (meshLoaded) {
  74890. meshLoaded(_this._defaultModel);
  74891. }
  74892. });
  74893. };
  74894. /**
  74895. * Called once for each button that changed state since the last frame
  74896. * @param buttonIdx Which button index changed
  74897. * @param state New state of the button
  74898. * @param changes Which properties on the state changed since last frame
  74899. */
  74900. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74901. // Daydream controller only has 1 GamepadButton (on the trackpad).
  74902. if (buttonIdx === 0) {
  74903. var observable = this.onTriggerStateChangedObservable;
  74904. if (observable) {
  74905. observable.notifyObservers(state);
  74906. }
  74907. }
  74908. else {
  74909. // If the app or home buttons are ever made available
  74910. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  74911. }
  74912. };
  74913. /**
  74914. * Base Url for the controller model.
  74915. */
  74916. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74917. /**
  74918. * File name for the controller model.
  74919. */
  74920. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  74921. /**
  74922. * Gamepad Id prefix used to identify Daydream Controller.
  74923. */
  74924. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  74925. return DaydreamController;
  74926. }(BABYLON.WebVRController));
  74927. BABYLON.DaydreamController = DaydreamController;
  74928. })(BABYLON || (BABYLON = {}));
  74929. //# sourceMappingURL=babylon.daydreamController.js.map
  74930. var BABYLON;
  74931. (function (BABYLON) {
  74932. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  74933. get: function () {
  74934. if (!this._gamepadManager) {
  74935. this._gamepadManager = new BABYLON.GamepadManager(this);
  74936. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  74937. if (!component) {
  74938. component = new GamepadSystemSceneComponent(this);
  74939. this._addComponent(component);
  74940. }
  74941. }
  74942. return this._gamepadManager;
  74943. },
  74944. enumerable: true,
  74945. configurable: true
  74946. });
  74947. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  74948. this.add(new BABYLON.FreeCameraGamepadInput());
  74949. return this;
  74950. };
  74951. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  74952. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  74953. return this;
  74954. };
  74955. /**
  74956. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  74957. */
  74958. var GamepadSystemSceneComponent = /** @class */ (function () {
  74959. /**
  74960. * Creates a new instance of the component for the given scene
  74961. * @param scene Defines the scene to register the component in
  74962. */
  74963. function GamepadSystemSceneComponent(scene) {
  74964. /**
  74965. * The component name helpfull to identify the component in the list of scene components.
  74966. */
  74967. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  74968. this.scene = scene;
  74969. }
  74970. /**
  74971. * Registers the component in a given scene
  74972. */
  74973. GamepadSystemSceneComponent.prototype.register = function () {
  74974. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  74975. };
  74976. /**
  74977. * Rebuilds the elements related to this component in case of
  74978. * context lost for instance.
  74979. */
  74980. GamepadSystemSceneComponent.prototype.rebuild = function () {
  74981. // Nothing to do for gamepads
  74982. };
  74983. /**
  74984. * Disposes the component and the associated ressources
  74985. */
  74986. GamepadSystemSceneComponent.prototype.dispose = function () {
  74987. var gamepadManager = this.scene._gamepadManager;
  74988. if (gamepadManager) {
  74989. gamepadManager.dispose();
  74990. this.scene._gamepadManager = null;
  74991. }
  74992. };
  74993. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  74994. var gamepadManager = this.scene._gamepadManager;
  74995. if (gamepadManager && gamepadManager._isMonitoring) {
  74996. gamepadManager._checkGamepadsStatus();
  74997. }
  74998. };
  74999. return GamepadSystemSceneComponent;
  75000. }());
  75001. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  75002. })(BABYLON || (BABYLON = {}));
  75003. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  75004. var BABYLON;
  75005. (function (BABYLON) {
  75006. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  75007. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  75008. });
  75009. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  75010. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  75011. });
  75012. var FollowCamera = /** @class */ (function (_super) {
  75013. __extends(FollowCamera, _super);
  75014. function FollowCamera(name, position, scene, lockedTarget) {
  75015. if (lockedTarget === void 0) { lockedTarget = null; }
  75016. var _this = _super.call(this, name, position, scene) || this;
  75017. _this.radius = 12;
  75018. _this.rotationOffset = 0;
  75019. _this.heightOffset = 4;
  75020. _this.cameraAcceleration = 0.05;
  75021. _this.maxCameraSpeed = 20;
  75022. _this.lockedTarget = lockedTarget;
  75023. return _this;
  75024. }
  75025. FollowCamera.prototype.getRadians = function (degrees) {
  75026. return degrees * Math.PI / 180;
  75027. };
  75028. FollowCamera.prototype.follow = function (cameraTarget) {
  75029. if (!cameraTarget)
  75030. return;
  75031. var yRotation;
  75032. if (cameraTarget.rotationQuaternion) {
  75033. var rotMatrix = new BABYLON.Matrix();
  75034. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  75035. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  75036. }
  75037. else {
  75038. yRotation = cameraTarget.rotation.y;
  75039. }
  75040. var radians = this.getRadians(this.rotationOffset) + yRotation;
  75041. var targetPosition = cameraTarget.getAbsolutePosition();
  75042. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  75043. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  75044. var dx = targetX - this.position.x;
  75045. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  75046. var dz = (targetZ) - this.position.z;
  75047. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  75048. var vy = dy * this.cameraAcceleration;
  75049. var vz = dz * this.cameraAcceleration * 2;
  75050. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  75051. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75052. }
  75053. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  75054. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75055. }
  75056. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  75057. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75058. }
  75059. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  75060. this.setTarget(targetPosition);
  75061. };
  75062. FollowCamera.prototype._checkInputs = function () {
  75063. _super.prototype._checkInputs.call(this);
  75064. if (this.lockedTarget) {
  75065. this.follow(this.lockedTarget);
  75066. }
  75067. };
  75068. FollowCamera.prototype.getClassName = function () {
  75069. return "FollowCamera";
  75070. };
  75071. __decorate([
  75072. BABYLON.serialize()
  75073. ], FollowCamera.prototype, "radius", void 0);
  75074. __decorate([
  75075. BABYLON.serialize()
  75076. ], FollowCamera.prototype, "rotationOffset", void 0);
  75077. __decorate([
  75078. BABYLON.serialize()
  75079. ], FollowCamera.prototype, "heightOffset", void 0);
  75080. __decorate([
  75081. BABYLON.serialize()
  75082. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  75083. __decorate([
  75084. BABYLON.serialize()
  75085. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  75086. __decorate([
  75087. BABYLON.serializeAsMeshReference("lockedTargetId")
  75088. ], FollowCamera.prototype, "lockedTarget", void 0);
  75089. return FollowCamera;
  75090. }(BABYLON.TargetCamera));
  75091. BABYLON.FollowCamera = FollowCamera;
  75092. var ArcFollowCamera = /** @class */ (function (_super) {
  75093. __extends(ArcFollowCamera, _super);
  75094. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  75095. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  75096. _this.alpha = alpha;
  75097. _this.beta = beta;
  75098. _this.radius = radius;
  75099. _this.target = target;
  75100. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  75101. _this.follow();
  75102. return _this;
  75103. }
  75104. ArcFollowCamera.prototype.follow = function () {
  75105. if (!this.target) {
  75106. return;
  75107. }
  75108. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  75109. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  75110. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  75111. var targetPosition = this.target.getAbsolutePosition();
  75112. this.position = targetPosition.add(this._cartesianCoordinates);
  75113. this.setTarget(targetPosition);
  75114. };
  75115. ArcFollowCamera.prototype._checkInputs = function () {
  75116. _super.prototype._checkInputs.call(this);
  75117. this.follow();
  75118. };
  75119. ArcFollowCamera.prototype.getClassName = function () {
  75120. return "ArcFollowCamera";
  75121. };
  75122. return ArcFollowCamera;
  75123. }(BABYLON.TargetCamera));
  75124. BABYLON.ArcFollowCamera = ArcFollowCamera;
  75125. })(BABYLON || (BABYLON = {}));
  75126. //# sourceMappingURL=babylon.followCamera.js.map
  75127. var BABYLON;
  75128. (function (BABYLON) {
  75129. // We're mainly based on the logic defined into the FreeCamera code
  75130. var UniversalCamera = /** @class */ (function (_super) {
  75131. __extends(UniversalCamera, _super);
  75132. //-- end properties for backward compatibility for inputs
  75133. function UniversalCamera(name, position, scene) {
  75134. var _this = _super.call(this, name, position, scene) || this;
  75135. _this.inputs.addGamepad();
  75136. return _this;
  75137. }
  75138. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  75139. //-- Begin properties for backward compatibility for inputs
  75140. get: function () {
  75141. var gamepad = this.inputs.attached["gamepad"];
  75142. if (gamepad)
  75143. return gamepad.gamepadAngularSensibility;
  75144. return 0;
  75145. },
  75146. set: function (value) {
  75147. var gamepad = this.inputs.attached["gamepad"];
  75148. if (gamepad)
  75149. gamepad.gamepadAngularSensibility = value;
  75150. },
  75151. enumerable: true,
  75152. configurable: true
  75153. });
  75154. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  75155. get: function () {
  75156. var gamepad = this.inputs.attached["gamepad"];
  75157. if (gamepad)
  75158. return gamepad.gamepadMoveSensibility;
  75159. return 0;
  75160. },
  75161. set: function (value) {
  75162. var gamepad = this.inputs.attached["gamepad"];
  75163. if (gamepad)
  75164. gamepad.gamepadMoveSensibility = value;
  75165. },
  75166. enumerable: true,
  75167. configurable: true
  75168. });
  75169. UniversalCamera.prototype.getClassName = function () {
  75170. return "UniversalCamera";
  75171. };
  75172. return UniversalCamera;
  75173. }(BABYLON.TouchCamera));
  75174. BABYLON.UniversalCamera = UniversalCamera;
  75175. })(BABYLON || (BABYLON = {}));
  75176. //# sourceMappingURL=babylon.universalCamera.js.map
  75177. var BABYLON;
  75178. (function (BABYLON) {
  75179. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  75180. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  75181. });
  75182. // We're mainly based on the logic defined into the FreeCamera code
  75183. var GamepadCamera = /** @class */ (function (_super) {
  75184. __extends(GamepadCamera, _super);
  75185. //-- end properties for backward compatibility for inputs
  75186. function GamepadCamera(name, position, scene) {
  75187. return _super.call(this, name, position, scene) || this;
  75188. }
  75189. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  75190. //-- Begin properties for backward compatibility for inputs
  75191. get: function () {
  75192. var gamepad = this.inputs.attached["gamepad"];
  75193. if (gamepad)
  75194. return gamepad.gamepadAngularSensibility;
  75195. return 0;
  75196. },
  75197. set: function (value) {
  75198. var gamepad = this.inputs.attached["gamepad"];
  75199. if (gamepad)
  75200. gamepad.gamepadAngularSensibility = value;
  75201. },
  75202. enumerable: true,
  75203. configurable: true
  75204. });
  75205. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  75206. get: function () {
  75207. var gamepad = this.inputs.attached["gamepad"];
  75208. if (gamepad)
  75209. return gamepad.gamepadMoveSensibility;
  75210. return 0;
  75211. },
  75212. set: function (value) {
  75213. var gamepad = this.inputs.attached["gamepad"];
  75214. if (gamepad)
  75215. gamepad.gamepadMoveSensibility = value;
  75216. },
  75217. enumerable: true,
  75218. configurable: true
  75219. });
  75220. GamepadCamera.prototype.getClassName = function () {
  75221. return "GamepadCamera";
  75222. };
  75223. return GamepadCamera;
  75224. }(BABYLON.UniversalCamera));
  75225. BABYLON.GamepadCamera = GamepadCamera;
  75226. })(BABYLON || (BABYLON = {}));
  75227. //# sourceMappingURL=babylon.gamepadCamera.js.map
  75228. var BABYLON;
  75229. (function (BABYLON) {
  75230. var PostProcessRenderPipelineManager = /** @class */ (function () {
  75231. function PostProcessRenderPipelineManager() {
  75232. this._renderPipelines = {};
  75233. }
  75234. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  75235. this._renderPipelines[renderPipeline._name] = renderPipeline;
  75236. };
  75237. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  75238. if (unique === void 0) { unique = false; }
  75239. var renderPipeline = this._renderPipelines[renderPipelineName];
  75240. if (!renderPipeline) {
  75241. return;
  75242. }
  75243. renderPipeline._attachCameras(cameras, unique);
  75244. };
  75245. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  75246. var renderPipeline = this._renderPipelines[renderPipelineName];
  75247. if (!renderPipeline) {
  75248. return;
  75249. }
  75250. renderPipeline._detachCameras(cameras);
  75251. };
  75252. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  75253. var renderPipeline = this._renderPipelines[renderPipelineName];
  75254. if (!renderPipeline) {
  75255. return;
  75256. }
  75257. renderPipeline._enableEffect(renderEffectName, cameras);
  75258. };
  75259. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  75260. var renderPipeline = this._renderPipelines[renderPipelineName];
  75261. if (!renderPipeline) {
  75262. return;
  75263. }
  75264. renderPipeline._disableEffect(renderEffectName, cameras);
  75265. };
  75266. PostProcessRenderPipelineManager.prototype.update = function () {
  75267. for (var renderPipelineName in this._renderPipelines) {
  75268. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75269. var pipeline = this._renderPipelines[renderPipelineName];
  75270. if (!pipeline.isSupported) {
  75271. pipeline.dispose();
  75272. delete this._renderPipelines[renderPipelineName];
  75273. }
  75274. else {
  75275. pipeline._update();
  75276. }
  75277. }
  75278. }
  75279. };
  75280. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  75281. for (var renderPipelineName in this._renderPipelines) {
  75282. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75283. var pipeline = this._renderPipelines[renderPipelineName];
  75284. pipeline._rebuild();
  75285. }
  75286. }
  75287. };
  75288. PostProcessRenderPipelineManager.prototype.dispose = function () {
  75289. for (var renderPipelineName in this._renderPipelines) {
  75290. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75291. var pipeline = this._renderPipelines[renderPipelineName];
  75292. pipeline.dispose();
  75293. }
  75294. }
  75295. };
  75296. return PostProcessRenderPipelineManager;
  75297. }());
  75298. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  75299. })(BABYLON || (BABYLON = {}));
  75300. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  75301. var BABYLON;
  75302. (function (BABYLON) {
  75303. /**
  75304. * This represents a set of one or more post processes in Babylon.
  75305. * A post process can be used to apply a shader to a texture after it is rendered.
  75306. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  75307. */
  75308. var PostProcessRenderEffect = /** @class */ (function () {
  75309. /**
  75310. * Instantiates a post process render effect.
  75311. * A post process can be used to apply a shader to a texture after it is rendered.
  75312. * @param engine The engine the effect is tied to
  75313. * @param name The name of the effect
  75314. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  75315. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  75316. */
  75317. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  75318. this._name = name;
  75319. this._singleInstance = singleInstance || true;
  75320. this._getPostProcesses = getPostProcesses;
  75321. this._cameras = {};
  75322. this._indicesForCamera = {};
  75323. this._postProcesses = {};
  75324. }
  75325. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  75326. /**
  75327. * Checks if all the post processes in the effect are supported.
  75328. */
  75329. get: function () {
  75330. for (var index in this._postProcesses) {
  75331. if (this._postProcesses.hasOwnProperty(index)) {
  75332. var pps = this._postProcesses[index];
  75333. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  75334. if (!pps[ppIndex].isSupported) {
  75335. return false;
  75336. }
  75337. }
  75338. }
  75339. }
  75340. return true;
  75341. },
  75342. enumerable: true,
  75343. configurable: true
  75344. });
  75345. /**
  75346. * Updates the current state of the effect
  75347. */
  75348. PostProcessRenderEffect.prototype._update = function () {
  75349. };
  75350. /**
  75351. * Attaches the effect on cameras
  75352. * @param cameras The camera to attach to.
  75353. */
  75354. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  75355. var _this = this;
  75356. var cameraKey;
  75357. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75358. if (!cams) {
  75359. return;
  75360. }
  75361. for (var i = 0; i < cams.length; i++) {
  75362. var camera = cams[i];
  75363. var cameraName = camera.name;
  75364. if (this._singleInstance) {
  75365. cameraKey = 0;
  75366. }
  75367. else {
  75368. cameraKey = cameraName;
  75369. }
  75370. if (!this._postProcesses[cameraKey]) {
  75371. var postProcess = this._getPostProcesses();
  75372. if (postProcess) {
  75373. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  75374. }
  75375. }
  75376. if (!this._indicesForCamera[cameraName]) {
  75377. this._indicesForCamera[cameraName] = [];
  75378. }
  75379. this._postProcesses[cameraKey].forEach(function (postProcess) {
  75380. var index = camera.attachPostProcess(postProcess);
  75381. _this._indicesForCamera[cameraName].push(index);
  75382. });
  75383. if (!this._cameras[cameraName]) {
  75384. this._cameras[cameraName] = camera;
  75385. }
  75386. }
  75387. };
  75388. /**
  75389. * Detatches the effect on cameras
  75390. * @param cameras The camera to detatch from.
  75391. */
  75392. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  75393. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75394. if (!cams) {
  75395. return;
  75396. }
  75397. for (var i = 0; i < cams.length; i++) {
  75398. var camera = cams[i];
  75399. var cameraName = camera.name;
  75400. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75401. camera.detachPostProcess(postProcess);
  75402. });
  75403. if (this._cameras[cameraName]) {
  75404. //this._indicesForCamera.splice(index, 1);
  75405. this._cameras[cameraName] = null;
  75406. }
  75407. }
  75408. };
  75409. /**
  75410. * Enables the effect on given cameras
  75411. * @param cameras The camera to enable.
  75412. */
  75413. PostProcessRenderEffect.prototype._enable = function (cameras) {
  75414. var _this = this;
  75415. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75416. if (!cams) {
  75417. return;
  75418. }
  75419. for (var i = 0; i < cams.length; i++) {
  75420. var camera = cams[i];
  75421. var cameraName = camera.name;
  75422. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  75423. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  75424. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75425. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  75426. });
  75427. }
  75428. }
  75429. }
  75430. };
  75431. /**
  75432. * Disables the effect on the given cameras
  75433. * @param cameras The camera to disable.
  75434. */
  75435. PostProcessRenderEffect.prototype._disable = function (cameras) {
  75436. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75437. if (!cams) {
  75438. return;
  75439. }
  75440. for (var i = 0; i < cams.length; i++) {
  75441. var camera = cams[i];
  75442. var cameraName = camera.name;
  75443. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75444. camera.detachPostProcess(postProcess);
  75445. });
  75446. }
  75447. };
  75448. /**
  75449. * Gets a list of the post processes contained in the effect.
  75450. * @param camera The camera to get the post processes on.
  75451. * @returns The list of the post processes in the effect.
  75452. */
  75453. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  75454. if (this._singleInstance) {
  75455. return this._postProcesses[0];
  75456. }
  75457. else {
  75458. if (!camera) {
  75459. return null;
  75460. }
  75461. return this._postProcesses[camera.name];
  75462. }
  75463. };
  75464. return PostProcessRenderEffect;
  75465. }());
  75466. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  75467. })(BABYLON || (BABYLON = {}));
  75468. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  75469. var BABYLON;
  75470. (function (BABYLON) {
  75471. var PostProcessRenderPipeline = /** @class */ (function () {
  75472. function PostProcessRenderPipeline(engine, name) {
  75473. this.engine = engine;
  75474. this._name = name;
  75475. this._renderEffects = {};
  75476. this._renderEffectsForIsolatedPass = new Array();
  75477. this._cameras = [];
  75478. }
  75479. PostProcessRenderPipeline.prototype.getClassName = function () {
  75480. return "PostProcessRenderPipeline";
  75481. };
  75482. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  75483. get: function () {
  75484. for (var renderEffectName in this._renderEffects) {
  75485. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75486. if (!this._renderEffects[renderEffectName].isSupported) {
  75487. return false;
  75488. }
  75489. }
  75490. }
  75491. return true;
  75492. },
  75493. enumerable: true,
  75494. configurable: true
  75495. });
  75496. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  75497. this._renderEffects[renderEffect._name] = renderEffect;
  75498. };
  75499. // private
  75500. PostProcessRenderPipeline.prototype._rebuild = function () {
  75501. };
  75502. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  75503. var renderEffects = this._renderEffects[renderEffectName];
  75504. if (!renderEffects) {
  75505. return;
  75506. }
  75507. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  75508. };
  75509. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  75510. var renderEffects = this._renderEffects[renderEffectName];
  75511. if (!renderEffects) {
  75512. return;
  75513. }
  75514. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  75515. };
  75516. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  75517. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75518. if (!cams) {
  75519. return;
  75520. }
  75521. var indicesToDelete = [];
  75522. var i;
  75523. for (i = 0; i < cams.length; i++) {
  75524. var camera = cams[i];
  75525. var cameraName = camera.name;
  75526. if (this._cameras.indexOf(camera) === -1) {
  75527. this._cameras[cameraName] = camera;
  75528. }
  75529. else if (unique) {
  75530. indicesToDelete.push(i);
  75531. }
  75532. }
  75533. for (i = 0; i < indicesToDelete.length; i++) {
  75534. cameras.splice(indicesToDelete[i], 1);
  75535. }
  75536. for (var renderEffectName in this._renderEffects) {
  75537. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75538. this._renderEffects[renderEffectName]._attachCameras(cams);
  75539. }
  75540. }
  75541. };
  75542. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  75543. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75544. if (!cams) {
  75545. return;
  75546. }
  75547. for (var renderEffectName in this._renderEffects) {
  75548. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75549. this._renderEffects[renderEffectName]._detachCameras(cams);
  75550. }
  75551. }
  75552. for (var i = 0; i < cams.length; i++) {
  75553. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  75554. }
  75555. };
  75556. PostProcessRenderPipeline.prototype._update = function () {
  75557. for (var renderEffectName in this._renderEffects) {
  75558. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75559. this._renderEffects[renderEffectName]._update();
  75560. }
  75561. }
  75562. for (var i = 0; i < this._cameras.length; i++) {
  75563. var cameraName = this._cameras[i].name;
  75564. if (this._renderEffectsForIsolatedPass[cameraName]) {
  75565. this._renderEffectsForIsolatedPass[cameraName]._update();
  75566. }
  75567. }
  75568. };
  75569. PostProcessRenderPipeline.prototype._reset = function () {
  75570. this._renderEffects = {};
  75571. this._renderEffectsForIsolatedPass = new Array();
  75572. };
  75573. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  75574. // 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)
  75575. var effectKeys = Object.keys(this._renderEffects);
  75576. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  75577. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  75578. if (postProcesses) {
  75579. postProcesses[0].samples = sampleCount;
  75580. return true;
  75581. }
  75582. }
  75583. return false;
  75584. };
  75585. PostProcessRenderPipeline.prototype.dispose = function () {
  75586. // Must be implemented by children
  75587. };
  75588. __decorate([
  75589. BABYLON.serialize()
  75590. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  75591. return PostProcessRenderPipeline;
  75592. }());
  75593. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  75594. })(BABYLON || (BABYLON = {}));
  75595. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  75596. var BABYLON;
  75597. (function (BABYLON) {
  75598. /**
  75599. * This represents a depth renderer in Babylon.
  75600. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  75601. */
  75602. var DepthRenderer = /** @class */ (function () {
  75603. /**
  75604. * Instantiates a depth renderer
  75605. * @param scene The scene the renderer belongs to
  75606. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  75607. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  75608. */
  75609. function DepthRenderer(scene, type, camera) {
  75610. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  75611. if (camera === void 0) { camera = null; }
  75612. var _this = this;
  75613. this._scene = scene;
  75614. this._camera = camera;
  75615. var engine = scene.getEngine();
  75616. // Render target
  75617. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  75618. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75619. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75620. this._depthMap.refreshRate = 1;
  75621. this._depthMap.renderParticles = false;
  75622. this._depthMap.renderList = null;
  75623. // Camera to get depth map from to support multiple concurrent cameras
  75624. this._depthMap.activeCamera = this._camera;
  75625. this._depthMap.ignoreCameraViewport = true;
  75626. this._depthMap.useCameraPostProcesses = false;
  75627. // set default depth value to 1.0 (far away)
  75628. this._depthMap.onClearObservable.add(function (engine) {
  75629. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  75630. });
  75631. // Custom render function
  75632. var renderSubMesh = function (subMesh) {
  75633. var mesh = subMesh.getRenderingMesh();
  75634. var scene = _this._scene;
  75635. var engine = scene.getEngine();
  75636. var material = subMesh.getMaterial();
  75637. if (!material) {
  75638. return;
  75639. }
  75640. // Culling and reverse (right handed system)
  75641. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75642. // Managing instances
  75643. var batch = mesh._getInstancesRenderList(subMesh._id);
  75644. if (batch.mustReturn) {
  75645. return;
  75646. }
  75647. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75648. var camera = _this._camera || scene.activeCamera;
  75649. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  75650. engine.enableEffect(_this._effect);
  75651. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75652. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75653. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  75654. // Alpha test
  75655. if (material && material.needAlphaTesting()) {
  75656. var alphaTexture = material.getAlphaTestTexture();
  75657. if (alphaTexture) {
  75658. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75659. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75660. }
  75661. }
  75662. // Bones
  75663. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75664. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75665. }
  75666. // Draw
  75667. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75668. }
  75669. };
  75670. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75671. var index;
  75672. if (depthOnlySubMeshes.length) {
  75673. engine.setColorWrite(false);
  75674. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75675. renderSubMesh(depthOnlySubMeshes.data[index]);
  75676. }
  75677. engine.setColorWrite(true);
  75678. }
  75679. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75680. renderSubMesh(opaqueSubMeshes.data[index]);
  75681. }
  75682. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75683. renderSubMesh(alphaTestSubMeshes.data[index]);
  75684. }
  75685. };
  75686. }
  75687. /**
  75688. * Creates the depth rendering effect and checks if the effect is ready.
  75689. * @param subMesh The submesh to be used to render the depth map of
  75690. * @param useInstances If multiple world instances should be used
  75691. * @returns if the depth renderer is ready to render the depth map
  75692. */
  75693. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  75694. var material = subMesh.getMaterial();
  75695. if (material.disableDepthWrite) {
  75696. return false;
  75697. }
  75698. var defines = [];
  75699. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75700. var mesh = subMesh.getMesh();
  75701. // Alpha test
  75702. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  75703. defines.push("#define ALPHATEST");
  75704. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75705. attribs.push(BABYLON.VertexBuffer.UVKind);
  75706. defines.push("#define UV1");
  75707. }
  75708. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75709. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75710. defines.push("#define UV2");
  75711. }
  75712. }
  75713. // Bones
  75714. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75715. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75716. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75717. if (mesh.numBoneInfluencers > 4) {
  75718. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75719. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75720. }
  75721. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75722. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75723. }
  75724. else {
  75725. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75726. }
  75727. // Instances
  75728. if (useInstances) {
  75729. defines.push("#define INSTANCES");
  75730. attribs.push("world0");
  75731. attribs.push("world1");
  75732. attribs.push("world2");
  75733. attribs.push("world3");
  75734. }
  75735. // Get correct effect
  75736. var join = defines.join("\n");
  75737. if (this._cachedDefines !== join) {
  75738. this._cachedDefines = join;
  75739. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  75740. }
  75741. return this._effect.isReady();
  75742. };
  75743. /**
  75744. * Gets the texture which the depth map will be written to.
  75745. * @returns The depth map texture
  75746. */
  75747. DepthRenderer.prototype.getDepthMap = function () {
  75748. return this._depthMap;
  75749. };
  75750. /**
  75751. * Disposes of the depth renderer.
  75752. */
  75753. DepthRenderer.prototype.dispose = function () {
  75754. this._depthMap.dispose();
  75755. };
  75756. return DepthRenderer;
  75757. }());
  75758. BABYLON.DepthRenderer = DepthRenderer;
  75759. })(BABYLON || (BABYLON = {}));
  75760. //# sourceMappingURL=babylon.depthRenderer.js.map
  75761. var BABYLON;
  75762. (function (BABYLON) {
  75763. var SSAORenderingPipeline = /** @class */ (function (_super) {
  75764. __extends(SSAORenderingPipeline, _super);
  75765. /**
  75766. * @constructor
  75767. * @param {string} name - The rendering pipeline name
  75768. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75769. * @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 }
  75770. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75771. */
  75772. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  75773. var _this = _super.call(this, scene.getEngine(), name) || this;
  75774. // Members
  75775. /**
  75776. * The PassPostProcess id in the pipeline that contains the original scene color
  75777. */
  75778. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75779. /**
  75780. * The SSAO PostProcess id in the pipeline
  75781. */
  75782. _this.SSAORenderEffect = "SSAORenderEffect";
  75783. /**
  75784. * The horizontal blur PostProcess id in the pipeline
  75785. */
  75786. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75787. /**
  75788. * The vertical blur PostProcess id in the pipeline
  75789. */
  75790. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75791. /**
  75792. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75793. */
  75794. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75795. /**
  75796. * The output strength of the SSAO post-process. Default value is 1.0.
  75797. */
  75798. _this.totalStrength = 1.0;
  75799. /**
  75800. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  75801. */
  75802. _this.radius = 0.0001;
  75803. /**
  75804. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  75805. * Must not be equal to fallOff and superior to fallOff.
  75806. * Default value is 0.975
  75807. */
  75808. _this.area = 0.0075;
  75809. /**
  75810. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  75811. * Must not be equal to area and inferior to area.
  75812. * Default value is 0.0
  75813. */
  75814. _this.fallOff = 0.000001;
  75815. /**
  75816. * The base color of the SSAO post-process
  75817. * The final result is "base + ssao" between [0, 1]
  75818. */
  75819. _this.base = 0.5;
  75820. _this._firstUpdate = true;
  75821. _this._scene = scene;
  75822. // Set up assets
  75823. _this._createRandomTexture();
  75824. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75825. var ssaoRatio = ratio.ssaoRatio || ratio;
  75826. var combineRatio = ratio.combineRatio || ratio;
  75827. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75828. _this._createSSAOPostProcess(ssaoRatio);
  75829. _this._createBlurPostProcess(ssaoRatio);
  75830. _this._createSSAOCombinePostProcess(combineRatio);
  75831. // Set up pipeline
  75832. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75833. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75834. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75835. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75836. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75837. // Finish
  75838. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75839. if (cameras)
  75840. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75841. return _this;
  75842. }
  75843. // Public Methods
  75844. /**
  75845. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75846. */
  75847. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75848. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75849. for (var i = 0; i < this._scene.cameras.length; i++) {
  75850. var camera = this._scene.cameras[i];
  75851. this._originalColorPostProcess.dispose(camera);
  75852. this._ssaoPostProcess.dispose(camera);
  75853. this._blurHPostProcess.dispose(camera);
  75854. this._blurVPostProcess.dispose(camera);
  75855. this._ssaoCombinePostProcess.dispose(camera);
  75856. }
  75857. this._randomTexture.dispose();
  75858. if (disableDepthRender)
  75859. this._scene.disableDepthRenderer();
  75860. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75861. _super.prototype.dispose.call(this);
  75862. };
  75863. // Private Methods
  75864. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  75865. var _this = this;
  75866. var size = 16;
  75867. 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);
  75868. 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);
  75869. this._blurHPostProcess.onActivateObservable.add(function () {
  75870. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  75871. _this._blurHPostProcess.kernel = size * dw;
  75872. });
  75873. this._blurVPostProcess.onActivateObservable.add(function () {
  75874. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  75875. _this._blurVPostProcess.kernel = size * dw;
  75876. });
  75877. };
  75878. SSAORenderingPipeline.prototype._rebuild = function () {
  75879. this._firstUpdate = true;
  75880. _super.prototype._rebuild.call(this);
  75881. };
  75882. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75883. var _this = this;
  75884. var numSamples = 16;
  75885. var sampleSphere = [
  75886. 0.5381, 0.1856, -0.4319,
  75887. 0.1379, 0.2486, 0.4430,
  75888. 0.3371, 0.5679, -0.0057,
  75889. -0.6999, -0.0451, -0.0019,
  75890. 0.0689, -0.1598, -0.8547,
  75891. 0.0560, 0.0069, -0.1843,
  75892. -0.0146, 0.1402, 0.0762,
  75893. 0.0100, -0.1924, -0.0344,
  75894. -0.3577, -0.5301, -0.4358,
  75895. -0.3169, 0.1063, 0.0158,
  75896. 0.0103, -0.5869, 0.0046,
  75897. -0.0897, -0.4940, 0.3287,
  75898. 0.7119, -0.0154, -0.0918,
  75899. -0.0533, 0.0596, -0.5411,
  75900. 0.0352, -0.0631, 0.5460,
  75901. -0.4776, 0.2847, -0.0271
  75902. ];
  75903. var samplesFactor = 1.0 / numSamples;
  75904. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  75905. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75906. "area", "fallOff", "base", "range", "viewport"
  75907. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75908. this._ssaoPostProcess.onApply = function (effect) {
  75909. if (_this._firstUpdate) {
  75910. effect.setArray3("sampleSphere", sampleSphere);
  75911. effect.setFloat("samplesFactor", samplesFactor);
  75912. effect.setFloat("randTextureTiles", 4.0);
  75913. }
  75914. effect.setFloat("totalStrength", _this.totalStrength);
  75915. effect.setFloat("radius", _this.radius);
  75916. effect.setFloat("area", _this.area);
  75917. effect.setFloat("fallOff", _this.fallOff);
  75918. effect.setFloat("base", _this.base);
  75919. effect.setTexture("textureSampler", _this._depthTexture);
  75920. effect.setTexture("randomSampler", _this._randomTexture);
  75921. };
  75922. };
  75923. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75924. var _this = this;
  75925. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75926. this._ssaoCombinePostProcess.onApply = function (effect) {
  75927. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  75928. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75929. };
  75930. };
  75931. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  75932. var size = 512;
  75933. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75934. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75935. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75936. var context = this._randomTexture.getContext();
  75937. var rand = function (min, max) {
  75938. return Math.random() * (max - min) + min;
  75939. };
  75940. var randVector = BABYLON.Vector3.Zero();
  75941. for (var x = 0; x < size; x++) {
  75942. for (var y = 0; y < size; y++) {
  75943. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  75944. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  75945. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  75946. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75947. context.fillRect(x, y, 1, 1);
  75948. }
  75949. }
  75950. this._randomTexture.update(false);
  75951. };
  75952. __decorate([
  75953. BABYLON.serialize()
  75954. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  75955. __decorate([
  75956. BABYLON.serialize()
  75957. ], SSAORenderingPipeline.prototype, "radius", void 0);
  75958. __decorate([
  75959. BABYLON.serialize()
  75960. ], SSAORenderingPipeline.prototype, "area", void 0);
  75961. __decorate([
  75962. BABYLON.serialize()
  75963. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  75964. __decorate([
  75965. BABYLON.serialize()
  75966. ], SSAORenderingPipeline.prototype, "base", void 0);
  75967. return SSAORenderingPipeline;
  75968. }(BABYLON.PostProcessRenderPipeline));
  75969. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  75970. })(BABYLON || (BABYLON = {}));
  75971. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  75972. var BABYLON;
  75973. (function (BABYLON) {
  75974. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  75975. __extends(SSAO2RenderingPipeline, _super);
  75976. /**
  75977. * @constructor
  75978. * @param {string} name - The rendering pipeline name
  75979. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75980. * @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 }
  75981. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75982. */
  75983. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  75984. var _this = _super.call(this, scene.getEngine(), name) || this;
  75985. // Members
  75986. /**
  75987. * The PassPostProcess id in the pipeline that contains the original scene color
  75988. */
  75989. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75990. /**
  75991. * The SSAO PostProcess id in the pipeline
  75992. */
  75993. _this.SSAORenderEffect = "SSAORenderEffect";
  75994. /**
  75995. * The horizontal blur PostProcess id in the pipeline
  75996. */
  75997. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75998. /**
  75999. * The vertical blur PostProcess id in the pipeline
  76000. */
  76001. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  76002. /**
  76003. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  76004. */
  76005. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  76006. /**
  76007. * The output strength of the SSAO post-process. Default value is 1.0.
  76008. */
  76009. _this.totalStrength = 1.0;
  76010. /**
  76011. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  76012. */
  76013. _this.maxZ = 100.0;
  76014. /**
  76015. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  76016. */
  76017. _this.minZAspect = 0.2;
  76018. /**
  76019. * Number of samples used for the SSAO calculations. Default value is 8
  76020. */
  76021. _this._samples = 8;
  76022. /**
  76023. * Are we using bilateral blur ?
  76024. */
  76025. _this._expensiveBlur = true;
  76026. /**
  76027. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  76028. */
  76029. _this.radius = 2.0;
  76030. /**
  76031. * The base color of the SSAO post-process
  76032. * The final result is "base + ssao" between [0, 1]
  76033. */
  76034. _this.base = 0.1;
  76035. _this._firstUpdate = true;
  76036. _this._scene = scene;
  76037. _this._ratio = ratio;
  76038. if (!_this.isSupported) {
  76039. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  76040. return _this;
  76041. }
  76042. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  76043. var blurRatio = _this._ratio.blurRatio || ratio;
  76044. // Set up assets
  76045. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  76046. _this._createRandomTexture();
  76047. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  76048. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  76049. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  76050. _this._createSSAOPostProcess(1.0);
  76051. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  76052. _this._createSSAOCombinePostProcess(blurRatio);
  76053. // Set up pipeline
  76054. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  76055. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  76056. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  76057. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  76058. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  76059. // Finish
  76060. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76061. if (cameras)
  76062. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  76063. return _this;
  76064. }
  76065. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  76066. get: function () {
  76067. return this._samples;
  76068. },
  76069. set: function (n) {
  76070. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  76071. this._samples = n;
  76072. this._sampleSphere = this._generateHemisphere();
  76073. this._firstUpdate = true;
  76074. },
  76075. enumerable: true,
  76076. configurable: true
  76077. });
  76078. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  76079. get: function () {
  76080. return this._expensiveBlur;
  76081. },
  76082. set: function (b) {
  76083. 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"]);
  76084. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  76085. this._expensiveBlur = b;
  76086. this._firstUpdate = true;
  76087. },
  76088. enumerable: true,
  76089. configurable: true
  76090. });
  76091. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  76092. /**
  76093. * Support test.
  76094. */
  76095. get: function () {
  76096. var engine = BABYLON.Engine.LastCreatedEngine;
  76097. if (!engine) {
  76098. return false;
  76099. }
  76100. return engine.getCaps().drawBuffersExtension;
  76101. },
  76102. enumerable: true,
  76103. configurable: true
  76104. });
  76105. // Public Methods
  76106. /**
  76107. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  76108. */
  76109. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  76110. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  76111. for (var i = 0; i < this._scene.cameras.length; i++) {
  76112. var camera = this._scene.cameras[i];
  76113. this._originalColorPostProcess.dispose(camera);
  76114. this._ssaoPostProcess.dispose(camera);
  76115. this._blurHPostProcess.dispose(camera);
  76116. this._blurVPostProcess.dispose(camera);
  76117. this._ssaoCombinePostProcess.dispose(camera);
  76118. }
  76119. this._randomTexture.dispose();
  76120. if (disableGeometryBufferRenderer)
  76121. this._scene.disableGeometryBufferRenderer();
  76122. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  76123. _super.prototype.dispose.call(this);
  76124. };
  76125. // Private Methods
  76126. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  76127. var _this = this;
  76128. this._samplerOffsets = [];
  76129. var expensive = this.expensiveBlur;
  76130. for (var i = -8; i < 8; i++) {
  76131. this._samplerOffsets.push(i * 2 + 0.5);
  76132. }
  76133. 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");
  76134. this._blurHPostProcess.onApply = function (effect) {
  76135. if (!_this._scene.activeCamera) {
  76136. return;
  76137. }
  76138. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  76139. effect.setFloat("near", _this._scene.activeCamera.minZ);
  76140. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  76141. effect.setFloat("radius", _this.radius);
  76142. effect.setTexture("depthSampler", _this._depthTexture);
  76143. if (_this._firstUpdate) {
  76144. effect.setArray("samplerOffsets", _this._samplerOffsets);
  76145. }
  76146. };
  76147. 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");
  76148. this._blurVPostProcess.onApply = function (effect) {
  76149. if (!_this._scene.activeCamera) {
  76150. return;
  76151. }
  76152. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  76153. effect.setFloat("near", _this._scene.activeCamera.minZ);
  76154. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  76155. effect.setFloat("radius", _this.radius);
  76156. effect.setTexture("depthSampler", _this._depthTexture);
  76157. if (_this._firstUpdate) {
  76158. effect.setArray("samplerOffsets", _this._samplerOffsets);
  76159. _this._firstUpdate = false;
  76160. }
  76161. };
  76162. };
  76163. SSAO2RenderingPipeline.prototype._rebuild = function () {
  76164. this._firstUpdate = true;
  76165. _super.prototype._rebuild.call(this);
  76166. };
  76167. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  76168. var numSamples = this.samples;
  76169. var result = [];
  76170. var vector, scale;
  76171. var rand = function (min, max) {
  76172. return Math.random() * (max - min) + min;
  76173. };
  76174. var i = 0;
  76175. while (i < numSamples) {
  76176. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  76177. vector.normalize();
  76178. scale = i / numSamples;
  76179. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  76180. vector.scaleInPlace(scale);
  76181. result.push(vector.x, vector.y, vector.z);
  76182. i++;
  76183. }
  76184. return result;
  76185. };
  76186. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  76187. var _this = this;
  76188. var numSamples = this.samples;
  76189. this._sampleSphere = this._generateHemisphere();
  76190. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  76191. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  76192. "base", "range", "projection", "near", "far", "texelSize",
  76193. "xViewport", "yViewport", "maxZ", "minZAspect"
  76194. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  76195. this._ssaoPostProcess.onApply = function (effect) {
  76196. if (_this._firstUpdate) {
  76197. effect.setArray3("sampleSphere", _this._sampleSphere);
  76198. effect.setFloat("randTextureTiles", 4.0);
  76199. }
  76200. if (!_this._scene.activeCamera) {
  76201. return;
  76202. }
  76203. effect.setFloat("samplesFactor", 1 / _this.samples);
  76204. effect.setFloat("totalStrength", _this.totalStrength);
  76205. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  76206. effect.setFloat("radius", _this.radius);
  76207. effect.setFloat("maxZ", _this.maxZ);
  76208. effect.setFloat("minZAspect", _this.minZAspect);
  76209. effect.setFloat("base", _this.base);
  76210. effect.setFloat("near", _this._scene.activeCamera.minZ);
  76211. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  76212. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  76213. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  76214. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  76215. effect.setTexture("textureSampler", _this._depthTexture);
  76216. effect.setTexture("normalSampler", _this._normalTexture);
  76217. effect.setTexture("randomSampler", _this._randomTexture);
  76218. };
  76219. };
  76220. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  76221. var _this = this;
  76222. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76223. this._ssaoCombinePostProcess.onApply = function (effect) {
  76224. var viewport = _this._scene.activeCamera.viewport;
  76225. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  76226. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  76227. };
  76228. };
  76229. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  76230. var size = 512;
  76231. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76232. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  76233. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  76234. var context = this._randomTexture.getContext();
  76235. var rand = function (min, max) {
  76236. return Math.random() * (max - min) + min;
  76237. };
  76238. var randVector = BABYLON.Vector3.Zero();
  76239. for (var x = 0; x < size; x++) {
  76240. for (var y = 0; y < size; y++) {
  76241. randVector.x = rand(0.0, 1.0);
  76242. randVector.y = rand(0.0, 1.0);
  76243. randVector.z = 0.0;
  76244. randVector.normalize();
  76245. randVector.scaleInPlace(255);
  76246. randVector.x = Math.floor(randVector.x);
  76247. randVector.y = Math.floor(randVector.y);
  76248. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  76249. context.fillRect(x, y, 1, 1);
  76250. }
  76251. }
  76252. this._randomTexture.update(false);
  76253. };
  76254. /**
  76255. * Serialize the rendering pipeline (Used when exporting)
  76256. * @returns the serialized object
  76257. */
  76258. SSAO2RenderingPipeline.prototype.serialize = function () {
  76259. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76260. serializationObject.customType = "SSAO2RenderingPipeline";
  76261. return serializationObject;
  76262. };
  76263. /**
  76264. * Parse the serialized pipeline
  76265. * @param source Source pipeline.
  76266. * @param scene The scene to load the pipeline to.
  76267. * @param rootUrl The URL of the serialized pipeline.
  76268. * @returns An instantiated pipeline from the serialized object.
  76269. */
  76270. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  76271. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  76272. };
  76273. __decorate([
  76274. BABYLON.serialize()
  76275. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  76276. __decorate([
  76277. BABYLON.serialize()
  76278. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  76279. __decorate([
  76280. BABYLON.serialize()
  76281. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  76282. __decorate([
  76283. BABYLON.serialize("samples")
  76284. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  76285. __decorate([
  76286. BABYLON.serialize()
  76287. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  76288. __decorate([
  76289. BABYLON.serialize("expensiveBlur")
  76290. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  76291. __decorate([
  76292. BABYLON.serialize()
  76293. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  76294. __decorate([
  76295. BABYLON.serialize()
  76296. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  76297. return SSAO2RenderingPipeline;
  76298. }(BABYLON.PostProcessRenderPipeline));
  76299. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  76300. })(BABYLON || (BABYLON = {}));
  76301. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  76302. // BABYLON.JS Chromatic Aberration GLSL Shader
  76303. // Author: Olivier Guyot
  76304. // Separates very slightly R, G and B colors on the edges of the screen
  76305. // Inspired by Francois Tarlier & Martins Upitis
  76306. var BABYLON;
  76307. (function (BABYLON) {
  76308. var LensRenderingPipeline = /** @class */ (function (_super) {
  76309. __extends(LensRenderingPipeline, _super);
  76310. /**
  76311. * @constructor
  76312. *
  76313. * Effect parameters are as follow:
  76314. * {
  76315. * chromatic_aberration: number; // from 0 to x (1 for realism)
  76316. * edge_blur: number; // from 0 to x (1 for realism)
  76317. * distortion: number; // from 0 to x (1 for realism)
  76318. * grain_amount: number; // from 0 to 1
  76319. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  76320. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  76321. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  76322. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  76323. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  76324. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  76325. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  76326. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  76327. * }
  76328. * Note: if an effect parameter is unset, effect is disabled
  76329. *
  76330. * @param {string} name - The rendering pipeline name
  76331. * @param {object} parameters - An object containing all parameters (see above)
  76332. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76333. * @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)
  76334. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76335. */
  76336. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  76337. if (ratio === void 0) { ratio = 1.0; }
  76338. var _this = _super.call(this, scene.getEngine(), name) || this;
  76339. // Lens effects can be of the following:
  76340. // - chromatic aberration (slight shift of RGB colors)
  76341. // - blur on the edge of the lens
  76342. // - lens distortion
  76343. // - depth-of-field blur & highlights enhancing
  76344. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  76345. // - grain effect (noise or custom texture)
  76346. // Two additional texture samplers are needed:
  76347. // - depth map (for depth-of-field)
  76348. // - grain texture
  76349. /**
  76350. * The chromatic aberration PostProcess id in the pipeline
  76351. */
  76352. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  76353. /**
  76354. * The highlights enhancing PostProcess id in the pipeline
  76355. */
  76356. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  76357. /**
  76358. * The depth-of-field PostProcess id in the pipeline
  76359. */
  76360. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  76361. _this._scene = scene;
  76362. // Fetch texture samplers
  76363. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  76364. if (parameters.grain_texture) {
  76365. _this._grainTexture = parameters.grain_texture;
  76366. }
  76367. else {
  76368. _this._createGrainTexture();
  76369. }
  76370. // save parameters
  76371. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  76372. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  76373. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  76374. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  76375. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  76376. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  76377. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  76378. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  76379. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  76380. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  76381. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  76382. // Create effects
  76383. _this._createChromaticAberrationPostProcess(ratio);
  76384. _this._createHighlightsPostProcess(ratio);
  76385. _this._createDepthOfFieldPostProcess(ratio / 4);
  76386. // Set up pipeline
  76387. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  76388. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  76389. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  76390. if (_this._highlightsGain === -1) {
  76391. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  76392. }
  76393. // Finish
  76394. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76395. if (cameras) {
  76396. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  76397. }
  76398. return _this;
  76399. }
  76400. // public methods (self explanatory)
  76401. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  76402. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  76403. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  76404. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  76405. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  76406. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  76407. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  76408. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  76409. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  76410. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  76411. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  76412. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  76413. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  76414. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  76415. };
  76416. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  76417. this._highlightsPostProcess.updateEffect();
  76418. };
  76419. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  76420. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  76421. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  76422. this._highlightsGain = amount;
  76423. };
  76424. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  76425. if (this._highlightsGain === -1) {
  76426. this._highlightsGain = 1.0;
  76427. }
  76428. this._highlightsThreshold = amount;
  76429. };
  76430. LensRenderingPipeline.prototype.disableHighlights = function () {
  76431. this._highlightsGain = -1;
  76432. };
  76433. /**
  76434. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  76435. */
  76436. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  76437. if (disableDepthRender === void 0) { disableDepthRender = false; }
  76438. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  76439. this._chromaticAberrationPostProcess = null;
  76440. this._highlightsPostProcess = null;
  76441. this._depthOfFieldPostProcess = null;
  76442. this._grainTexture.dispose();
  76443. if (disableDepthRender)
  76444. this._scene.disableDepthRenderer();
  76445. };
  76446. // colors shifting and distortion
  76447. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  76448. var _this = this;
  76449. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  76450. [], // samplers
  76451. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76452. this._chromaticAberrationPostProcess.onApply = function (effect) {
  76453. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  76454. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  76455. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  76456. effect.setFloat('radialIntensity', 1);
  76457. effect.setFloat2('direction', 17, 17);
  76458. effect.setFloat2('centerPosition', 0.5, 0.5);
  76459. };
  76460. };
  76461. // highlights enhancing
  76462. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  76463. var _this = this;
  76464. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  76465. [], // samplers
  76466. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  76467. this._highlightsPostProcess.onApply = function (effect) {
  76468. effect.setFloat('gain', _this._highlightsGain);
  76469. effect.setFloat('threshold', _this._highlightsThreshold);
  76470. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  76471. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  76472. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  76473. };
  76474. };
  76475. // colors shifting and distortion
  76476. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  76477. var _this = this;
  76478. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  76479. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  76480. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  76481. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76482. this._depthOfFieldPostProcess.onApply = function (effect) {
  76483. effect.setTexture("depthSampler", _this._depthTexture);
  76484. effect.setTexture("grainSampler", _this._grainTexture);
  76485. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  76486. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  76487. effect.setFloat('grain_amount', _this._grainAmount);
  76488. effect.setBool('blur_noise', _this._blurNoise);
  76489. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  76490. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  76491. effect.setFloat('distortion', _this._distortion);
  76492. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  76493. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  76494. effect.setFloat('aperture', _this._dofAperture);
  76495. effect.setFloat('darken', _this._dofDarken);
  76496. effect.setFloat('edge_blur', _this._edgeBlur);
  76497. effect.setBool('highlights', (_this._highlightsGain !== -1));
  76498. if (_this._scene.activeCamera) {
  76499. effect.setFloat('near', _this._scene.activeCamera.minZ);
  76500. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  76501. }
  76502. };
  76503. };
  76504. // creates a black and white random noise texture, 512x512
  76505. LensRenderingPipeline.prototype._createGrainTexture = function () {
  76506. var size = 512;
  76507. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76508. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  76509. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  76510. var context = this._grainTexture.getContext();
  76511. var rand = function (min, max) {
  76512. return Math.random() * (max - min) + min;
  76513. };
  76514. var value;
  76515. for (var x = 0; x < size; x++) {
  76516. for (var y = 0; y < size; y++) {
  76517. value = Math.floor(rand(0.42, 0.58) * 255);
  76518. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  76519. context.fillRect(x, y, 1, 1);
  76520. }
  76521. }
  76522. this._grainTexture.update(false);
  76523. };
  76524. return LensRenderingPipeline;
  76525. }(BABYLON.PostProcessRenderPipeline));
  76526. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  76527. })(BABYLON || (BABYLON = {}));
  76528. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  76529. var BABYLON;
  76530. (function (BABYLON) {
  76531. var StandardRenderingPipeline = /** @class */ (function (_super) {
  76532. __extends(StandardRenderingPipeline, _super);
  76533. /**
  76534. * @constructor
  76535. * @param {string} name - The rendering pipeline name
  76536. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76537. * @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)
  76538. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  76539. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76540. */
  76541. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  76542. if (originalPostProcess === void 0) { originalPostProcess = null; }
  76543. var _this = _super.call(this, scene.getEngine(), name) || this;
  76544. _this.downSampleX4PostProcess = null;
  76545. _this.brightPassPostProcess = null;
  76546. _this.blurHPostProcesses = [];
  76547. _this.blurVPostProcesses = [];
  76548. _this.textureAdderPostProcess = null;
  76549. _this.volumetricLightPostProcess = null;
  76550. _this.volumetricLightSmoothXPostProcess = null;
  76551. _this.volumetricLightSmoothYPostProcess = null;
  76552. _this.volumetricLightMergePostProces = null;
  76553. _this.volumetricLightFinalPostProcess = null;
  76554. _this.luminancePostProcess = null;
  76555. _this.luminanceDownSamplePostProcesses = [];
  76556. _this.hdrPostProcess = null;
  76557. _this.textureAdderFinalPostProcess = null;
  76558. _this.lensFlareFinalPostProcess = null;
  76559. _this.hdrFinalPostProcess = null;
  76560. _this.lensFlarePostProcess = null;
  76561. _this.lensFlareComposePostProcess = null;
  76562. _this.motionBlurPostProcess = null;
  76563. _this.depthOfFieldPostProcess = null;
  76564. // Values
  76565. _this.brightThreshold = 1.0;
  76566. _this.blurWidth = 512.0;
  76567. _this.horizontalBlur = false;
  76568. _this.exposure = 1.0;
  76569. _this.lensTexture = null;
  76570. _this.volumetricLightCoefficient = 0.2;
  76571. _this.volumetricLightPower = 4.0;
  76572. _this.volumetricLightBlurScale = 64.0;
  76573. _this.sourceLight = null;
  76574. _this.hdrMinimumLuminance = 1.0;
  76575. _this.hdrDecreaseRate = 0.5;
  76576. _this.hdrIncreaseRate = 0.5;
  76577. _this.lensColorTexture = null;
  76578. _this.lensFlareStrength = 20.0;
  76579. _this.lensFlareGhostDispersal = 1.4;
  76580. _this.lensFlareHaloWidth = 0.7;
  76581. _this.lensFlareDistortionStrength = 16.0;
  76582. _this.lensStarTexture = null;
  76583. _this.lensFlareDirtTexture = null;
  76584. _this.depthOfFieldDistance = 10.0;
  76585. _this.depthOfFieldBlurWidth = 64.0;
  76586. _this.motionStrength = 1.0;
  76587. // IAnimatable
  76588. _this.animations = [];
  76589. _this._currentDepthOfFieldSource = null;
  76590. _this._hdrCurrentLuminance = 1.0;
  76591. // Getters and setters
  76592. _this._bloomEnabled = true;
  76593. _this._depthOfFieldEnabled = false;
  76594. _this._vlsEnabled = false;
  76595. _this._lensFlareEnabled = false;
  76596. _this._hdrEnabled = false;
  76597. _this._motionBlurEnabled = false;
  76598. _this._motionBlurSamples = 64.0;
  76599. _this._volumetricLightStepsCount = 50.0;
  76600. _this._cameras = cameras || [];
  76601. // Initialize
  76602. _this._scene = scene;
  76603. _this._basePostProcess = originalPostProcess;
  76604. _this._ratio = ratio;
  76605. // Misc
  76606. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76607. // Finish
  76608. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76609. _this._buildPipeline();
  76610. return _this;
  76611. }
  76612. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  76613. get: function () {
  76614. return this._bloomEnabled;
  76615. },
  76616. set: function (enabled) {
  76617. if (this._bloomEnabled === enabled) {
  76618. return;
  76619. }
  76620. this._bloomEnabled = enabled;
  76621. this._buildPipeline();
  76622. },
  76623. enumerable: true,
  76624. configurable: true
  76625. });
  76626. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  76627. get: function () {
  76628. return this._depthOfFieldEnabled;
  76629. },
  76630. set: function (enabled) {
  76631. if (this._depthOfFieldEnabled === enabled) {
  76632. return;
  76633. }
  76634. this._depthOfFieldEnabled = enabled;
  76635. this._buildPipeline();
  76636. },
  76637. enumerable: true,
  76638. configurable: true
  76639. });
  76640. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  76641. get: function () {
  76642. return this._lensFlareEnabled;
  76643. },
  76644. set: function (enabled) {
  76645. if (this._lensFlareEnabled === enabled) {
  76646. return;
  76647. }
  76648. this._lensFlareEnabled = enabled;
  76649. this._buildPipeline();
  76650. },
  76651. enumerable: true,
  76652. configurable: true
  76653. });
  76654. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  76655. get: function () {
  76656. return this._hdrEnabled;
  76657. },
  76658. set: function (enabled) {
  76659. if (this._hdrEnabled === enabled) {
  76660. return;
  76661. }
  76662. this._hdrEnabled = enabled;
  76663. this._buildPipeline();
  76664. },
  76665. enumerable: true,
  76666. configurable: true
  76667. });
  76668. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  76669. get: function () {
  76670. return this._vlsEnabled;
  76671. },
  76672. set: function (enabled) {
  76673. if (this._vlsEnabled === enabled) {
  76674. return;
  76675. }
  76676. if (enabled) {
  76677. var geometry = this._scene.enableGeometryBufferRenderer();
  76678. if (!geometry) {
  76679. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  76680. return;
  76681. }
  76682. }
  76683. this._vlsEnabled = enabled;
  76684. this._buildPipeline();
  76685. },
  76686. enumerable: true,
  76687. configurable: true
  76688. });
  76689. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  76690. get: function () {
  76691. return this._motionBlurEnabled;
  76692. },
  76693. set: function (enabled) {
  76694. if (this._motionBlurEnabled === enabled) {
  76695. return;
  76696. }
  76697. this._motionBlurEnabled = enabled;
  76698. this._buildPipeline();
  76699. },
  76700. enumerable: true,
  76701. configurable: true
  76702. });
  76703. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  76704. get: function () {
  76705. return this._volumetricLightStepsCount;
  76706. },
  76707. set: function (count) {
  76708. if (this.volumetricLightPostProcess) {
  76709. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  76710. }
  76711. this._volumetricLightStepsCount = count;
  76712. },
  76713. enumerable: true,
  76714. configurable: true
  76715. });
  76716. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  76717. get: function () {
  76718. return this._motionBlurSamples;
  76719. },
  76720. set: function (samples) {
  76721. if (this.motionBlurPostProcess) {
  76722. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  76723. }
  76724. this._motionBlurSamples = samples;
  76725. },
  76726. enumerable: true,
  76727. configurable: true
  76728. });
  76729. StandardRenderingPipeline.prototype._buildPipeline = function () {
  76730. var _this = this;
  76731. var ratio = this._ratio;
  76732. var scene = this._scene;
  76733. this._disposePostProcesses();
  76734. this._reset();
  76735. // Create pass post-process
  76736. if (!this._basePostProcess) {
  76737. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  76738. this.originalPostProcess.onApply = function (effect) {
  76739. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  76740. };
  76741. }
  76742. else {
  76743. this.originalPostProcess = this._basePostProcess;
  76744. }
  76745. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  76746. this._currentDepthOfFieldSource = this.originalPostProcess;
  76747. if (this._bloomEnabled) {
  76748. // Create down sample X4 post-process
  76749. this._createDownSampleX4PostProcess(scene, ratio / 2);
  76750. // Create bright pass post-process
  76751. this._createBrightPassPostProcess(scene, ratio / 2);
  76752. // Create gaussian blur post-processes (down sampling blurs)
  76753. this._createBlurPostProcesses(scene, ratio / 4, 1);
  76754. // Create texture adder post-process
  76755. this._createTextureAdderPostProcess(scene, ratio);
  76756. // Create depth-of-field source post-process
  76757. 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);
  76758. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  76759. }
  76760. if (this._vlsEnabled) {
  76761. // Create volumetric light
  76762. this._createVolumetricLightPostProcess(scene, ratio);
  76763. // Create volumetric light final post-process
  76764. 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);
  76765. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  76766. }
  76767. if (this._lensFlareEnabled) {
  76768. // Create lens flare post-process
  76769. this._createLensFlarePostProcess(scene, ratio);
  76770. // Create depth-of-field source post-process post lens-flare and disable it now
  76771. 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);
  76772. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  76773. }
  76774. if (this._hdrEnabled) {
  76775. // Create luminance
  76776. this._createLuminancePostProcesses(scene, this._floatTextureType);
  76777. // Create HDR
  76778. this._createHdrPostProcess(scene, ratio);
  76779. // Create depth-of-field source post-process post hdr and disable it now
  76780. 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);
  76781. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  76782. }
  76783. if (this._depthOfFieldEnabled) {
  76784. // Create gaussian blur used by depth-of-field
  76785. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  76786. // Create depth-of-field post-process
  76787. this._createDepthOfFieldPostProcess(scene, ratio);
  76788. }
  76789. if (this._motionBlurEnabled) {
  76790. // Create motion blur post-process
  76791. this._createMotionBlurPostProcess(scene, ratio);
  76792. }
  76793. if (this._cameras !== null) {
  76794. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76795. }
  76796. };
  76797. // Down Sample X4 Post-Processs
  76798. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  76799. var _this = this;
  76800. var downSampleX4Offsets = new Array(32);
  76801. 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);
  76802. this.downSampleX4PostProcess.onApply = function (effect) {
  76803. var id = 0;
  76804. var width = _this.downSampleX4PostProcess.width;
  76805. var height = _this.downSampleX4PostProcess.height;
  76806. for (var i = -2; i < 2; i++) {
  76807. for (var j = -2; j < 2; j++) {
  76808. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  76809. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  76810. id += 2;
  76811. }
  76812. }
  76813. effect.setArray2("dsOffsets", downSampleX4Offsets);
  76814. };
  76815. // Add to pipeline
  76816. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  76817. };
  76818. // Brightpass Post-Process
  76819. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  76820. var _this = this;
  76821. var brightOffsets = new Array(8);
  76822. 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);
  76823. this.brightPassPostProcess.onApply = function (effect) {
  76824. var sU = (1.0 / _this.brightPassPostProcess.width);
  76825. var sV = (1.0 / _this.brightPassPostProcess.height);
  76826. brightOffsets[0] = -0.5 * sU;
  76827. brightOffsets[1] = 0.5 * sV;
  76828. brightOffsets[2] = 0.5 * sU;
  76829. brightOffsets[3] = 0.5 * sV;
  76830. brightOffsets[4] = -0.5 * sU;
  76831. brightOffsets[5] = -0.5 * sV;
  76832. brightOffsets[6] = 0.5 * sU;
  76833. brightOffsets[7] = -0.5 * sV;
  76834. effect.setArray2("dsOffsets", brightOffsets);
  76835. effect.setFloat("brightThreshold", _this.brightThreshold);
  76836. };
  76837. // Add to pipeline
  76838. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  76839. };
  76840. // Create blur H&V post-processes
  76841. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  76842. var _this = this;
  76843. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  76844. var engine = scene.getEngine();
  76845. 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);
  76846. 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);
  76847. blurX.onActivateObservable.add(function () {
  76848. var dw = blurX.width / engine.getRenderWidth();
  76849. blurX.kernel = _this[blurWidthKey] * dw;
  76850. });
  76851. blurY.onActivateObservable.add(function () {
  76852. var dw = blurY.height / engine.getRenderHeight();
  76853. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  76854. });
  76855. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  76856. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  76857. this.blurHPostProcesses.push(blurX);
  76858. this.blurVPostProcesses.push(blurY);
  76859. };
  76860. // Create texture adder post-process
  76861. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  76862. var _this = this;
  76863. 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);
  76864. this.textureAdderPostProcess.onApply = function (effect) {
  76865. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  76866. effect.setTexture("lensSampler", _this.lensTexture);
  76867. effect.setFloat("exposure", _this.exposure);
  76868. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  76869. };
  76870. // Add to pipeline
  76871. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  76872. };
  76873. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  76874. var _this = this;
  76875. var geometryRenderer = scene.enableGeometryBufferRenderer();
  76876. geometryRenderer.enablePosition = true;
  76877. var geometry = geometryRenderer.getGBuffer();
  76878. // Base post-process
  76879. 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));
  76880. var depthValues = BABYLON.Vector2.Zero();
  76881. this.volumetricLightPostProcess.onApply = function (effect) {
  76882. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  76883. var generator = _this.sourceLight.getShadowGenerator();
  76884. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  76885. effect.setTexture("positionSampler", geometry.textures[2]);
  76886. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  76887. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  76888. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  76889. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  76890. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  76891. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  76892. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  76893. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  76894. effect.setVector2("depthValues", depthValues);
  76895. }
  76896. };
  76897. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  76898. // Smooth
  76899. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  76900. // Merge
  76901. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  76902. this.volumetricLightMergePostProces.onApply = function (effect) {
  76903. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  76904. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  76905. };
  76906. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  76907. };
  76908. // Create luminance
  76909. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  76910. var _this = this;
  76911. // Create luminance
  76912. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  76913. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  76914. var offsets = [];
  76915. this.luminancePostProcess.onApply = function (effect) {
  76916. var sU = (1.0 / _this.luminancePostProcess.width);
  76917. var sV = (1.0 / _this.luminancePostProcess.height);
  76918. offsets[0] = -0.5 * sU;
  76919. offsets[1] = 0.5 * sV;
  76920. offsets[2] = 0.5 * sU;
  76921. offsets[3] = 0.5 * sV;
  76922. offsets[4] = -0.5 * sU;
  76923. offsets[5] = -0.5 * sV;
  76924. offsets[6] = 0.5 * sU;
  76925. offsets[7] = -0.5 * sV;
  76926. effect.setArray2("lumOffsets", offsets);
  76927. };
  76928. // Add to pipeline
  76929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  76930. // Create down sample luminance
  76931. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  76932. var size = Math.pow(3, i);
  76933. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  76934. if (i === 0) {
  76935. defines += "#define FINAL_DOWN_SAMPLER";
  76936. }
  76937. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  76938. this.luminanceDownSamplePostProcesses.push(postProcess);
  76939. }
  76940. // Create callbacks and add effects
  76941. var lastLuminance = this.luminancePostProcess;
  76942. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  76943. var downSampleOffsets = new Array(18);
  76944. pp.onApply = function (effect) {
  76945. if (!lastLuminance) {
  76946. return;
  76947. }
  76948. var id = 0;
  76949. for (var x = -1; x < 2; x++) {
  76950. for (var y = -1; y < 2; y++) {
  76951. downSampleOffsets[id] = x / lastLuminance.width;
  76952. downSampleOffsets[id + 1] = y / lastLuminance.height;
  76953. id += 2;
  76954. }
  76955. }
  76956. effect.setArray2("dsOffsets", downSampleOffsets);
  76957. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  76958. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76959. lastLuminance = _this.luminancePostProcess;
  76960. }
  76961. else {
  76962. lastLuminance = pp;
  76963. }
  76964. };
  76965. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76966. pp.onAfterRender = function (effect) {
  76967. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  76968. 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);
  76969. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  76970. };
  76971. }
  76972. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  76973. });
  76974. };
  76975. // Create HDR post-process
  76976. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  76977. var _this = this;
  76978. 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);
  76979. var outputLiminance = 1;
  76980. var time = 0;
  76981. var lastTime = 0;
  76982. this.hdrPostProcess.onApply = function (effect) {
  76983. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  76984. time += scene.getEngine().getDeltaTime();
  76985. if (outputLiminance < 0) {
  76986. outputLiminance = _this._hdrCurrentLuminance;
  76987. }
  76988. else {
  76989. var dt = (lastTime - time) / 1000.0;
  76990. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  76991. outputLiminance += _this.hdrDecreaseRate * dt;
  76992. }
  76993. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  76994. outputLiminance -= _this.hdrIncreaseRate * dt;
  76995. }
  76996. else {
  76997. outputLiminance = _this._hdrCurrentLuminance;
  76998. }
  76999. }
  77000. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  77001. effect.setFloat("averageLuminance", outputLiminance);
  77002. lastTime = time;
  77003. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  77004. };
  77005. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  77006. };
  77007. // Create lens flare post-process
  77008. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  77009. var _this = this;
  77010. 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);
  77011. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  77012. this._createBlurPostProcesses(scene, ratio / 4, 2);
  77013. 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);
  77014. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  77015. var resolution = new BABYLON.Vector2(0, 0);
  77016. // Lens flare
  77017. this.lensFlarePostProcess.onApply = function (effect) {
  77018. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  77019. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  77020. effect.setFloat("strength", _this.lensFlareStrength);
  77021. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  77022. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  77023. // Shift
  77024. resolution.x = _this.lensFlarePostProcess.width;
  77025. resolution.y = _this.lensFlarePostProcess.height;
  77026. effect.setVector2("resolution", resolution);
  77027. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  77028. };
  77029. // Compose
  77030. 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);
  77031. 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);
  77032. this.lensFlareComposePostProcess.onApply = function (effect) {
  77033. if (!_this._scene.activeCamera) {
  77034. return;
  77035. }
  77036. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  77037. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  77038. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  77039. // Lens start rotation matrix
  77040. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  77041. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  77042. 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));
  77043. camRot *= 4.0;
  77044. 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);
  77045. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  77046. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  77047. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  77048. };
  77049. };
  77050. // Create depth-of-field post-process
  77051. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  77052. var _this = this;
  77053. 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);
  77054. this.depthOfFieldPostProcess.onApply = function (effect) {
  77055. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  77056. effect.setTexture("depthSampler", _this._getDepthTexture());
  77057. effect.setFloat("distance", _this.depthOfFieldDistance);
  77058. };
  77059. // Add to pipeline
  77060. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  77061. };
  77062. // Create motion blur post-process
  77063. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  77064. var _this = this;
  77065. 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);
  77066. var motionScale = 0;
  77067. var prevViewProjection = BABYLON.Matrix.Identity();
  77068. var invViewProjection = BABYLON.Matrix.Identity();
  77069. var viewProjection = BABYLON.Matrix.Identity();
  77070. var screenSize = BABYLON.Vector2.Zero();
  77071. this.motionBlurPostProcess.onApply = function (effect) {
  77072. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  77073. viewProjection.invertToRef(invViewProjection);
  77074. effect.setMatrix("inverseViewProjection", invViewProjection);
  77075. effect.setMatrix("prevViewProjection", prevViewProjection);
  77076. prevViewProjection = viewProjection;
  77077. screenSize.x = _this.motionBlurPostProcess.width;
  77078. screenSize.y = _this.motionBlurPostProcess.height;
  77079. effect.setVector2("screenSize", screenSize);
  77080. motionScale = scene.getEngine().getFps() / 60.0;
  77081. effect.setFloat("motionScale", motionScale);
  77082. effect.setFloat("motionStrength", _this.motionStrength);
  77083. effect.setTexture("depthSampler", _this._getDepthTexture());
  77084. };
  77085. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  77086. };
  77087. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  77088. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  77089. var renderer = this._scene.enableGeometryBufferRenderer();
  77090. return renderer.getGBuffer().textures[0];
  77091. }
  77092. return this._scene.enableDepthRenderer().getDepthMap();
  77093. };
  77094. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  77095. for (var i = 0; i < this._cameras.length; i++) {
  77096. var camera = this._cameras[i];
  77097. if (this.originalPostProcess) {
  77098. this.originalPostProcess.dispose(camera);
  77099. }
  77100. if (this.downSampleX4PostProcess) {
  77101. this.downSampleX4PostProcess.dispose(camera);
  77102. }
  77103. if (this.brightPassPostProcess) {
  77104. this.brightPassPostProcess.dispose(camera);
  77105. }
  77106. if (this.textureAdderPostProcess) {
  77107. this.textureAdderPostProcess.dispose(camera);
  77108. }
  77109. if (this.textureAdderFinalPostProcess) {
  77110. this.textureAdderFinalPostProcess.dispose(camera);
  77111. }
  77112. if (this.volumetricLightPostProcess) {
  77113. this.volumetricLightPostProcess.dispose(camera);
  77114. }
  77115. if (this.volumetricLightSmoothXPostProcess) {
  77116. this.volumetricLightSmoothXPostProcess.dispose(camera);
  77117. }
  77118. if (this.volumetricLightSmoothYPostProcess) {
  77119. this.volumetricLightSmoothYPostProcess.dispose(camera);
  77120. }
  77121. if (this.volumetricLightMergePostProces) {
  77122. this.volumetricLightMergePostProces.dispose(camera);
  77123. }
  77124. if (this.volumetricLightFinalPostProcess) {
  77125. this.volumetricLightFinalPostProcess.dispose(camera);
  77126. }
  77127. if (this.lensFlarePostProcess) {
  77128. this.lensFlarePostProcess.dispose(camera);
  77129. }
  77130. if (this.lensFlareComposePostProcess) {
  77131. this.lensFlareComposePostProcess.dispose(camera);
  77132. }
  77133. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  77134. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  77135. }
  77136. if (this.luminancePostProcess) {
  77137. this.luminancePostProcess.dispose(camera);
  77138. }
  77139. if (this.hdrPostProcess) {
  77140. this.hdrPostProcess.dispose(camera);
  77141. }
  77142. if (this.hdrFinalPostProcess) {
  77143. this.hdrFinalPostProcess.dispose(camera);
  77144. }
  77145. if (this.depthOfFieldPostProcess) {
  77146. this.depthOfFieldPostProcess.dispose(camera);
  77147. }
  77148. if (this.motionBlurPostProcess) {
  77149. this.motionBlurPostProcess.dispose(camera);
  77150. }
  77151. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  77152. this.blurHPostProcesses[j].dispose(camera);
  77153. }
  77154. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  77155. this.blurVPostProcesses[j].dispose(camera);
  77156. }
  77157. }
  77158. this.originalPostProcess = null;
  77159. this.downSampleX4PostProcess = null;
  77160. this.brightPassPostProcess = null;
  77161. this.textureAdderPostProcess = null;
  77162. this.textureAdderFinalPostProcess = null;
  77163. this.volumetricLightPostProcess = null;
  77164. this.volumetricLightSmoothXPostProcess = null;
  77165. this.volumetricLightSmoothYPostProcess = null;
  77166. this.volumetricLightMergePostProces = null;
  77167. this.volumetricLightFinalPostProcess = null;
  77168. this.lensFlarePostProcess = null;
  77169. this.lensFlareComposePostProcess = null;
  77170. this.luminancePostProcess = null;
  77171. this.hdrPostProcess = null;
  77172. this.hdrFinalPostProcess = null;
  77173. this.depthOfFieldPostProcess = null;
  77174. this.motionBlurPostProcess = null;
  77175. this.luminanceDownSamplePostProcesses = [];
  77176. this.blurHPostProcesses = [];
  77177. this.blurVPostProcesses = [];
  77178. };
  77179. /**
  77180. * Dispose of the pipeline and stop all post processes
  77181. */
  77182. StandardRenderingPipeline.prototype.dispose = function () {
  77183. this._disposePostProcesses();
  77184. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77185. _super.prototype.dispose.call(this);
  77186. };
  77187. /**
  77188. * Serialize the rendering pipeline (Used when exporting)
  77189. * @returns the serialized object
  77190. */
  77191. StandardRenderingPipeline.prototype.serialize = function () {
  77192. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77193. if (this.sourceLight) {
  77194. serializationObject.sourceLightId = this.sourceLight.id;
  77195. }
  77196. serializationObject.customType = "StandardRenderingPipeline";
  77197. return serializationObject;
  77198. };
  77199. /**
  77200. * Parse the serialized pipeline
  77201. * @param source Source pipeline.
  77202. * @param scene The scene to load the pipeline to.
  77203. * @param rootUrl The URL of the serialized pipeline.
  77204. * @returns An instantiated pipeline from the serialized object.
  77205. */
  77206. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  77207. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  77208. if (source.sourceLightId) {
  77209. p.sourceLight = scene.getLightByID(source.sourceLightId);
  77210. }
  77211. return p;
  77212. };
  77213. // Luminance steps
  77214. StandardRenderingPipeline.LuminanceSteps = 6;
  77215. __decorate([
  77216. BABYLON.serialize()
  77217. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  77218. __decorate([
  77219. BABYLON.serialize()
  77220. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  77221. __decorate([
  77222. BABYLON.serialize()
  77223. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  77224. __decorate([
  77225. BABYLON.serialize()
  77226. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  77227. __decorate([
  77228. BABYLON.serializeAsTexture("lensTexture")
  77229. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  77230. __decorate([
  77231. BABYLON.serialize()
  77232. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  77233. __decorate([
  77234. BABYLON.serialize()
  77235. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  77236. __decorate([
  77237. BABYLON.serialize()
  77238. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  77239. __decorate([
  77240. BABYLON.serialize()
  77241. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  77242. __decorate([
  77243. BABYLON.serialize()
  77244. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  77245. __decorate([
  77246. BABYLON.serialize()
  77247. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  77248. __decorate([
  77249. BABYLON.serializeAsTexture("lensColorTexture")
  77250. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  77251. __decorate([
  77252. BABYLON.serialize()
  77253. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  77254. __decorate([
  77255. BABYLON.serialize()
  77256. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  77257. __decorate([
  77258. BABYLON.serialize()
  77259. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  77260. __decorate([
  77261. BABYLON.serialize()
  77262. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  77263. __decorate([
  77264. BABYLON.serializeAsTexture("lensStarTexture")
  77265. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  77266. __decorate([
  77267. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  77268. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  77269. __decorate([
  77270. BABYLON.serialize()
  77271. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  77272. __decorate([
  77273. BABYLON.serialize()
  77274. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  77275. __decorate([
  77276. BABYLON.serialize()
  77277. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  77278. __decorate([
  77279. BABYLON.serialize()
  77280. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  77281. __decorate([
  77282. BABYLON.serialize()
  77283. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  77284. __decorate([
  77285. BABYLON.serialize()
  77286. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  77287. __decorate([
  77288. BABYLON.serialize()
  77289. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  77290. __decorate([
  77291. BABYLON.serialize()
  77292. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  77293. __decorate([
  77294. BABYLON.serialize()
  77295. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  77296. __decorate([
  77297. BABYLON.serialize()
  77298. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  77299. __decorate([
  77300. BABYLON.serialize()
  77301. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  77302. __decorate([
  77303. BABYLON.serialize()
  77304. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  77305. return StandardRenderingPipeline;
  77306. }(BABYLON.PostProcessRenderPipeline));
  77307. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  77308. })(BABYLON || (BABYLON = {}));
  77309. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  77310. var BABYLON;
  77311. (function (BABYLON) {
  77312. var FxaaPostProcess = /** @class */ (function (_super) {
  77313. __extends(FxaaPostProcess, _super);
  77314. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77315. if (camera === void 0) { camera = null; }
  77316. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77317. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  77318. var defines = _this._getDefines();
  77319. _this.updateEffect(defines);
  77320. _this.onApplyObservable.add(function (effect) {
  77321. var texelSize = _this.texelSize;
  77322. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  77323. });
  77324. return _this;
  77325. }
  77326. FxaaPostProcess.prototype._getDefines = function () {
  77327. var engine = this.getEngine();
  77328. if (!engine) {
  77329. return null;
  77330. }
  77331. var glInfo = engine.getGlInfo();
  77332. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  77333. return "#define MALI 1\n";
  77334. }
  77335. return null;
  77336. };
  77337. return FxaaPostProcess;
  77338. }(BABYLON.PostProcess));
  77339. BABYLON.FxaaPostProcess = FxaaPostProcess;
  77340. })(BABYLON || (BABYLON = {}));
  77341. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  77342. var BABYLON;
  77343. (function (BABYLON) {
  77344. /**
  77345. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  77346. */
  77347. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  77348. __extends(ChromaticAberrationPostProcess, _super);
  77349. /**
  77350. * Creates a new instance ChromaticAberrationPostProcess
  77351. * @param name The name of the effect.
  77352. * @param screenWidth The width of the screen to apply the effect on.
  77353. * @param screenHeight The height of the screen to apply the effect on.
  77354. * @param options The required width/height ratio to downsize to before computing the render pass.
  77355. * @param camera The camera to apply the render pass to.
  77356. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77357. * @param engine The engine which the post process will be applied. (default: current engine)
  77358. * @param reusable If the post process can be reused on the same frame. (default: false)
  77359. * @param textureType Type of textures used when performing the post process. (default: 0)
  77360. * @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)
  77361. */
  77362. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77363. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77364. if (blockCompilation === void 0) { blockCompilation = false; }
  77365. 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;
  77366. /**
  77367. * The amount of seperation of rgb channels (default: 30)
  77368. */
  77369. _this.aberrationAmount = 30;
  77370. /**
  77371. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  77372. */
  77373. _this.radialIntensity = 0;
  77374. /**
  77375. * 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))
  77376. */
  77377. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  77378. /**
  77379. * 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))
  77380. */
  77381. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  77382. _this.onApplyObservable.add(function (effect) {
  77383. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  77384. effect.setFloat('screen_width', screenWidth);
  77385. effect.setFloat('screen_height', screenHeight);
  77386. effect.setFloat('radialIntensity', _this.radialIntensity);
  77387. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  77388. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  77389. });
  77390. return _this;
  77391. }
  77392. return ChromaticAberrationPostProcess;
  77393. }(BABYLON.PostProcess));
  77394. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  77395. })(BABYLON || (BABYLON = {}));
  77396. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  77397. var BABYLON;
  77398. (function (BABYLON) {
  77399. /**
  77400. * The GrainPostProcess adds noise to the image at mid luminance levels
  77401. */
  77402. var GrainPostProcess = /** @class */ (function (_super) {
  77403. __extends(GrainPostProcess, _super);
  77404. /**
  77405. * Creates a new instance of @see GrainPostProcess
  77406. * @param name The name of the effect.
  77407. * @param options The required width/height ratio to downsize to before computing the render pass.
  77408. * @param camera The camera to apply the render pass to.
  77409. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77410. * @param engine The engine which the post process will be applied. (default: current engine)
  77411. * @param reusable If the post process can be reused on the same frame. (default: false)
  77412. * @param textureType Type of textures used when performing the post process. (default: 0)
  77413. * @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)
  77414. */
  77415. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77416. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77417. if (blockCompilation === void 0) { blockCompilation = false; }
  77418. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77419. /**
  77420. * The intensity of the grain added (default: 30)
  77421. */
  77422. _this.intensity = 30;
  77423. /**
  77424. * If the grain should be randomized on every frame
  77425. */
  77426. _this.animated = false;
  77427. _this.onApplyObservable.add(function (effect) {
  77428. effect.setFloat('intensity', _this.intensity);
  77429. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  77430. });
  77431. return _this;
  77432. }
  77433. return GrainPostProcess;
  77434. }(BABYLON.PostProcess));
  77435. BABYLON.GrainPostProcess = GrainPostProcess;
  77436. })(BABYLON || (BABYLON = {}));
  77437. //# sourceMappingURL=babylon.grainPostProcess.js.map
  77438. var BABYLON;
  77439. (function (BABYLON) {
  77440. /**
  77441. * The SharpenPostProcess applies a sharpen kernel to every pixel
  77442. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77443. */
  77444. var SharpenPostProcess = /** @class */ (function (_super) {
  77445. __extends(SharpenPostProcess, _super);
  77446. /**
  77447. * Creates a new instance ConvolutionPostProcess
  77448. * @param name The name of the effect.
  77449. * @param options The required width/height ratio to downsize to before computing the render pass.
  77450. * @param camera The camera to apply the render pass to.
  77451. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77452. * @param engine The engine which the post process will be applied. (default: current engine)
  77453. * @param reusable If the post process can be reused on the same frame. (default: false)
  77454. * @param textureType Type of textures used when performing the post process. (default: 0)
  77455. * @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)
  77456. */
  77457. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77458. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77459. if (blockCompilation === void 0) { blockCompilation = false; }
  77460. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77461. /**
  77462. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  77463. */
  77464. _this.colorAmount = 1.0;
  77465. /**
  77466. * How much sharpness should be applied (default: 0.3)
  77467. */
  77468. _this.edgeAmount = 0.3;
  77469. _this.onApply = function (effect) {
  77470. effect.setFloat2("screenSize", _this.width, _this.height);
  77471. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  77472. };
  77473. return _this;
  77474. }
  77475. return SharpenPostProcess;
  77476. }(BABYLON.PostProcess));
  77477. BABYLON.SharpenPostProcess = SharpenPostProcess;
  77478. })(BABYLON || (BABYLON = {}));
  77479. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  77480. var BABYLON;
  77481. (function (BABYLON) {
  77482. /**
  77483. * The Blur Post Process which blurs an image based on a kernel and direction.
  77484. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  77485. */
  77486. var BlurPostProcess = /** @class */ (function (_super) {
  77487. __extends(BlurPostProcess, _super);
  77488. /**
  77489. * Creates a new instance BlurPostProcess
  77490. * @param name The name of the effect.
  77491. * @param direction The direction in which to blur the image.
  77492. * @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.
  77493. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  77494. * @param camera The camera to apply the render pass to.
  77495. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77496. * @param engine The engine which the post process will be applied. (default: current engine)
  77497. * @param reusable If the post process can be reused on the same frame. (default: false)
  77498. * @param textureType Type of textures used when performing the post process. (default: 0)
  77499. * @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)
  77500. */
  77501. function BlurPostProcess(name,
  77502. /** The direction in which to blur the image. */
  77503. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  77504. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77505. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77506. if (defines === void 0) { defines = ""; }
  77507. if (blockCompilation === void 0) { blockCompilation = false; }
  77508. 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;
  77509. _this.direction = direction;
  77510. _this.blockCompilation = blockCompilation;
  77511. _this._packedFloat = false;
  77512. _this._staticDefines = "";
  77513. _this._staticDefines = defines;
  77514. _this.onApplyObservable.add(function (effect) {
  77515. if (_this._outputTexture) {
  77516. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  77517. }
  77518. else {
  77519. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  77520. }
  77521. });
  77522. _this.kernel = kernel;
  77523. return _this;
  77524. }
  77525. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  77526. /**
  77527. * Gets the length in pixels of the blur sample region
  77528. */
  77529. get: function () {
  77530. return this._idealKernel;
  77531. },
  77532. /**
  77533. * Sets the length in pixels of the blur sample region
  77534. */
  77535. set: function (v) {
  77536. if (this._idealKernel === v) {
  77537. return;
  77538. }
  77539. v = Math.max(v, 1);
  77540. this._idealKernel = v;
  77541. this._kernel = this._nearestBestKernel(v);
  77542. if (!this.blockCompilation) {
  77543. this._updateParameters();
  77544. }
  77545. },
  77546. enumerable: true,
  77547. configurable: true
  77548. });
  77549. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  77550. /**
  77551. * Gets wether or not the blur is unpacking/repacking floats
  77552. */
  77553. get: function () {
  77554. return this._packedFloat;
  77555. },
  77556. /**
  77557. * Sets wether or not the blur needs to unpack/repack floats
  77558. */
  77559. set: function (v) {
  77560. if (this._packedFloat === v) {
  77561. return;
  77562. }
  77563. this._packedFloat = v;
  77564. if (!this.blockCompilation) {
  77565. this._updateParameters();
  77566. }
  77567. },
  77568. enumerable: true,
  77569. configurable: true
  77570. });
  77571. /**
  77572. * Updates the effect with the current post process compile time values and recompiles the shader.
  77573. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  77574. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  77575. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  77576. * @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
  77577. * @param onCompiled Called when the shader has been compiled.
  77578. * @param onError Called if there is an error when compiling a shader.
  77579. */
  77580. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  77581. if (defines === void 0) { defines = null; }
  77582. if (uniforms === void 0) { uniforms = null; }
  77583. if (samplers === void 0) { samplers = null; }
  77584. this._updateParameters(onCompiled, onError);
  77585. };
  77586. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  77587. // Generate sampling offsets and weights
  77588. var N = this._kernel;
  77589. var centerIndex = (N - 1) / 2;
  77590. // Generate Gaussian sampling weights over kernel
  77591. var offsets = [];
  77592. var weights = [];
  77593. var totalWeight = 0;
  77594. for (var i = 0; i < N; i++) {
  77595. var u = i / (N - 1);
  77596. var w = this._gaussianWeight(u * 2.0 - 1);
  77597. offsets[i] = (i - centerIndex);
  77598. weights[i] = w;
  77599. totalWeight += w;
  77600. }
  77601. // Normalize weights
  77602. for (var i = 0; i < weights.length; i++) {
  77603. weights[i] /= totalWeight;
  77604. }
  77605. // Optimize: combine samples to take advantage of hardware linear sampling
  77606. // Walk from left to center, combining pairs (symmetrically)
  77607. var linearSamplingWeights = [];
  77608. var linearSamplingOffsets = [];
  77609. var linearSamplingMap = [];
  77610. for (var i = 0; i <= centerIndex; i += 2) {
  77611. var j = Math.min(i + 1, Math.floor(centerIndex));
  77612. var singleCenterSample = i === j;
  77613. if (singleCenterSample) {
  77614. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  77615. }
  77616. else {
  77617. var sharedCell = j === centerIndex;
  77618. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  77619. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  77620. if (offsetLinear === 0) {
  77621. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  77622. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  77623. }
  77624. else {
  77625. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  77626. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  77627. }
  77628. }
  77629. }
  77630. for (var i = 0; i < linearSamplingMap.length; i++) {
  77631. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  77632. linearSamplingWeights[i] = linearSamplingMap[i].w;
  77633. }
  77634. // Replace with optimized
  77635. offsets = linearSamplingOffsets;
  77636. weights = linearSamplingWeights;
  77637. // Generate shaders
  77638. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  77639. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  77640. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  77641. var defines = "";
  77642. defines += this._staticDefines;
  77643. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  77644. if (this._staticDefines.indexOf("DOF") != -1) {
  77645. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  77646. varyingCount--;
  77647. }
  77648. for (var i = 0; i < varyingCount; i++) {
  77649. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  77650. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  77651. }
  77652. var depCount = 0;
  77653. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  77654. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  77655. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  77656. depCount++;
  77657. }
  77658. if (this.packedFloat) {
  77659. defines += "#define PACKEDFLOAT 1";
  77660. }
  77661. this.blockCompilation = false;
  77662. _super.prototype.updateEffect.call(this, defines, null, null, {
  77663. varyingCount: varyingCount,
  77664. depCount: depCount
  77665. }, onCompiled, onError);
  77666. };
  77667. /**
  77668. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  77669. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  77670. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  77671. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  77672. * The gaps between physical kernels are compensated for in the weighting of the samples
  77673. * @param idealKernel Ideal blur kernel.
  77674. * @return Nearest best kernel.
  77675. */
  77676. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  77677. var v = Math.round(idealKernel);
  77678. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  77679. var k = _a[_i];
  77680. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  77681. return Math.max(k, 3);
  77682. }
  77683. }
  77684. return Math.max(v, 3);
  77685. };
  77686. /**
  77687. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  77688. * @param x The point on the Gaussian distribution to sample.
  77689. * @return the value of the Gaussian function at x.
  77690. */
  77691. BlurPostProcess.prototype._gaussianWeight = function (x) {
  77692. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  77693. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  77694. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  77695. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  77696. // truncated at around 1.3% of peak strength.
  77697. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  77698. var sigma = (1 / 3);
  77699. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  77700. var exponent = -((x * x) / (2.0 * sigma * sigma));
  77701. var weight = (1.0 / denominator) * Math.exp(exponent);
  77702. return weight;
  77703. };
  77704. /**
  77705. * Generates a string that can be used as a floating point number in GLSL.
  77706. * @param x Value to print.
  77707. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  77708. * @return GLSL float string.
  77709. */
  77710. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  77711. if (decimalFigures === void 0) { decimalFigures = 8; }
  77712. return x.toFixed(decimalFigures).replace(/0+$/, '');
  77713. };
  77714. return BlurPostProcess;
  77715. }(BABYLON.PostProcess));
  77716. BABYLON.BlurPostProcess = BlurPostProcess;
  77717. })(BABYLON || (BABYLON = {}));
  77718. //# sourceMappingURL=babylon.blurPostProcess.js.map
  77719. var BABYLON;
  77720. (function (BABYLON) {
  77721. /**
  77722. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  77723. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  77724. * based on samples that have a large difference in distance than the center pixel.
  77725. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77726. */
  77727. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  77728. __extends(DepthOfFieldBlurPostProcess, _super);
  77729. /**
  77730. * Creates a new instance CircleOfConfusionPostProcess
  77731. * @param name The name of the effect.
  77732. * @param scene The scene the effect belongs to.
  77733. * @param direction The direction the blur should be applied.
  77734. * @param kernel The size of the kernel used to blur.
  77735. * @param options The required width/height ratio to downsize to before computing the render pass.
  77736. * @param camera The camera to apply the render pass to.
  77737. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  77738. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  77739. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77740. * @param engine The engine which the post process will be applied. (default: current engine)
  77741. * @param reusable If the post process can be reused on the same frame. (default: false)
  77742. * @param textureType Type of textures used when performing the post process. (default: 0)
  77743. * @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)
  77744. */
  77745. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  77746. if (imageToBlur === void 0) { imageToBlur = null; }
  77747. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77748. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77749. if (blockCompilation === void 0) { blockCompilation = false; }
  77750. 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;
  77751. _this.direction = direction;
  77752. _this.onApplyObservable.add(function (effect) {
  77753. if (imageToBlur != null) {
  77754. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  77755. }
  77756. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77757. if (scene.activeCamera) {
  77758. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  77759. }
  77760. });
  77761. return _this;
  77762. }
  77763. return DepthOfFieldBlurPostProcess;
  77764. }(BABYLON.BlurPostProcess));
  77765. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  77766. })(BABYLON || (BABYLON = {}));
  77767. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  77768. var BABYLON;
  77769. (function (BABYLON) {
  77770. /**
  77771. * Options to be set when merging outputs from the default pipeline.
  77772. */
  77773. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  77774. function DepthOfFieldMergePostProcessOptions() {
  77775. }
  77776. return DepthOfFieldMergePostProcessOptions;
  77777. }());
  77778. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  77779. /**
  77780. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77781. */
  77782. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  77783. __extends(DepthOfFieldMergePostProcess, _super);
  77784. /**
  77785. * Creates a new instance of DepthOfFieldMergePostProcess
  77786. * @param name The name of the effect.
  77787. * @param originalFromInput Post process which's input will be used for the merge.
  77788. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  77789. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  77790. * @param options The required width/height ratio to downsize to before computing the render pass.
  77791. * @param camera The camera to apply the render pass to.
  77792. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77793. * @param engine The engine which the post process will be applied. (default: current engine)
  77794. * @param reusable If the post process can be reused on the same frame. (default: false)
  77795. * @param textureType Type of textures used when performing the post process. (default: 0)
  77796. * @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)
  77797. */
  77798. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77799. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77800. if (blockCompilation === void 0) { blockCompilation = false; }
  77801. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77802. _this.blurSteps = blurSteps;
  77803. _this.onApplyObservable.add(function (effect) {
  77804. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77805. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77806. blurSteps.forEach(function (step, index) {
  77807. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  77808. });
  77809. });
  77810. if (!blockCompilation) {
  77811. _this.updateEffect();
  77812. }
  77813. return _this;
  77814. }
  77815. /**
  77816. * Updates the effect with the current post process compile time values and recompiles the shader.
  77817. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  77818. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  77819. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  77820. * @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
  77821. * @param onCompiled Called when the shader has been compiled.
  77822. * @param onError Called if there is an error when compiling a shader.
  77823. */
  77824. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  77825. if (defines === void 0) { defines = null; }
  77826. if (uniforms === void 0) { uniforms = null; }
  77827. if (samplers === void 0) { samplers = null; }
  77828. if (!defines) {
  77829. defines = "";
  77830. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  77831. }
  77832. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  77833. };
  77834. return DepthOfFieldMergePostProcess;
  77835. }(BABYLON.PostProcess));
  77836. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  77837. })(BABYLON || (BABYLON = {}));
  77838. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  77839. var BABYLON;
  77840. (function (BABYLON) {
  77841. /**
  77842. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  77843. */
  77844. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  77845. __extends(CircleOfConfusionPostProcess, _super);
  77846. /**
  77847. * Creates a new instance CircleOfConfusionPostProcess
  77848. * @param name The name of the effect.
  77849. * @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.
  77850. * @param options The required width/height ratio to downsize to before computing the render pass.
  77851. * @param camera The camera to apply the render pass to.
  77852. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77853. * @param engine The engine which the post process will be applied. (default: current engine)
  77854. * @param reusable If the post process can be reused on the same frame. (default: false)
  77855. * @param textureType Type of textures used when performing the post process. (default: 0)
  77856. * @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)
  77857. */
  77858. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77859. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77860. if (blockCompilation === void 0) { blockCompilation = false; }
  77861. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77862. /**
  77863. * 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.
  77864. */
  77865. _this.lensSize = 50;
  77866. /**
  77867. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77868. */
  77869. _this.fStop = 1.4;
  77870. /**
  77871. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77872. */
  77873. _this.focusDistance = 2000;
  77874. /**
  77875. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  77876. */
  77877. _this.focalLength = 50;
  77878. _this._depthTexture = null;
  77879. _this._depthTexture = depthTexture;
  77880. _this.onApplyObservable.add(function (effect) {
  77881. if (!_this._depthTexture) {
  77882. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  77883. return;
  77884. }
  77885. effect.setTexture("depthSampler", _this._depthTexture);
  77886. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  77887. var aperture = _this.lensSize / _this.fStop;
  77888. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  77889. effect.setFloat('focusDistance', _this.focusDistance);
  77890. effect.setFloat('cocPrecalculation', cocPrecalculation);
  77891. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  77892. });
  77893. return _this;
  77894. }
  77895. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  77896. /**
  77897. * 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.
  77898. */
  77899. set: function (value) {
  77900. this._depthTexture = value;
  77901. },
  77902. enumerable: true,
  77903. configurable: true
  77904. });
  77905. return CircleOfConfusionPostProcess;
  77906. }(BABYLON.PostProcess));
  77907. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  77908. })(BABYLON || (BABYLON = {}));
  77909. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  77910. var BABYLON;
  77911. (function (BABYLON) {
  77912. /**
  77913. * Specifies the level of max blur that should be applied when using the depth of field effect
  77914. */
  77915. var DepthOfFieldEffectBlurLevel;
  77916. (function (DepthOfFieldEffectBlurLevel) {
  77917. /**
  77918. * Subtle blur
  77919. */
  77920. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  77921. /**
  77922. * Medium blur
  77923. */
  77924. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  77925. /**
  77926. * Large blur
  77927. */
  77928. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  77929. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  77930. ;
  77931. /**
  77932. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  77933. */
  77934. var DepthOfFieldEffect = /** @class */ (function (_super) {
  77935. __extends(DepthOfFieldEffect, _super);
  77936. /**
  77937. * Creates a new instance DepthOfFieldEffect
  77938. * @param scene The scene the effect belongs to.
  77939. * @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.
  77940. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77941. * @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)
  77942. */
  77943. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  77944. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  77945. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77946. if (blockCompilation === void 0) { blockCompilation = false; }
  77947. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  77948. return _this._effects;
  77949. }, true) || this;
  77950. /**
  77951. * Internal post processes in depth of field effect
  77952. */
  77953. _this._effects = [];
  77954. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  77955. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77956. // 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)
  77957. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  77958. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77959. _this._depthOfFieldBlurY = [];
  77960. _this._depthOfFieldBlurX = [];
  77961. var blurCount = 1;
  77962. var kernelSize = 15;
  77963. switch (blurLevel) {
  77964. case DepthOfFieldEffectBlurLevel.High: {
  77965. blurCount = 3;
  77966. kernelSize = 51;
  77967. break;
  77968. }
  77969. case DepthOfFieldEffectBlurLevel.Medium: {
  77970. blurCount = 2;
  77971. kernelSize = 31;
  77972. break;
  77973. }
  77974. default: {
  77975. kernelSize = 15;
  77976. blurCount = 1;
  77977. break;
  77978. }
  77979. }
  77980. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  77981. var ratio = 1.0;
  77982. for (var i = 0; i < blurCount; i++) {
  77983. 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);
  77984. blurY.autoClear = false;
  77985. ratio = 0.75 / Math.pow(2, i);
  77986. 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);
  77987. blurX.autoClear = false;
  77988. _this._depthOfFieldBlurY.push(blurY);
  77989. _this._depthOfFieldBlurX.push(blurX);
  77990. }
  77991. // Set all post processes on the effect.
  77992. _this._effects = [_this._circleOfConfusion];
  77993. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  77994. _this._effects.push(_this._depthOfFieldBlurY[i]);
  77995. _this._effects.push(_this._depthOfFieldBlurX[i]);
  77996. }
  77997. // Merge blurred images with original image based on circleOfConfusion
  77998. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77999. _this._dofMerge.autoClear = false;
  78000. _this._effects.push(_this._dofMerge);
  78001. return _this;
  78002. }
  78003. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  78004. get: function () {
  78005. return this._circleOfConfusion.focalLength;
  78006. },
  78007. /**
  78008. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  78009. */
  78010. set: function (value) {
  78011. this._circleOfConfusion.focalLength = value;
  78012. },
  78013. enumerable: true,
  78014. configurable: true
  78015. });
  78016. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  78017. get: function () {
  78018. return this._circleOfConfusion.fStop;
  78019. },
  78020. /**
  78021. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  78022. */
  78023. set: function (value) {
  78024. this._circleOfConfusion.fStop = value;
  78025. },
  78026. enumerable: true,
  78027. configurable: true
  78028. });
  78029. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  78030. get: function () {
  78031. return this._circleOfConfusion.focusDistance;
  78032. },
  78033. /**
  78034. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  78035. */
  78036. set: function (value) {
  78037. this._circleOfConfusion.focusDistance = value;
  78038. },
  78039. enumerable: true,
  78040. configurable: true
  78041. });
  78042. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  78043. get: function () {
  78044. return this._circleOfConfusion.lensSize;
  78045. },
  78046. /**
  78047. * 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.
  78048. */
  78049. set: function (value) {
  78050. this._circleOfConfusion.lensSize = value;
  78051. },
  78052. enumerable: true,
  78053. configurable: true
  78054. });
  78055. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  78056. /**
  78057. * 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.
  78058. */
  78059. set: function (value) {
  78060. this._circleOfConfusion.depthTexture = value;
  78061. },
  78062. enumerable: true,
  78063. configurable: true
  78064. });
  78065. /**
  78066. * Disposes each of the internal effects for a given camera.
  78067. * @param camera The camera to dispose the effect on.
  78068. */
  78069. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  78070. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78071. this._effects[effectIndex].dispose(camera);
  78072. }
  78073. };
  78074. /**
  78075. * Internal
  78076. */
  78077. DepthOfFieldEffect.prototype._updateEffects = function () {
  78078. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78079. this._effects[effectIndex].updateEffect();
  78080. }
  78081. };
  78082. /**
  78083. * Internal
  78084. * @returns if all the contained post processes are ready.
  78085. */
  78086. DepthOfFieldEffect.prototype._isReady = function () {
  78087. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78088. if (!this._effects[effectIndex].isReady()) {
  78089. return false;
  78090. }
  78091. }
  78092. return true;
  78093. };
  78094. return DepthOfFieldEffect;
  78095. }(BABYLON.PostProcessRenderEffect));
  78096. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  78097. })(BABYLON || (BABYLON = {}));
  78098. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  78099. var BABYLON;
  78100. (function (BABYLON) {
  78101. /**
  78102. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  78103. */
  78104. var BloomMergePostProcess = /** @class */ (function (_super) {
  78105. __extends(BloomMergePostProcess, _super);
  78106. /**
  78107. * Creates a new instance of @see BloomMergePostProcess
  78108. * @param name The name of the effect.
  78109. * @param originalFromInput Post process which's input will be used for the merge.
  78110. * @param blurred Blurred highlights post process which's output will be used.
  78111. * @param weight Weight of the bloom to be added to the original input.
  78112. * @param options The required width/height ratio to downsize to before computing the render pass.
  78113. * @param camera The camera to apply the render pass to.
  78114. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78115. * @param engine The engine which the post process will be applied. (default: current engine)
  78116. * @param reusable If the post process can be reused on the same frame. (default: false)
  78117. * @param textureType Type of textures used when performing the post process. (default: 0)
  78118. * @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)
  78119. */
  78120. function BloomMergePostProcess(name, originalFromInput, blurred,
  78121. /** Weight of the bloom to be added to the original input. */
  78122. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78123. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78124. if (blockCompilation === void 0) { blockCompilation = false; }
  78125. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  78126. _this.weight = weight;
  78127. _this.onApplyObservable.add(function (effect) {
  78128. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  78129. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  78130. effect.setFloat("bloomWeight", _this.weight);
  78131. });
  78132. if (!blockCompilation) {
  78133. _this.updateEffect();
  78134. }
  78135. return _this;
  78136. }
  78137. return BloomMergePostProcess;
  78138. }(BABYLON.PostProcess));
  78139. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  78140. })(BABYLON || (BABYLON = {}));
  78141. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  78142. var BABYLON;
  78143. (function (BABYLON) {
  78144. /**
  78145. * 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.
  78146. */
  78147. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  78148. __extends(ExtractHighlightsPostProcess, _super);
  78149. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78150. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78151. if (blockCompilation === void 0) { blockCompilation = false; }
  78152. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78153. /**
  78154. * The luminance threshold, pixels below this value will be set to black.
  78155. */
  78156. _this.threshold = 0.9;
  78157. /**
  78158. * Internal
  78159. */
  78160. _this._exposure = 1;
  78161. /**
  78162. * Post process which has the input texture to be used when performing highlight extraction
  78163. */
  78164. _this._inputPostProcess = null;
  78165. _this.onApplyObservable.add(function (effect) {
  78166. if (_this._inputPostProcess) {
  78167. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  78168. }
  78169. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  78170. effect.setFloat('exposure', _this._exposure);
  78171. });
  78172. return _this;
  78173. }
  78174. return ExtractHighlightsPostProcess;
  78175. }(BABYLON.PostProcess));
  78176. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  78177. })(BABYLON || (BABYLON = {}));
  78178. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  78179. var BABYLON;
  78180. (function (BABYLON) {
  78181. /**
  78182. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  78183. */
  78184. var BloomEffect = /** @class */ (function (_super) {
  78185. __extends(BloomEffect, _super);
  78186. /**
  78187. * Creates a new instance of @see BloomEffect
  78188. * @param scene The scene the effect belongs to.
  78189. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  78190. * @param bloomKernel The size of the kernel to be used when applying the blur.
  78191. * @param bloomWeight The the strength of bloom.
  78192. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  78193. * @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)
  78194. */
  78195. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  78196. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  78197. if (blockCompilation === void 0) { blockCompilation = false; }
  78198. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  78199. return _this._effects;
  78200. }, true) || this;
  78201. _this.bloomScale = bloomScale;
  78202. /**
  78203. * Internal
  78204. */
  78205. _this._effects = [];
  78206. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  78207. _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);
  78208. _this._blurX.alwaysForcePOT = true;
  78209. _this._blurX.autoClear = false;
  78210. _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);
  78211. _this._blurY.alwaysForcePOT = true;
  78212. _this._blurY.autoClear = false;
  78213. _this.kernel = bloomKernel;
  78214. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  78215. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  78216. _this._merge.autoClear = false;
  78217. _this._effects.push(_this._merge);
  78218. return _this;
  78219. }
  78220. Object.defineProperty(BloomEffect.prototype, "threshold", {
  78221. /**
  78222. * The luminance threshold to find bright areas of the image to bloom.
  78223. */
  78224. get: function () {
  78225. return this._downscale.threshold;
  78226. },
  78227. set: function (value) {
  78228. this._downscale.threshold = value;
  78229. },
  78230. enumerable: true,
  78231. configurable: true
  78232. });
  78233. Object.defineProperty(BloomEffect.prototype, "weight", {
  78234. /**
  78235. * The strength of the bloom.
  78236. */
  78237. get: function () {
  78238. return this._merge.weight;
  78239. },
  78240. set: function (value) {
  78241. this._merge.weight = value;
  78242. },
  78243. enumerable: true,
  78244. configurable: true
  78245. });
  78246. Object.defineProperty(BloomEffect.prototype, "kernel", {
  78247. /**
  78248. * Specifies the size of the bloom blur kernel, relative to the final output size
  78249. */
  78250. get: function () {
  78251. return this._blurX.kernel / this.bloomScale;
  78252. },
  78253. set: function (value) {
  78254. this._blurX.kernel = value * this.bloomScale;
  78255. this._blurY.kernel = value * this.bloomScale;
  78256. },
  78257. enumerable: true,
  78258. configurable: true
  78259. });
  78260. /**
  78261. * Disposes each of the internal effects for a given camera.
  78262. * @param camera The camera to dispose the effect on.
  78263. */
  78264. BloomEffect.prototype.disposeEffects = function (camera) {
  78265. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78266. this._effects[effectIndex].dispose(camera);
  78267. }
  78268. };
  78269. /**
  78270. * Internal
  78271. */
  78272. BloomEffect.prototype._updateEffects = function () {
  78273. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78274. this._effects[effectIndex].updateEffect();
  78275. }
  78276. };
  78277. /**
  78278. * Internal
  78279. * @returns if all the contained post processes are ready.
  78280. */
  78281. BloomEffect.prototype._isReady = function () {
  78282. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78283. if (!this._effects[effectIndex].isReady()) {
  78284. return false;
  78285. }
  78286. }
  78287. return true;
  78288. };
  78289. return BloomEffect;
  78290. }(BABYLON.PostProcessRenderEffect));
  78291. BABYLON.BloomEffect = BloomEffect;
  78292. })(BABYLON || (BABYLON = {}));
  78293. //# sourceMappingURL=babylon.bloomEffect.js.map
  78294. var BABYLON;
  78295. (function (BABYLON) {
  78296. /**
  78297. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  78298. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  78299. */
  78300. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  78301. __extends(DefaultRenderingPipeline, _super);
  78302. /**
  78303. * @constructor
  78304. * @param {string} name - The rendering pipeline name (default: "")
  78305. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  78306. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  78307. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  78308. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  78309. */
  78310. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  78311. if (name === void 0) { name = ""; }
  78312. if (hdr === void 0) { hdr = true; }
  78313. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78314. if (automaticBuild === void 0) { automaticBuild = true; }
  78315. var _this = _super.call(this, scene.getEngine(), name) || this;
  78316. _this._camerasToBeAttached = [];
  78317. /**
  78318. * ID of the sharpen post process,
  78319. */
  78320. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  78321. /**
  78322. * ID of the image processing post process;
  78323. */
  78324. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  78325. /**
  78326. * ID of the Fast Approximate Anti-Aliasing post process;
  78327. */
  78328. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  78329. /**
  78330. * ID of the chromatic aberration post process,
  78331. */
  78332. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  78333. /**
  78334. * ID of the grain post process
  78335. */
  78336. _this.GrainPostProcessId = "GrainPostProcessEffect";
  78337. /**
  78338. * Glow post process which adds a glow to emmisive areas of the image
  78339. */
  78340. _this._glowLayer = null;
  78341. /**
  78342. * Animations which can be used to tweak settings over a period of time
  78343. */
  78344. _this.animations = [];
  78345. _this._imageProcessingConfigurationObserver = null;
  78346. // Values
  78347. _this._sharpenEnabled = false;
  78348. _this._bloomEnabled = false;
  78349. _this._depthOfFieldEnabled = false;
  78350. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  78351. _this._fxaaEnabled = false;
  78352. _this._imageProcessingEnabled = true;
  78353. _this._bloomScale = 0.5;
  78354. _this._chromaticAberrationEnabled = false;
  78355. _this._grainEnabled = false;
  78356. _this._buildAllowed = true;
  78357. _this._resizeObserver = null;
  78358. _this._hardwareScaleLevel = 1.0;
  78359. _this._bloomKernel = 64;
  78360. /**
  78361. * Specifies the weight of the bloom in the final rendering
  78362. */
  78363. _this._bloomWeight = 0.15;
  78364. /**
  78365. * Specifies the luma threshold for the area that will be blurred by the bloom
  78366. */
  78367. _this._bloomThreshold = 0.9;
  78368. _this._samples = 1;
  78369. _this._hasCleared = false;
  78370. _this._prevPostProcess = null;
  78371. _this._prevPrevPostProcess = null;
  78372. _this._cameras = cameras || scene.cameras;
  78373. _this._camerasToBeAttached = _this._cameras.slice();
  78374. _this._buildAllowed = automaticBuild;
  78375. // Initialize
  78376. _this._scene = scene;
  78377. var caps = _this._scene.getEngine().getCaps();
  78378. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  78379. // Misc
  78380. if (_this._hdr) {
  78381. if (caps.textureHalfFloatRender) {
  78382. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78383. }
  78384. else if (caps.textureFloatRender) {
  78385. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78386. }
  78387. }
  78388. else {
  78389. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78390. }
  78391. // Attach
  78392. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78393. var engine = _this._scene.getEngine();
  78394. // Create post processes before hand so they can be modified before enabled.
  78395. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  78396. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78397. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  78398. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  78399. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  78400. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78401. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  78402. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78403. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  78404. _this._resizeObserver = engine.onResizeObservable.add(function () {
  78405. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  78406. _this.bloomKernel = _this.bloomKernel;
  78407. });
  78408. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  78409. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  78410. });
  78411. _this._buildPipeline();
  78412. return _this;
  78413. }
  78414. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  78415. get: function () {
  78416. return this._sharpenEnabled;
  78417. },
  78418. /**
  78419. * Enable or disable the sharpen process from the pipeline
  78420. */
  78421. set: function (enabled) {
  78422. if (this._sharpenEnabled === enabled) {
  78423. return;
  78424. }
  78425. this._sharpenEnabled = enabled;
  78426. this._buildPipeline();
  78427. },
  78428. enumerable: true,
  78429. configurable: true
  78430. });
  78431. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  78432. /**
  78433. * Specifies the size of the bloom blur kernel, relative to the final output size
  78434. */
  78435. get: function () {
  78436. return this._bloomKernel;
  78437. },
  78438. set: function (value) {
  78439. this._bloomKernel = value;
  78440. this.bloom.kernel = value / this._hardwareScaleLevel;
  78441. },
  78442. enumerable: true,
  78443. configurable: true
  78444. });
  78445. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  78446. get: function () {
  78447. return this._bloomWeight;
  78448. },
  78449. /**
  78450. * The strength of the bloom.
  78451. */
  78452. set: function (value) {
  78453. if (this._bloomWeight === value) {
  78454. return;
  78455. }
  78456. this.bloom.weight = value;
  78457. this._bloomWeight = value;
  78458. },
  78459. enumerable: true,
  78460. configurable: true
  78461. });
  78462. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  78463. get: function () {
  78464. return this._bloomThreshold;
  78465. },
  78466. /**
  78467. * The strength of the bloom.
  78468. */
  78469. set: function (value) {
  78470. if (this._bloomThreshold === value) {
  78471. return;
  78472. }
  78473. this.bloom.threshold = value;
  78474. this._bloomThreshold = value;
  78475. },
  78476. enumerable: true,
  78477. configurable: true
  78478. });
  78479. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  78480. get: function () {
  78481. return this._bloomScale;
  78482. },
  78483. /**
  78484. * The scale of the bloom, lower value will provide better performance.
  78485. */
  78486. set: function (value) {
  78487. if (this._bloomScale === value) {
  78488. return;
  78489. }
  78490. this._bloomScale = value;
  78491. // recreate bloom and dispose old as this setting is not dynamic
  78492. this._rebuildBloom();
  78493. this._buildPipeline();
  78494. },
  78495. enumerable: true,
  78496. configurable: true
  78497. });
  78498. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  78499. get: function () {
  78500. return this._bloomEnabled;
  78501. },
  78502. /**
  78503. * Enable or disable the bloom from the pipeline
  78504. */
  78505. set: function (enabled) {
  78506. if (this._bloomEnabled === enabled) {
  78507. return;
  78508. }
  78509. this._bloomEnabled = enabled;
  78510. this._buildPipeline();
  78511. },
  78512. enumerable: true,
  78513. configurable: true
  78514. });
  78515. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  78516. // recreate bloom and dispose old as this setting is not dynamic
  78517. var oldBloom = this.bloom;
  78518. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  78519. this.bloom.threshold = oldBloom.threshold;
  78520. for (var i = 0; i < this._cameras.length; i++) {
  78521. oldBloom.disposeEffects(this._cameras[i]);
  78522. }
  78523. };
  78524. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  78525. /**
  78526. * If the depth of field is enabled.
  78527. */
  78528. get: function () {
  78529. return this._depthOfFieldEnabled;
  78530. },
  78531. set: function (enabled) {
  78532. if (this._depthOfFieldEnabled === enabled) {
  78533. return;
  78534. }
  78535. this._depthOfFieldEnabled = enabled;
  78536. this._buildPipeline();
  78537. },
  78538. enumerable: true,
  78539. configurable: true
  78540. });
  78541. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  78542. /**
  78543. * Blur level of the depth of field effect. (Higher blur will effect performance)
  78544. */
  78545. get: function () {
  78546. return this._depthOfFieldBlurLevel;
  78547. },
  78548. set: function (value) {
  78549. if (this._depthOfFieldBlurLevel === value) {
  78550. return;
  78551. }
  78552. this._depthOfFieldBlurLevel = value;
  78553. // recreate dof and dispose old as this setting is not dynamic
  78554. var oldDof = this.depthOfField;
  78555. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  78556. this.depthOfField.focalLength = oldDof.focalLength;
  78557. this.depthOfField.focusDistance = oldDof.focusDistance;
  78558. this.depthOfField.fStop = oldDof.fStop;
  78559. this.depthOfField.lensSize = oldDof.lensSize;
  78560. for (var i = 0; i < this._cameras.length; i++) {
  78561. oldDof.disposeEffects(this._cameras[i]);
  78562. }
  78563. this._buildPipeline();
  78564. },
  78565. enumerable: true,
  78566. configurable: true
  78567. });
  78568. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  78569. get: function () {
  78570. return this._fxaaEnabled;
  78571. },
  78572. /**
  78573. * If the anti aliasing is enabled.
  78574. */
  78575. set: function (enabled) {
  78576. if (this._fxaaEnabled === enabled) {
  78577. return;
  78578. }
  78579. this._fxaaEnabled = enabled;
  78580. this._buildPipeline();
  78581. },
  78582. enumerable: true,
  78583. configurable: true
  78584. });
  78585. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  78586. get: function () {
  78587. return this._samples;
  78588. },
  78589. /**
  78590. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  78591. */
  78592. set: function (sampleCount) {
  78593. if (this._samples === sampleCount) {
  78594. return;
  78595. }
  78596. this._samples = sampleCount;
  78597. this._buildPipeline();
  78598. },
  78599. enumerable: true,
  78600. configurable: true
  78601. });
  78602. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  78603. get: function () {
  78604. return this._imageProcessingEnabled;
  78605. },
  78606. /**
  78607. * If image processing is enabled.
  78608. */
  78609. set: function (enabled) {
  78610. if (this._imageProcessingEnabled === enabled) {
  78611. return;
  78612. }
  78613. this._imageProcessingEnabled = enabled;
  78614. this._buildPipeline();
  78615. },
  78616. enumerable: true,
  78617. configurable: true
  78618. });
  78619. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  78620. get: function () {
  78621. return this._glowLayer == null;
  78622. },
  78623. /**
  78624. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  78625. */
  78626. set: function (enabled) {
  78627. if (enabled && !this._glowLayer) {
  78628. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  78629. }
  78630. else if (!enabled && this._glowLayer) {
  78631. this._glowLayer.dispose();
  78632. this._glowLayer = null;
  78633. }
  78634. },
  78635. enumerable: true,
  78636. configurable: true
  78637. });
  78638. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  78639. get: function () {
  78640. return this._chromaticAberrationEnabled;
  78641. },
  78642. /**
  78643. * Enable or disable the chromaticAberration process from the pipeline
  78644. */
  78645. set: function (enabled) {
  78646. if (this._chromaticAberrationEnabled === enabled) {
  78647. return;
  78648. }
  78649. this._chromaticAberrationEnabled = enabled;
  78650. this._buildPipeline();
  78651. },
  78652. enumerable: true,
  78653. configurable: true
  78654. });
  78655. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  78656. get: function () {
  78657. return this._grainEnabled;
  78658. },
  78659. /**
  78660. * Enable or disable the grain process from the pipeline
  78661. */
  78662. set: function (enabled) {
  78663. if (this._grainEnabled === enabled) {
  78664. return;
  78665. }
  78666. this._grainEnabled = enabled;
  78667. this._buildPipeline();
  78668. },
  78669. enumerable: true,
  78670. configurable: true
  78671. });
  78672. /**
  78673. * Force the compilation of the entire pipeline.
  78674. */
  78675. DefaultRenderingPipeline.prototype.prepare = function () {
  78676. var previousState = this._buildAllowed;
  78677. this._buildAllowed = true;
  78678. this._buildPipeline();
  78679. this._buildAllowed = previousState;
  78680. };
  78681. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  78682. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  78683. if (this._hasCleared) {
  78684. postProcess.autoClear = false;
  78685. }
  78686. else {
  78687. postProcess.autoClear = true;
  78688. this._scene.autoClear = false;
  78689. this._hasCleared = true;
  78690. }
  78691. if (!skipTextureSharing) {
  78692. if (this._prevPrevPostProcess) {
  78693. postProcess.shareOutputWith(this._prevPrevPostProcess);
  78694. }
  78695. else {
  78696. postProcess.useOwnOutput();
  78697. }
  78698. if (this._prevPostProcess) {
  78699. this._prevPrevPostProcess = this._prevPostProcess;
  78700. }
  78701. this._prevPostProcess = postProcess;
  78702. }
  78703. };
  78704. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  78705. var _this = this;
  78706. if (!this._buildAllowed) {
  78707. return;
  78708. }
  78709. this._scene.autoClear = true;
  78710. var engine = this._scene.getEngine();
  78711. this._disposePostProcesses();
  78712. if (this._cameras !== null) {
  78713. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78714. // get back cameras to be used to reattach pipeline
  78715. this._cameras = this._camerasToBeAttached.slice();
  78716. }
  78717. this._reset();
  78718. this._prevPostProcess = null;
  78719. this._prevPrevPostProcess = null;
  78720. this._hasCleared = false;
  78721. if (this.depthOfFieldEnabled) {
  78722. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  78723. this.depthOfField.depthTexture = depthTexture;
  78724. if (!this.depthOfField._isReady()) {
  78725. this.depthOfField._updateEffects();
  78726. }
  78727. this.addEffect(this.depthOfField);
  78728. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  78729. }
  78730. if (this.bloomEnabled) {
  78731. if (!this.bloom._isReady()) {
  78732. this.bloom._updateEffects();
  78733. }
  78734. this.addEffect(this.bloom);
  78735. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  78736. }
  78737. if (this._imageProcessingEnabled) {
  78738. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78739. if (this._hdr) {
  78740. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  78741. this._setAutoClearAndTextureSharing(this.imageProcessing);
  78742. }
  78743. else {
  78744. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  78745. }
  78746. }
  78747. if (this.sharpenEnabled) {
  78748. if (!this.sharpen.isReady()) {
  78749. this.sharpen.updateEffect();
  78750. }
  78751. this.addEffect(this._sharpenEffect);
  78752. this._setAutoClearAndTextureSharing(this.sharpen);
  78753. }
  78754. if (this.grainEnabled) {
  78755. if (!this.grain.isReady()) {
  78756. this.grain.updateEffect();
  78757. }
  78758. this.addEffect(this._grainEffect);
  78759. this._setAutoClearAndTextureSharing(this.grain);
  78760. }
  78761. if (this.chromaticAberrationEnabled) {
  78762. if (!this.chromaticAberration.isReady()) {
  78763. this.chromaticAberration.updateEffect();
  78764. }
  78765. this.addEffect(this._chromaticAberrationEffect);
  78766. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  78767. }
  78768. if (this.fxaaEnabled) {
  78769. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78770. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  78771. this._setAutoClearAndTextureSharing(this.fxaa, true);
  78772. }
  78773. if (this._cameras !== null) {
  78774. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78775. }
  78776. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  78777. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  78778. }
  78779. };
  78780. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  78781. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  78782. for (var i = 0; i < this._cameras.length; i++) {
  78783. var camera = this._cameras[i];
  78784. if (this.imageProcessing) {
  78785. this.imageProcessing.dispose(camera);
  78786. }
  78787. if (this.fxaa) {
  78788. this.fxaa.dispose(camera);
  78789. }
  78790. // These are created in the constructor and should not be disposed on every pipeline change
  78791. if (disposeNonRecreated) {
  78792. if (this.sharpen) {
  78793. this.sharpen.dispose(camera);
  78794. }
  78795. if (this.depthOfField) {
  78796. this.depthOfField.disposeEffects(camera);
  78797. }
  78798. if (this.bloom) {
  78799. this.bloom.disposeEffects(camera);
  78800. }
  78801. if (this.chromaticAberration) {
  78802. this.chromaticAberration.dispose(camera);
  78803. }
  78804. if (this.grain) {
  78805. this.grain.dispose(camera);
  78806. }
  78807. if (this._glowLayer) {
  78808. this._glowLayer.dispose();
  78809. }
  78810. }
  78811. }
  78812. this.imageProcessing = null;
  78813. this.fxaa = null;
  78814. if (disposeNonRecreated) {
  78815. this.sharpen = null;
  78816. this._sharpenEffect = null;
  78817. this.depthOfField = null;
  78818. this.bloom = null;
  78819. this.chromaticAberration = null;
  78820. this._chromaticAberrationEffect = null;
  78821. this.grain = null;
  78822. this._grainEffect = null;
  78823. this._glowLayer = null;
  78824. }
  78825. };
  78826. /**
  78827. * Adds a camera to the pipeline
  78828. * @param camera the camera to be added
  78829. */
  78830. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  78831. this._camerasToBeAttached.push(camera);
  78832. this._buildPipeline();
  78833. };
  78834. /**
  78835. * Removes a camera from the pipeline
  78836. * @param camera the camera to remove
  78837. */
  78838. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  78839. var index = this._camerasToBeAttached.indexOf(camera);
  78840. this._camerasToBeAttached.splice(index, 1);
  78841. this._buildPipeline();
  78842. };
  78843. /**
  78844. * Dispose of the pipeline and stop all post processes
  78845. */
  78846. DefaultRenderingPipeline.prototype.dispose = function () {
  78847. this._disposePostProcesses(true);
  78848. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78849. this._scene.autoClear = true;
  78850. if (this._resizeObserver) {
  78851. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  78852. this._resizeObserver = null;
  78853. }
  78854. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  78855. _super.prototype.dispose.call(this);
  78856. };
  78857. /**
  78858. * Serialize the rendering pipeline (Used when exporting)
  78859. * @returns the serialized object
  78860. */
  78861. DefaultRenderingPipeline.prototype.serialize = function () {
  78862. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78863. serializationObject.customType = "DefaultRenderingPipeline";
  78864. return serializationObject;
  78865. };
  78866. /**
  78867. * Parse the serialized pipeline
  78868. * @param source Source pipeline.
  78869. * @param scene The scene to load the pipeline to.
  78870. * @param rootUrl The URL of the serialized pipeline.
  78871. * @returns An instantiated pipeline from the serialized object.
  78872. */
  78873. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78874. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  78875. };
  78876. __decorate([
  78877. BABYLON.serialize()
  78878. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  78879. __decorate([
  78880. BABYLON.serialize()
  78881. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  78882. __decorate([
  78883. BABYLON.serialize()
  78884. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  78885. __decorate([
  78886. BABYLON.serialize()
  78887. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  78888. __decorate([
  78889. BABYLON.serialize()
  78890. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  78891. __decorate([
  78892. BABYLON.serialize()
  78893. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  78894. __decorate([
  78895. BABYLON.serialize()
  78896. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  78897. __decorate([
  78898. BABYLON.serialize()
  78899. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  78900. __decorate([
  78901. BABYLON.serialize()
  78902. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  78903. __decorate([
  78904. BABYLON.serialize()
  78905. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  78906. __decorate([
  78907. BABYLON.serialize()
  78908. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  78909. __decorate([
  78910. BABYLON.serialize()
  78911. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  78912. __decorate([
  78913. BABYLON.serialize()
  78914. ], DefaultRenderingPipeline.prototype, "samples", null);
  78915. __decorate([
  78916. BABYLON.serialize()
  78917. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  78918. __decorate([
  78919. BABYLON.serialize()
  78920. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  78921. __decorate([
  78922. BABYLON.serialize()
  78923. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  78924. __decorate([
  78925. BABYLON.serialize()
  78926. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  78927. return DefaultRenderingPipeline;
  78928. }(BABYLON.PostProcessRenderPipeline));
  78929. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  78930. })(BABYLON || (BABYLON = {}));
  78931. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  78932. var BABYLON;
  78933. (function (BABYLON) {
  78934. /**
  78935. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  78936. */
  78937. var GeometryBufferRenderer = /** @class */ (function () {
  78938. /**
  78939. * Creates a new G Buffer for the scene
  78940. * @param scene The scene the buffer belongs to
  78941. * @param ratio How big is the buffer related to the main canvas.
  78942. */
  78943. function GeometryBufferRenderer(scene, ratio) {
  78944. if (ratio === void 0) { ratio = 1; }
  78945. this._enablePosition = false;
  78946. this._scene = scene;
  78947. this._ratio = ratio;
  78948. // Render target
  78949. this._createRenderTargets();
  78950. }
  78951. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  78952. /**
  78953. * Set the render list (meshes to be rendered) used in the G buffer.
  78954. */
  78955. set: function (meshes) {
  78956. this._multiRenderTarget.renderList = meshes;
  78957. },
  78958. enumerable: true,
  78959. configurable: true
  78960. });
  78961. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  78962. /**
  78963. * Gets wether or not G buffer are supported by the running hardware.
  78964. * This requires draw buffer supports
  78965. */
  78966. get: function () {
  78967. return this._multiRenderTarget.isSupported;
  78968. },
  78969. enumerable: true,
  78970. configurable: true
  78971. });
  78972. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  78973. /**
  78974. * Gets wether or not position are enabled for the G buffer.
  78975. */
  78976. get: function () {
  78977. return this._enablePosition;
  78978. },
  78979. /**
  78980. * Sets wether or not position are enabled for the G buffer.
  78981. */
  78982. set: function (enable) {
  78983. this._enablePosition = enable;
  78984. this.dispose();
  78985. this._createRenderTargets();
  78986. },
  78987. enumerable: true,
  78988. configurable: true
  78989. });
  78990. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  78991. /**
  78992. * Gets the scene associated with the buffer.
  78993. */
  78994. get: function () {
  78995. return this._scene;
  78996. },
  78997. enumerable: true,
  78998. configurable: true
  78999. });
  79000. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  79001. /**
  79002. * Gets the ratio used by the buffer during its creation.
  79003. * How big is the buffer related to the main canvas.
  79004. */
  79005. get: function () {
  79006. return this._ratio;
  79007. },
  79008. enumerable: true,
  79009. configurable: true
  79010. });
  79011. /**
  79012. * Checks wether everything is ready to render a submesh to the G buffer.
  79013. * @param subMesh the submesh to check readiness for
  79014. * @param useInstances is the mesh drawn using instance or not
  79015. * @returns true if ready otherwise false
  79016. */
  79017. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  79018. var material = subMesh.getMaterial();
  79019. if (material && material.disableDepthWrite) {
  79020. return false;
  79021. }
  79022. var defines = [];
  79023. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  79024. var mesh = subMesh.getMesh();
  79025. // Alpha test
  79026. if (material && material.needAlphaTesting()) {
  79027. defines.push("#define ALPHATEST");
  79028. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79029. attribs.push(BABYLON.VertexBuffer.UVKind);
  79030. defines.push("#define UV1");
  79031. }
  79032. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79033. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79034. defines.push("#define UV2");
  79035. }
  79036. }
  79037. // Buffers
  79038. if (this._enablePosition) {
  79039. defines.push("#define POSITION");
  79040. }
  79041. // Bones
  79042. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79043. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79044. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79045. if (mesh.numBoneInfluencers > 4) {
  79046. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79047. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79048. }
  79049. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79050. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  79051. }
  79052. else {
  79053. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79054. }
  79055. // Instances
  79056. if (useInstances) {
  79057. defines.push("#define INSTANCES");
  79058. attribs.push("world0");
  79059. attribs.push("world1");
  79060. attribs.push("world2");
  79061. attribs.push("world3");
  79062. }
  79063. // Get correct effect
  79064. var join = defines.join("\n");
  79065. if (this._cachedDefines !== join) {
  79066. this._cachedDefines = join;
  79067. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  79068. }
  79069. return this._effect.isReady();
  79070. };
  79071. /**
  79072. * Gets the current underlying G Buffer.
  79073. * @returns the buffer
  79074. */
  79075. GeometryBufferRenderer.prototype.getGBuffer = function () {
  79076. return this._multiRenderTarget;
  79077. };
  79078. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  79079. /**
  79080. * Gets the number of samples used to render the buffer (anti aliasing).
  79081. */
  79082. get: function () {
  79083. return this._multiRenderTarget.samples;
  79084. },
  79085. /**
  79086. * Sets the number of samples used to render the buffer (anti aliasing).
  79087. */
  79088. set: function (value) {
  79089. this._multiRenderTarget.samples = value;
  79090. },
  79091. enumerable: true,
  79092. configurable: true
  79093. });
  79094. /**
  79095. * Disposes the renderer and frees up associated resources.
  79096. */
  79097. GeometryBufferRenderer.prototype.dispose = function () {
  79098. this.getGBuffer().dispose();
  79099. };
  79100. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  79101. var _this = this;
  79102. var engine = this._scene.getEngine();
  79103. var count = this._enablePosition ? 3 : 2;
  79104. 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 });
  79105. if (!this.isSupported) {
  79106. return;
  79107. }
  79108. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79109. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79110. this._multiRenderTarget.refreshRate = 1;
  79111. this._multiRenderTarget.renderParticles = false;
  79112. this._multiRenderTarget.renderList = null;
  79113. // set default depth value to 1.0 (far away)
  79114. this._multiRenderTarget.onClearObservable.add(function (engine) {
  79115. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  79116. });
  79117. // Custom render function
  79118. var renderSubMesh = function (subMesh) {
  79119. var mesh = subMesh.getRenderingMesh();
  79120. var scene = _this._scene;
  79121. var engine = scene.getEngine();
  79122. var material = subMesh.getMaterial();
  79123. if (!material) {
  79124. return;
  79125. }
  79126. // Culling
  79127. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  79128. // Managing instances
  79129. var batch = mesh._getInstancesRenderList(subMesh._id);
  79130. if (batch.mustReturn) {
  79131. return;
  79132. }
  79133. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79134. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  79135. engine.enableEffect(_this._effect);
  79136. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  79137. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79138. _this._effect.setMatrix("view", scene.getViewMatrix());
  79139. // Alpha test
  79140. if (material && material.needAlphaTesting()) {
  79141. var alphaTexture = material.getAlphaTestTexture();
  79142. if (alphaTexture) {
  79143. _this._effect.setTexture("diffuseSampler", alphaTexture);
  79144. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79145. }
  79146. }
  79147. // Bones
  79148. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79149. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79150. }
  79151. // Draw
  79152. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  79153. }
  79154. };
  79155. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79156. var index;
  79157. if (depthOnlySubMeshes.length) {
  79158. engine.setColorWrite(false);
  79159. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79160. renderSubMesh(depthOnlySubMeshes.data[index]);
  79161. }
  79162. engine.setColorWrite(true);
  79163. }
  79164. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79165. renderSubMesh(opaqueSubMeshes.data[index]);
  79166. }
  79167. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79168. renderSubMesh(alphaTestSubMeshes.data[index]);
  79169. }
  79170. };
  79171. };
  79172. return GeometryBufferRenderer;
  79173. }());
  79174. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  79175. })(BABYLON || (BABYLON = {}));
  79176. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  79177. var BABYLON;
  79178. (function (BABYLON) {
  79179. /**
  79180. * This groups together the common properties used for image processing either in direct forward pass
  79181. * or through post processing effect depending on the use of the image processing pipeline in your scene
  79182. * or not.
  79183. */
  79184. var ImageProcessingConfiguration = /** @class */ (function () {
  79185. function ImageProcessingConfiguration() {
  79186. /**
  79187. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  79188. */
  79189. this.colorCurves = new BABYLON.ColorCurves();
  79190. this._colorCurvesEnabled = false;
  79191. this._colorGradingEnabled = false;
  79192. this._colorGradingWithGreenDepth = true;
  79193. this._colorGradingBGR = true;
  79194. this._exposure = 1.0;
  79195. this._toneMappingEnabled = false;
  79196. this._contrast = 1.0;
  79197. /**
  79198. * Vignette stretch size.
  79199. */
  79200. this.vignetteStretch = 0;
  79201. /**
  79202. * Vignette centre X Offset.
  79203. */
  79204. this.vignetteCentreX = 0;
  79205. /**
  79206. * Vignette centre Y Offset.
  79207. */
  79208. this.vignetteCentreY = 0;
  79209. /**
  79210. * Vignette weight or intensity of the vignette effect.
  79211. */
  79212. this.vignetteWeight = 1.5;
  79213. /**
  79214. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79215. * if vignetteEnabled is set to true.
  79216. */
  79217. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79218. /**
  79219. * Camera field of view used by the Vignette effect.
  79220. */
  79221. this.vignetteCameraFov = 0.5;
  79222. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  79223. this._vignetteEnabled = false;
  79224. this._applyByPostProcess = false;
  79225. this._isEnabled = true;
  79226. /**
  79227. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  79228. */
  79229. this.onUpdateParameters = new BABYLON.Observable();
  79230. }
  79231. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  79232. /**
  79233. * Gets wether the color curves effect is enabled.
  79234. */
  79235. get: function () {
  79236. return this._colorCurvesEnabled;
  79237. },
  79238. /**
  79239. * Sets wether the color curves effect is enabled.
  79240. */
  79241. set: function (value) {
  79242. if (this._colorCurvesEnabled === value) {
  79243. return;
  79244. }
  79245. this._colorCurvesEnabled = value;
  79246. this._updateParameters();
  79247. },
  79248. enumerable: true,
  79249. configurable: true
  79250. });
  79251. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  79252. /**
  79253. * Gets wether the color grading effect is enabled.
  79254. */
  79255. get: function () {
  79256. return this._colorGradingEnabled;
  79257. },
  79258. /**
  79259. * Sets wether the color grading effect is enabled.
  79260. */
  79261. set: function (value) {
  79262. if (this._colorGradingEnabled === value) {
  79263. return;
  79264. }
  79265. this._colorGradingEnabled = value;
  79266. this._updateParameters();
  79267. },
  79268. enumerable: true,
  79269. configurable: true
  79270. });
  79271. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  79272. /**
  79273. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  79274. */
  79275. get: function () {
  79276. return this._colorGradingWithGreenDepth;
  79277. },
  79278. /**
  79279. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  79280. */
  79281. set: function (value) {
  79282. if (this._colorGradingWithGreenDepth === value) {
  79283. return;
  79284. }
  79285. this._colorGradingWithGreenDepth = value;
  79286. this._updateParameters();
  79287. },
  79288. enumerable: true,
  79289. configurable: true
  79290. });
  79291. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  79292. /**
  79293. * Gets wether the color grading texture contains BGR values.
  79294. */
  79295. get: function () {
  79296. return this._colorGradingBGR;
  79297. },
  79298. /**
  79299. * Sets wether the color grading texture contains BGR values.
  79300. */
  79301. set: function (value) {
  79302. if (this._colorGradingBGR === value) {
  79303. return;
  79304. }
  79305. this._colorGradingBGR = value;
  79306. this._updateParameters();
  79307. },
  79308. enumerable: true,
  79309. configurable: true
  79310. });
  79311. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  79312. /**
  79313. * Gets the Exposure used in the effect.
  79314. */
  79315. get: function () {
  79316. return this._exposure;
  79317. },
  79318. /**
  79319. * Sets the Exposure used in the effect.
  79320. */
  79321. set: function (value) {
  79322. if (this._exposure === value) {
  79323. return;
  79324. }
  79325. this._exposure = value;
  79326. this._updateParameters();
  79327. },
  79328. enumerable: true,
  79329. configurable: true
  79330. });
  79331. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  79332. /**
  79333. * Gets wether the tone mapping effect is enabled.
  79334. */
  79335. get: function () {
  79336. return this._toneMappingEnabled;
  79337. },
  79338. /**
  79339. * Sets wether the tone mapping effect is enabled.
  79340. */
  79341. set: function (value) {
  79342. if (this._toneMappingEnabled === value) {
  79343. return;
  79344. }
  79345. this._toneMappingEnabled = value;
  79346. this._updateParameters();
  79347. },
  79348. enumerable: true,
  79349. configurable: true
  79350. });
  79351. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  79352. /**
  79353. * Gets the contrast used in the effect.
  79354. */
  79355. get: function () {
  79356. return this._contrast;
  79357. },
  79358. /**
  79359. * Sets the contrast used in the effect.
  79360. */
  79361. set: function (value) {
  79362. if (this._contrast === value) {
  79363. return;
  79364. }
  79365. this._contrast = value;
  79366. this._updateParameters();
  79367. },
  79368. enumerable: true,
  79369. configurable: true
  79370. });
  79371. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  79372. /**
  79373. * Gets the vignette blend mode allowing different kind of effect.
  79374. */
  79375. get: function () {
  79376. return this._vignetteBlendMode;
  79377. },
  79378. /**
  79379. * Sets the vignette blend mode allowing different kind of effect.
  79380. */
  79381. set: function (value) {
  79382. if (this._vignetteBlendMode === value) {
  79383. return;
  79384. }
  79385. this._vignetteBlendMode = value;
  79386. this._updateParameters();
  79387. },
  79388. enumerable: true,
  79389. configurable: true
  79390. });
  79391. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  79392. /**
  79393. * Gets wether the vignette effect is enabled.
  79394. */
  79395. get: function () {
  79396. return this._vignetteEnabled;
  79397. },
  79398. /**
  79399. * Sets wether the vignette effect is enabled.
  79400. */
  79401. set: function (value) {
  79402. if (this._vignetteEnabled === value) {
  79403. return;
  79404. }
  79405. this._vignetteEnabled = value;
  79406. this._updateParameters();
  79407. },
  79408. enumerable: true,
  79409. configurable: true
  79410. });
  79411. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  79412. /**
  79413. * Gets wether the image processing is applied through a post process or not.
  79414. */
  79415. get: function () {
  79416. return this._applyByPostProcess;
  79417. },
  79418. /**
  79419. * Sets wether the image processing is applied through a post process or not.
  79420. */
  79421. set: function (value) {
  79422. if (this._applyByPostProcess === value) {
  79423. return;
  79424. }
  79425. this._applyByPostProcess = value;
  79426. this._updateParameters();
  79427. },
  79428. enumerable: true,
  79429. configurable: true
  79430. });
  79431. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  79432. /**
  79433. * Gets wether the image processing is enabled or not.
  79434. */
  79435. get: function () {
  79436. return this._isEnabled;
  79437. },
  79438. /**
  79439. * Sets wether the image processing is enabled or not.
  79440. */
  79441. set: function (value) {
  79442. if (this._isEnabled === value) {
  79443. return;
  79444. }
  79445. this._isEnabled = value;
  79446. this._updateParameters();
  79447. },
  79448. enumerable: true,
  79449. configurable: true
  79450. });
  79451. /**
  79452. * Method called each time the image processing information changes requires to recompile the effect.
  79453. */
  79454. ImageProcessingConfiguration.prototype._updateParameters = function () {
  79455. this.onUpdateParameters.notifyObservers(this);
  79456. };
  79457. ImageProcessingConfiguration.prototype.getClassName = function () {
  79458. return "ImageProcessingConfiguration";
  79459. };
  79460. /**
  79461. * Prepare the list of uniforms associated with the Image Processing effects.
  79462. * @param uniformsList The list of uniforms used in the effect
  79463. * @param defines the list of defines currently in use
  79464. */
  79465. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  79466. if (defines.EXPOSURE) {
  79467. uniforms.push("exposureLinear");
  79468. }
  79469. if (defines.CONTRAST) {
  79470. uniforms.push("contrast");
  79471. }
  79472. if (defines.COLORGRADING) {
  79473. uniforms.push("colorTransformSettings");
  79474. }
  79475. if (defines.VIGNETTE) {
  79476. uniforms.push("vInverseScreenSize");
  79477. uniforms.push("vignetteSettings1");
  79478. uniforms.push("vignetteSettings2");
  79479. }
  79480. if (defines.COLORCURVES) {
  79481. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  79482. }
  79483. };
  79484. /**
  79485. * Prepare the list of samplers associated with the Image Processing effects.
  79486. * @param uniformsList The list of uniforms used in the effect
  79487. * @param defines the list of defines currently in use
  79488. */
  79489. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  79490. if (defines.COLORGRADING) {
  79491. samplersList.push("txColorTransform");
  79492. }
  79493. };
  79494. /**
  79495. * Prepare the list of defines associated to the shader.
  79496. * @param defines the list of defines to complete
  79497. */
  79498. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  79499. if (forPostProcess === void 0) { forPostProcess = false; }
  79500. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  79501. defines.VIGNETTE = false;
  79502. defines.TONEMAPPING = false;
  79503. defines.CONTRAST = false;
  79504. defines.EXPOSURE = false;
  79505. defines.COLORCURVES = false;
  79506. defines.COLORGRADING = false;
  79507. defines.COLORGRADING3D = false;
  79508. defines.IMAGEPROCESSING = false;
  79509. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  79510. return;
  79511. }
  79512. defines.VIGNETTE = this.vignetteEnabled;
  79513. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  79514. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  79515. defines.TONEMAPPING = this.toneMappingEnabled;
  79516. defines.CONTRAST = (this.contrast !== 1.0);
  79517. defines.EXPOSURE = (this.exposure !== 1.0);
  79518. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  79519. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  79520. if (defines.COLORGRADING) {
  79521. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  79522. }
  79523. else {
  79524. defines.COLORGRADING3D = false;
  79525. }
  79526. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  79527. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  79528. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  79529. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  79530. };
  79531. /**
  79532. * Returns true if all the image processing information are ready.
  79533. */
  79534. ImageProcessingConfiguration.prototype.isReady = function () {
  79535. // Color Grading texure can not be none blocking.
  79536. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  79537. };
  79538. /**
  79539. * Binds the image processing to the shader.
  79540. * @param effect The effect to bind to
  79541. */
  79542. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  79543. if (aspectRatio === void 0) { aspectRatio = 1; }
  79544. // Color Curves
  79545. if (this._colorCurvesEnabled && this.colorCurves) {
  79546. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  79547. }
  79548. // Vignette
  79549. if (this._vignetteEnabled) {
  79550. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  79551. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  79552. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  79553. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  79554. var vignetteScaleX = vignetteScaleY * aspectRatio;
  79555. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  79556. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  79557. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  79558. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  79559. var vignettePower = -2.0 * this.vignetteWeight;
  79560. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  79561. }
  79562. // Exposure
  79563. effect.setFloat("exposureLinear", this.exposure);
  79564. // Contrast
  79565. effect.setFloat("contrast", this.contrast);
  79566. // Color transform settings
  79567. if (this.colorGradingTexture) {
  79568. effect.setTexture("txColorTransform", this.colorGradingTexture);
  79569. var textureSize = this.colorGradingTexture.getSize().height;
  79570. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  79571. 0.5 / textureSize, // textureOffset
  79572. textureSize, // textureSize
  79573. this.colorGradingTexture.level // weight
  79574. );
  79575. }
  79576. };
  79577. /**
  79578. * Clones the current image processing instance.
  79579. * @return The cloned image processing
  79580. */
  79581. ImageProcessingConfiguration.prototype.clone = function () {
  79582. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  79583. };
  79584. /**
  79585. * Serializes the current image processing instance to a json representation.
  79586. * @return a JSON representation
  79587. */
  79588. ImageProcessingConfiguration.prototype.serialize = function () {
  79589. return BABYLON.SerializationHelper.Serialize(this);
  79590. };
  79591. /**
  79592. * Parses the image processing from a json representation.
  79593. * @param source the JSON source to parse
  79594. * @return The parsed image processing
  79595. */
  79596. ImageProcessingConfiguration.Parse = function (source) {
  79597. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  79598. };
  79599. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  79600. /**
  79601. * Used to apply the vignette as a mix with the pixel color.
  79602. */
  79603. get: function () {
  79604. return this._VIGNETTEMODE_MULTIPLY;
  79605. },
  79606. enumerable: true,
  79607. configurable: true
  79608. });
  79609. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  79610. /**
  79611. * Used to apply the vignette as a replacement of the pixel color.
  79612. */
  79613. get: function () {
  79614. return this._VIGNETTEMODE_OPAQUE;
  79615. },
  79616. enumerable: true,
  79617. configurable: true
  79618. });
  79619. // Static constants associated to the image processing.
  79620. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  79621. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  79622. __decorate([
  79623. BABYLON.serializeAsColorCurves()
  79624. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  79625. __decorate([
  79626. BABYLON.serialize()
  79627. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  79628. __decorate([
  79629. BABYLON.serializeAsTexture()
  79630. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  79631. __decorate([
  79632. BABYLON.serialize()
  79633. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  79634. __decorate([
  79635. BABYLON.serialize()
  79636. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  79637. __decorate([
  79638. BABYLON.serialize()
  79639. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  79640. __decorate([
  79641. BABYLON.serialize()
  79642. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  79643. __decorate([
  79644. BABYLON.serialize()
  79645. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  79646. __decorate([
  79647. BABYLON.serialize()
  79648. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  79649. __decorate([
  79650. BABYLON.serialize()
  79651. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  79652. __decorate([
  79653. BABYLON.serialize()
  79654. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  79655. __decorate([
  79656. BABYLON.serialize()
  79657. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  79658. __decorate([
  79659. BABYLON.serialize()
  79660. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  79661. __decorate([
  79662. BABYLON.serializeAsColor4()
  79663. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  79664. __decorate([
  79665. BABYLON.serialize()
  79666. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  79667. __decorate([
  79668. BABYLON.serialize()
  79669. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  79670. __decorate([
  79671. BABYLON.serialize()
  79672. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  79673. __decorate([
  79674. BABYLON.serialize()
  79675. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  79676. __decorate([
  79677. BABYLON.serialize()
  79678. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  79679. return ImageProcessingConfiguration;
  79680. }());
  79681. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  79682. })(BABYLON || (BABYLON = {}));
  79683. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  79684. var BABYLON;
  79685. (function (BABYLON) {
  79686. /**
  79687. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  79688. * It can help converting any input color in a desired output one. This can then be used to create effects
  79689. * from sepia, black and white to sixties or futuristic rendering...
  79690. *
  79691. * The only supported format is currently 3dl.
  79692. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  79693. */
  79694. var ColorGradingTexture = /** @class */ (function (_super) {
  79695. __extends(ColorGradingTexture, _super);
  79696. /**
  79697. * Instantiates a ColorGradingTexture from the following parameters.
  79698. *
  79699. * @param url The location of the color gradind data (currently only supporting 3dl)
  79700. * @param scene The scene the texture will be used in
  79701. */
  79702. function ColorGradingTexture(url, scene) {
  79703. var _this = _super.call(this, scene) || this;
  79704. if (!url) {
  79705. return _this;
  79706. }
  79707. _this._engine = scene.getEngine();
  79708. _this._textureMatrix = BABYLON.Matrix.Identity();
  79709. _this.name = url;
  79710. _this.url = url;
  79711. _this.hasAlpha = false;
  79712. _this.isCube = false;
  79713. _this.is3D = _this._engine.webGLVersion > 1;
  79714. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79715. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79716. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79717. _this.anisotropicFilteringLevel = 1;
  79718. _this._texture = _this._getFromCache(url, true);
  79719. if (!_this._texture) {
  79720. if (!scene.useDelayedTextureLoading) {
  79721. _this.loadTexture();
  79722. }
  79723. else {
  79724. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  79725. }
  79726. }
  79727. return _this;
  79728. }
  79729. /**
  79730. * Returns the texture matrix used in most of the material.
  79731. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  79732. */
  79733. ColorGradingTexture.prototype.getTextureMatrix = function () {
  79734. return this._textureMatrix;
  79735. };
  79736. /**
  79737. * Occurs when the file being loaded is a .3dl LUT file.
  79738. */
  79739. ColorGradingTexture.prototype.load3dlTexture = function () {
  79740. var engine = this._engine;
  79741. var texture;
  79742. if (engine.webGLVersion === 1) {
  79743. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79744. }
  79745. else {
  79746. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79747. }
  79748. this._texture = texture;
  79749. var callback = function (text) {
  79750. if (typeof text !== "string") {
  79751. return;
  79752. }
  79753. var data = null;
  79754. var tempData = null;
  79755. var line;
  79756. var lines = text.split('\n');
  79757. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  79758. var maxColor = 0;
  79759. for (var i = 0; i < lines.length; i++) {
  79760. line = lines[i];
  79761. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  79762. continue;
  79763. if (line.indexOf('#') === 0)
  79764. continue;
  79765. var words = line.split(" ");
  79766. if (size === 0) {
  79767. // Number of space + one
  79768. size = words.length;
  79769. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  79770. tempData = new Float32Array(size * size * size * 4);
  79771. continue;
  79772. }
  79773. if (size != 0) {
  79774. var r = Math.max(parseInt(words[0]), 0);
  79775. var g = Math.max(parseInt(words[1]), 0);
  79776. var b = Math.max(parseInt(words[2]), 0);
  79777. maxColor = Math.max(r, maxColor);
  79778. maxColor = Math.max(g, maxColor);
  79779. maxColor = Math.max(b, maxColor);
  79780. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  79781. if (tempData) {
  79782. tempData[pixelStorageIndex + 0] = r;
  79783. tempData[pixelStorageIndex + 1] = g;
  79784. tempData[pixelStorageIndex + 2] = b;
  79785. }
  79786. pixelIndexSlice++;
  79787. if (pixelIndexSlice % size == 0) {
  79788. pixelIndexH++;
  79789. pixelIndexSlice = 0;
  79790. if (pixelIndexH % size == 0) {
  79791. pixelIndexW++;
  79792. pixelIndexH = 0;
  79793. }
  79794. }
  79795. }
  79796. }
  79797. if (tempData && data) {
  79798. for (var i = 0; i < tempData.length; i++) {
  79799. if (i > 0 && (i + 1) % 4 === 0) {
  79800. data[i] = 255;
  79801. }
  79802. else {
  79803. var value = tempData[i];
  79804. data[i] = (value / maxColor * 255);
  79805. }
  79806. }
  79807. }
  79808. if (texture.is3D) {
  79809. texture.updateSize(size, size, size);
  79810. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79811. }
  79812. else {
  79813. texture.updateSize(size * size, size);
  79814. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79815. }
  79816. };
  79817. var scene = this.getScene();
  79818. if (scene) {
  79819. scene._loadFile(this.url, callback);
  79820. }
  79821. else {
  79822. this._engine._loadFile(this.url, callback);
  79823. }
  79824. return this._texture;
  79825. };
  79826. /**
  79827. * Starts the loading process of the texture.
  79828. */
  79829. ColorGradingTexture.prototype.loadTexture = function () {
  79830. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  79831. this.load3dlTexture();
  79832. }
  79833. };
  79834. /**
  79835. * Clones the color gradind texture.
  79836. */
  79837. ColorGradingTexture.prototype.clone = function () {
  79838. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  79839. // Base texture
  79840. newTexture.level = this.level;
  79841. return newTexture;
  79842. };
  79843. /**
  79844. * Called during delayed load for textures.
  79845. */
  79846. ColorGradingTexture.prototype.delayLoad = function () {
  79847. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79848. return;
  79849. }
  79850. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79851. this._texture = this._getFromCache(this.url, true);
  79852. if (!this._texture) {
  79853. this.loadTexture();
  79854. }
  79855. };
  79856. /**
  79857. * Parses a color grading texture serialized by Babylon.
  79858. * @param parsedTexture The texture information being parsedTexture
  79859. * @param scene The scene to load the texture in
  79860. * @param rootUrl The root url of the data assets to load
  79861. * @return A color gradind texture
  79862. */
  79863. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79864. var texture = null;
  79865. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79866. texture = new ColorGradingTexture(parsedTexture.name, scene);
  79867. texture.name = parsedTexture.name;
  79868. texture.level = parsedTexture.level;
  79869. }
  79870. return texture;
  79871. };
  79872. /**
  79873. * Serializes the LUT texture to json format.
  79874. */
  79875. ColorGradingTexture.prototype.serialize = function () {
  79876. if (!this.name) {
  79877. return null;
  79878. }
  79879. var serializationObject = {};
  79880. serializationObject.name = this.name;
  79881. serializationObject.level = this.level;
  79882. serializationObject.customType = "BABYLON.ColorGradingTexture";
  79883. return serializationObject;
  79884. };
  79885. /**
  79886. * Empty line regex stored for GC.
  79887. */
  79888. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  79889. return ColorGradingTexture;
  79890. }(BABYLON.BaseTexture));
  79891. BABYLON.ColorGradingTexture = ColorGradingTexture;
  79892. })(BABYLON || (BABYLON = {}));
  79893. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  79894. var BABYLON;
  79895. (function (BABYLON) {
  79896. /**
  79897. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  79898. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  79899. * 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;
  79900. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  79901. */
  79902. var ColorCurves = /** @class */ (function () {
  79903. function ColorCurves() {
  79904. this._dirty = true;
  79905. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  79906. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  79907. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79908. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  79909. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79910. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  79911. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  79912. this._globalHue = 30;
  79913. this._globalDensity = 0;
  79914. this._globalSaturation = 0;
  79915. this._globalExposure = 0;
  79916. this._highlightsHue = 30;
  79917. this._highlightsDensity = 0;
  79918. this._highlightsSaturation = 0;
  79919. this._highlightsExposure = 0;
  79920. this._midtonesHue = 30;
  79921. this._midtonesDensity = 0;
  79922. this._midtonesSaturation = 0;
  79923. this._midtonesExposure = 0;
  79924. this._shadowsHue = 30;
  79925. this._shadowsDensity = 0;
  79926. this._shadowsSaturation = 0;
  79927. this._shadowsExposure = 0;
  79928. }
  79929. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  79930. /**
  79931. * Gets the global Hue value.
  79932. * 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).
  79933. */
  79934. get: function () {
  79935. return this._globalHue;
  79936. },
  79937. /**
  79938. * Sets the global Hue value.
  79939. * 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).
  79940. */
  79941. set: function (value) {
  79942. this._globalHue = value;
  79943. this._dirty = true;
  79944. },
  79945. enumerable: true,
  79946. configurable: true
  79947. });
  79948. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  79949. /**
  79950. * Gets the global Density value.
  79951. * 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.
  79952. * Values less than zero provide a filter of opposite hue.
  79953. */
  79954. get: function () {
  79955. return this._globalDensity;
  79956. },
  79957. /**
  79958. * Sets the global Density value.
  79959. * 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.
  79960. * Values less than zero provide a filter of opposite hue.
  79961. */
  79962. set: function (value) {
  79963. this._globalDensity = value;
  79964. this._dirty = true;
  79965. },
  79966. enumerable: true,
  79967. configurable: true
  79968. });
  79969. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  79970. /**
  79971. * Gets the global Saturation value.
  79972. * 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.
  79973. */
  79974. get: function () {
  79975. return this._globalSaturation;
  79976. },
  79977. /**
  79978. * Sets the global Saturation value.
  79979. * 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.
  79980. */
  79981. set: function (value) {
  79982. this._globalSaturation = value;
  79983. this._dirty = true;
  79984. },
  79985. enumerable: true,
  79986. configurable: true
  79987. });
  79988. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  79989. /**
  79990. * Gets the global Exposure value.
  79991. * 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.
  79992. */
  79993. get: function () {
  79994. return this._globalExposure;
  79995. },
  79996. /**
  79997. * Sets the global Exposure value.
  79998. * 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.
  79999. */
  80000. set: function (value) {
  80001. this._globalExposure = value;
  80002. this._dirty = true;
  80003. },
  80004. enumerable: true,
  80005. configurable: true
  80006. });
  80007. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  80008. /**
  80009. * Gets the highlights Hue value.
  80010. * 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).
  80011. */
  80012. get: function () {
  80013. return this._highlightsHue;
  80014. },
  80015. /**
  80016. * Sets the highlights Hue value.
  80017. * 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).
  80018. */
  80019. set: function (value) {
  80020. this._highlightsHue = value;
  80021. this._dirty = true;
  80022. },
  80023. enumerable: true,
  80024. configurable: true
  80025. });
  80026. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  80027. /**
  80028. * Gets the highlights Density value.
  80029. * 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.
  80030. * Values less than zero provide a filter of opposite hue.
  80031. */
  80032. get: function () {
  80033. return this._highlightsDensity;
  80034. },
  80035. /**
  80036. * Sets the highlights Density value.
  80037. * 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.
  80038. * Values less than zero provide a filter of opposite hue.
  80039. */
  80040. set: function (value) {
  80041. this._highlightsDensity = value;
  80042. this._dirty = true;
  80043. },
  80044. enumerable: true,
  80045. configurable: true
  80046. });
  80047. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  80048. /**
  80049. * Gets the highlights Saturation value.
  80050. * 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.
  80051. */
  80052. get: function () {
  80053. return this._highlightsSaturation;
  80054. },
  80055. /**
  80056. * Sets the highlights Saturation value.
  80057. * 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.
  80058. */
  80059. set: function (value) {
  80060. this._highlightsSaturation = value;
  80061. this._dirty = true;
  80062. },
  80063. enumerable: true,
  80064. configurable: true
  80065. });
  80066. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  80067. /**
  80068. * Gets the highlights Exposure value.
  80069. * 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.
  80070. */
  80071. get: function () {
  80072. return this._highlightsExposure;
  80073. },
  80074. /**
  80075. * Sets the highlights Exposure value.
  80076. * 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.
  80077. */
  80078. set: function (value) {
  80079. this._highlightsExposure = value;
  80080. this._dirty = true;
  80081. },
  80082. enumerable: true,
  80083. configurable: true
  80084. });
  80085. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  80086. /**
  80087. * Gets the midtones Hue value.
  80088. * 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).
  80089. */
  80090. get: function () {
  80091. return this._midtonesHue;
  80092. },
  80093. /**
  80094. * Sets the midtones Hue value.
  80095. * 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).
  80096. */
  80097. set: function (value) {
  80098. this._midtonesHue = value;
  80099. this._dirty = true;
  80100. },
  80101. enumerable: true,
  80102. configurable: true
  80103. });
  80104. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  80105. /**
  80106. * Gets the midtones Density value.
  80107. * 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.
  80108. * Values less than zero provide a filter of opposite hue.
  80109. */
  80110. get: function () {
  80111. return this._midtonesDensity;
  80112. },
  80113. /**
  80114. * Sets the midtones Density value.
  80115. * 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.
  80116. * Values less than zero provide a filter of opposite hue.
  80117. */
  80118. set: function (value) {
  80119. this._midtonesDensity = value;
  80120. this._dirty = true;
  80121. },
  80122. enumerable: true,
  80123. configurable: true
  80124. });
  80125. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  80126. /**
  80127. * Gets the midtones Saturation value.
  80128. * 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.
  80129. */
  80130. get: function () {
  80131. return this._midtonesSaturation;
  80132. },
  80133. /**
  80134. * Sets the midtones Saturation value.
  80135. * 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.
  80136. */
  80137. set: function (value) {
  80138. this._midtonesSaturation = value;
  80139. this._dirty = true;
  80140. },
  80141. enumerable: true,
  80142. configurable: true
  80143. });
  80144. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  80145. /**
  80146. * Gets the midtones Exposure value.
  80147. * 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.
  80148. */
  80149. get: function () {
  80150. return this._midtonesExposure;
  80151. },
  80152. /**
  80153. * Sets the midtones Exposure value.
  80154. * 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.
  80155. */
  80156. set: function (value) {
  80157. this._midtonesExposure = value;
  80158. this._dirty = true;
  80159. },
  80160. enumerable: true,
  80161. configurable: true
  80162. });
  80163. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  80164. /**
  80165. * Gets the shadows Hue value.
  80166. * 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).
  80167. */
  80168. get: function () {
  80169. return this._shadowsHue;
  80170. },
  80171. /**
  80172. * Sets the shadows Hue value.
  80173. * 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).
  80174. */
  80175. set: function (value) {
  80176. this._shadowsHue = value;
  80177. this._dirty = true;
  80178. },
  80179. enumerable: true,
  80180. configurable: true
  80181. });
  80182. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  80183. /**
  80184. * Gets the shadows Density value.
  80185. * 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.
  80186. * Values less than zero provide a filter of opposite hue.
  80187. */
  80188. get: function () {
  80189. return this._shadowsDensity;
  80190. },
  80191. /**
  80192. * Sets the shadows Density value.
  80193. * 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.
  80194. * Values less than zero provide a filter of opposite hue.
  80195. */
  80196. set: function (value) {
  80197. this._shadowsDensity = value;
  80198. this._dirty = true;
  80199. },
  80200. enumerable: true,
  80201. configurable: true
  80202. });
  80203. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  80204. /**
  80205. * Gets the shadows Saturation value.
  80206. * 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.
  80207. */
  80208. get: function () {
  80209. return this._shadowsSaturation;
  80210. },
  80211. /**
  80212. * Sets the shadows Saturation value.
  80213. * 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.
  80214. */
  80215. set: function (value) {
  80216. this._shadowsSaturation = value;
  80217. this._dirty = true;
  80218. },
  80219. enumerable: true,
  80220. configurable: true
  80221. });
  80222. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  80223. /**
  80224. * Gets the shadows Exposure value.
  80225. * 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.
  80226. */
  80227. get: function () {
  80228. return this._shadowsExposure;
  80229. },
  80230. /**
  80231. * Sets the shadows Exposure value.
  80232. * 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.
  80233. */
  80234. set: function (value) {
  80235. this._shadowsExposure = value;
  80236. this._dirty = true;
  80237. },
  80238. enumerable: true,
  80239. configurable: true
  80240. });
  80241. ColorCurves.prototype.getClassName = function () {
  80242. return "ColorCurves";
  80243. };
  80244. /**
  80245. * Binds the color curves to the shader.
  80246. * @param colorCurves The color curve to bind
  80247. * @param effect The effect to bind to
  80248. */
  80249. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  80250. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  80251. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  80252. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  80253. if (colorCurves._dirty) {
  80254. colorCurves._dirty = false;
  80255. // Fill in global info.
  80256. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  80257. // Compute highlights info.
  80258. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  80259. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  80260. // Compute midtones info.
  80261. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  80262. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  80263. // Compute shadows info.
  80264. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  80265. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  80266. // Compute deltas (neutral is midtones).
  80267. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  80268. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  80269. }
  80270. if (effect) {
  80271. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  80272. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  80273. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  80274. }
  80275. };
  80276. /**
  80277. * Prepare the list of uniforms associated with the ColorCurves effects.
  80278. * @param uniformsList The list of uniforms used in the effect
  80279. */
  80280. ColorCurves.PrepareUniforms = function (uniformsList) {
  80281. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  80282. };
  80283. /**
  80284. * Returns color grading data based on a hue, density, saturation and exposure value.
  80285. * @param filterHue The hue of the color filter.
  80286. * @param filterDensity The density of the color filter.
  80287. * @param saturation The saturation.
  80288. * @param exposure The exposure.
  80289. * @param result The result data container.
  80290. */
  80291. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  80292. if (hue == null) {
  80293. return;
  80294. }
  80295. hue = ColorCurves.clamp(hue, 0, 360);
  80296. density = ColorCurves.clamp(density, -100, 100);
  80297. saturation = ColorCurves.clamp(saturation, -100, 100);
  80298. exposure = ColorCurves.clamp(exposure, -100, 100);
  80299. // Remap the slider/config filter density with non-linear mapping and also scale by half
  80300. // so that the maximum filter density is only 50% control. This provides fine control
  80301. // for small values and reasonable range.
  80302. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  80303. density *= 0.5;
  80304. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  80305. if (density < 0) {
  80306. density *= -1;
  80307. hue = (hue + 180) % 360;
  80308. }
  80309. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  80310. result.scaleToRef(2, result);
  80311. result.a = 1 + 0.01 * saturation;
  80312. };
  80313. /**
  80314. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  80315. * @param value The input slider value in range [-100,100].
  80316. * @returns Adjusted value.
  80317. */
  80318. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  80319. value /= 100;
  80320. var x = Math.abs(value);
  80321. x = Math.pow(x, 2);
  80322. if (value < 0) {
  80323. x *= -1;
  80324. }
  80325. x *= 100;
  80326. return x;
  80327. };
  80328. /**
  80329. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  80330. * @param hue The hue (H) input.
  80331. * @param saturation The saturation (S) input.
  80332. * @param brightness The brightness (B) input.
  80333. * @result An RGBA color represented as Vector4.
  80334. */
  80335. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  80336. var h = ColorCurves.clamp(hue, 0, 360);
  80337. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  80338. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  80339. if (s === 0) {
  80340. result.r = v;
  80341. result.g = v;
  80342. result.b = v;
  80343. }
  80344. else {
  80345. // sector 0 to 5
  80346. h /= 60;
  80347. var i = Math.floor(h);
  80348. // fractional part of h
  80349. var f = h - i;
  80350. var p = v * (1 - s);
  80351. var q = v * (1 - s * f);
  80352. var t = v * (1 - s * (1 - f));
  80353. switch (i) {
  80354. case 0:
  80355. result.r = v;
  80356. result.g = t;
  80357. result.b = p;
  80358. break;
  80359. case 1:
  80360. result.r = q;
  80361. result.g = v;
  80362. result.b = p;
  80363. break;
  80364. case 2:
  80365. result.r = p;
  80366. result.g = v;
  80367. result.b = t;
  80368. break;
  80369. case 3:
  80370. result.r = p;
  80371. result.g = q;
  80372. result.b = v;
  80373. break;
  80374. case 4:
  80375. result.r = t;
  80376. result.g = p;
  80377. result.b = v;
  80378. break;
  80379. default: // case 5:
  80380. result.r = v;
  80381. result.g = p;
  80382. result.b = q;
  80383. break;
  80384. }
  80385. }
  80386. result.a = 1;
  80387. };
  80388. /**
  80389. * Returns a value clamped between min and max
  80390. * @param value The value to clamp
  80391. * @param min The minimum of value
  80392. * @param max The maximum of value
  80393. * @returns The clamped value.
  80394. */
  80395. ColorCurves.clamp = function (value, min, max) {
  80396. return Math.min(Math.max(value, min), max);
  80397. };
  80398. /**
  80399. * Clones the current color curve instance.
  80400. * @return The cloned curves
  80401. */
  80402. ColorCurves.prototype.clone = function () {
  80403. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  80404. };
  80405. /**
  80406. * Serializes the current color curve instance to a json representation.
  80407. * @return a JSON representation
  80408. */
  80409. ColorCurves.prototype.serialize = function () {
  80410. return BABYLON.SerializationHelper.Serialize(this);
  80411. };
  80412. /**
  80413. * Parses the color curve from a json representation.
  80414. * @param source the JSON source to parse
  80415. * @return The parsed curves
  80416. */
  80417. ColorCurves.Parse = function (source) {
  80418. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  80419. };
  80420. __decorate([
  80421. BABYLON.serialize()
  80422. ], ColorCurves.prototype, "_globalHue", void 0);
  80423. __decorate([
  80424. BABYLON.serialize()
  80425. ], ColorCurves.prototype, "_globalDensity", void 0);
  80426. __decorate([
  80427. BABYLON.serialize()
  80428. ], ColorCurves.prototype, "_globalSaturation", void 0);
  80429. __decorate([
  80430. BABYLON.serialize()
  80431. ], ColorCurves.prototype, "_globalExposure", void 0);
  80432. __decorate([
  80433. BABYLON.serialize()
  80434. ], ColorCurves.prototype, "_highlightsHue", void 0);
  80435. __decorate([
  80436. BABYLON.serialize()
  80437. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  80438. __decorate([
  80439. BABYLON.serialize()
  80440. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  80441. __decorate([
  80442. BABYLON.serialize()
  80443. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  80444. __decorate([
  80445. BABYLON.serialize()
  80446. ], ColorCurves.prototype, "_midtonesHue", void 0);
  80447. __decorate([
  80448. BABYLON.serialize()
  80449. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  80450. __decorate([
  80451. BABYLON.serialize()
  80452. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  80453. __decorate([
  80454. BABYLON.serialize()
  80455. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  80456. return ColorCurves;
  80457. }());
  80458. BABYLON.ColorCurves = ColorCurves;
  80459. })(BABYLON || (BABYLON = {}));
  80460. //# sourceMappingURL=babylon.colorCurves.js.map
  80461. var BABYLON;
  80462. (function (BABYLON) {
  80463. var RefractionPostProcess = /** @class */ (function (_super) {
  80464. __extends(RefractionPostProcess, _super);
  80465. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  80466. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  80467. _this.color = color;
  80468. _this.depth = depth;
  80469. _this.colorLevel = colorLevel;
  80470. _this._ownRefractionTexture = true;
  80471. _this.onActivateObservable.add(function (cam) {
  80472. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  80473. });
  80474. _this.onApplyObservable.add(function (effect) {
  80475. effect.setColor3("baseColor", _this.color);
  80476. effect.setFloat("depth", _this.depth);
  80477. effect.setFloat("colorLevel", _this.colorLevel);
  80478. effect.setTexture("refractionSampler", _this._refTexture);
  80479. });
  80480. return _this;
  80481. }
  80482. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  80483. /**
  80484. * Gets or sets the refraction texture
  80485. * Please note that you are responsible for disposing the texture if you set it manually
  80486. */
  80487. get: function () {
  80488. return this._refTexture;
  80489. },
  80490. set: function (value) {
  80491. if (this._refTexture && this._ownRefractionTexture) {
  80492. this._refTexture.dispose();
  80493. }
  80494. this._refTexture = value;
  80495. this._ownRefractionTexture = false;
  80496. },
  80497. enumerable: true,
  80498. configurable: true
  80499. });
  80500. // Methods
  80501. RefractionPostProcess.prototype.dispose = function (camera) {
  80502. if (this._refTexture && this._ownRefractionTexture) {
  80503. this._refTexture.dispose();
  80504. this._refTexture = null;
  80505. }
  80506. _super.prototype.dispose.call(this, camera);
  80507. };
  80508. return RefractionPostProcess;
  80509. }(BABYLON.PostProcess));
  80510. BABYLON.RefractionPostProcess = RefractionPostProcess;
  80511. })(BABYLON || (BABYLON = {}));
  80512. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  80513. var BABYLON;
  80514. (function (BABYLON) {
  80515. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  80516. __extends(BlackAndWhitePostProcess, _super);
  80517. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  80518. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  80519. _this.degree = 1;
  80520. _this.onApplyObservable.add(function (effect) {
  80521. effect.setFloat("degree", _this.degree);
  80522. });
  80523. return _this;
  80524. }
  80525. return BlackAndWhitePostProcess;
  80526. }(BABYLON.PostProcess));
  80527. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  80528. })(BABYLON || (BABYLON = {}));
  80529. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  80530. var BABYLON;
  80531. (function (BABYLON) {
  80532. /**
  80533. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  80534. * input texture to perform effects such as edge detection or sharpening
  80535. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  80536. */
  80537. var ConvolutionPostProcess = /** @class */ (function (_super) {
  80538. __extends(ConvolutionPostProcess, _super);
  80539. /**
  80540. * Creates a new instance ConvolutionPostProcess
  80541. * @param name The name of the effect.
  80542. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  80543. * @param options The required width/height ratio to downsize to before computing the render pass.
  80544. * @param camera The camera to apply the render pass to.
  80545. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80546. * @param engine The engine which the post process will be applied. (default: current engine)
  80547. * @param reusable If the post process can be reused on the same frame. (default: false)
  80548. * @param textureType Type of textures used when performing the post process. (default: 0)
  80549. */
  80550. function ConvolutionPostProcess(name,
  80551. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  80552. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  80553. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80554. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  80555. _this.kernel = kernel;
  80556. _this.onApply = function (effect) {
  80557. effect.setFloat2("screenSize", _this.width, _this.height);
  80558. effect.setArray("kernel", _this.kernel);
  80559. };
  80560. return _this;
  80561. }
  80562. // Statics
  80563. /**
  80564. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80565. */
  80566. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  80567. /**
  80568. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80569. */
  80570. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  80571. /**
  80572. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80573. */
  80574. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  80575. /**
  80576. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80577. */
  80578. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  80579. /**
  80580. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80581. */
  80582. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  80583. /**
  80584. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80585. */
  80586. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  80587. return ConvolutionPostProcess;
  80588. }(BABYLON.PostProcess));
  80589. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  80590. })(BABYLON || (BABYLON = {}));
  80591. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  80592. var BABYLON;
  80593. (function (BABYLON) {
  80594. var FilterPostProcess = /** @class */ (function (_super) {
  80595. __extends(FilterPostProcess, _super);
  80596. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  80597. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  80598. _this.kernelMatrix = kernelMatrix;
  80599. _this.onApply = function (effect) {
  80600. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  80601. };
  80602. return _this;
  80603. }
  80604. return FilterPostProcess;
  80605. }(BABYLON.PostProcess));
  80606. BABYLON.FilterPostProcess = FilterPostProcess;
  80607. })(BABYLON || (BABYLON = {}));
  80608. //# sourceMappingURL=babylon.filterPostProcess.js.map
  80609. var BABYLON;
  80610. (function (BABYLON) {
  80611. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  80612. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  80613. __extends(VolumetricLightScatteringPostProcess, _super);
  80614. /**
  80615. * @constructor
  80616. * @param {string} name - The post-process name
  80617. * @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)
  80618. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  80619. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  80620. * @param {number} samples - The post-process quality, default 100
  80621. * @param {number} samplingMode - The post-process filtering mode
  80622. * @param {BABYLON.Engine} engine - The babylon engine
  80623. * @param {boolean} reusable - If the post-process is reusable
  80624. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  80625. */
  80626. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  80627. if (samples === void 0) { samples = 100; }
  80628. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80629. 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;
  80630. _this._screenCoordinates = BABYLON.Vector2.Zero();
  80631. /**
  80632. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  80633. */
  80634. _this.customMeshPosition = BABYLON.Vector3.Zero();
  80635. /**
  80636. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  80637. */
  80638. _this.useCustomMeshPosition = false;
  80639. /**
  80640. * If the post-process should inverse the light scattering direction
  80641. */
  80642. _this.invert = true;
  80643. /**
  80644. * Array containing the excluded meshes not rendered in the internal pass
  80645. */
  80646. _this.excludedMeshes = new Array();
  80647. /**
  80648. * Controls the overall intensity of the post-process
  80649. */
  80650. _this.exposure = 0.3;
  80651. /**
  80652. * Dissipates each sample's contribution in range [0, 1]
  80653. */
  80654. _this.decay = 0.96815;
  80655. /**
  80656. * Controls the overall intensity of each sample
  80657. */
  80658. _this.weight = 0.58767;
  80659. /**
  80660. * Controls the density of each sample
  80661. */
  80662. _this.density = 0.926;
  80663. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  80664. engine = scene.getEngine();
  80665. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  80666. // Configure mesh
  80667. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  80668. // Configure
  80669. _this._createPass(scene, ratio.passRatio || ratio);
  80670. _this.onActivate = function (camera) {
  80671. if (!_this.isSupported) {
  80672. _this.dispose(camera);
  80673. }
  80674. _this.onActivate = null;
  80675. };
  80676. _this.onApplyObservable.add(function (effect) {
  80677. _this._updateMeshScreenCoordinates(scene);
  80678. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  80679. effect.setFloat("exposure", _this.exposure);
  80680. effect.setFloat("decay", _this.decay);
  80681. effect.setFloat("weight", _this.weight);
  80682. effect.setFloat("density", _this.density);
  80683. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  80684. });
  80685. return _this;
  80686. }
  80687. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  80688. get: function () {
  80689. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  80690. return false;
  80691. },
  80692. set: function (useDiffuseColor) {
  80693. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  80694. },
  80695. enumerable: true,
  80696. configurable: true
  80697. });
  80698. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  80699. return "VolumetricLightScatteringPostProcess";
  80700. };
  80701. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  80702. var mesh = subMesh.getMesh();
  80703. // Render this.mesh as default
  80704. if (mesh === this.mesh && mesh.material) {
  80705. return mesh.material.isReady(mesh);
  80706. }
  80707. var defines = [];
  80708. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80709. var material = subMesh.getMaterial();
  80710. // Alpha test
  80711. if (material) {
  80712. if (material.needAlphaTesting()) {
  80713. defines.push("#define ALPHATEST");
  80714. }
  80715. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80716. attribs.push(BABYLON.VertexBuffer.UVKind);
  80717. defines.push("#define UV1");
  80718. }
  80719. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80720. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80721. defines.push("#define UV2");
  80722. }
  80723. }
  80724. // Bones
  80725. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80726. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80727. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80728. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80729. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  80730. }
  80731. else {
  80732. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80733. }
  80734. // Instances
  80735. if (useInstances) {
  80736. defines.push("#define INSTANCES");
  80737. attribs.push("world0");
  80738. attribs.push("world1");
  80739. attribs.push("world2");
  80740. attribs.push("world3");
  80741. }
  80742. // Get correct effect
  80743. var join = defines.join("\n");
  80744. if (this._cachedDefines !== join) {
  80745. this._cachedDefines = join;
  80746. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  80747. }
  80748. return this._volumetricLightScatteringPass.isReady();
  80749. };
  80750. /**
  80751. * Sets the new light position for light scattering effect
  80752. * @param {BABYLON.Vector3} The new custom light position
  80753. */
  80754. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  80755. this.customMeshPosition = position;
  80756. };
  80757. /**
  80758. * Returns the light position for light scattering effect
  80759. * @return {BABYLON.Vector3} The custom light position
  80760. */
  80761. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  80762. return this.customMeshPosition;
  80763. };
  80764. /**
  80765. * Disposes the internal assets and detaches the post-process from the camera
  80766. */
  80767. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  80768. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  80769. if (rttIndex !== -1) {
  80770. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  80771. }
  80772. this._volumetricLightScatteringRTT.dispose();
  80773. _super.prototype.dispose.call(this, camera);
  80774. };
  80775. /**
  80776. * Returns the render target texture used by the post-process
  80777. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  80778. */
  80779. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  80780. return this._volumetricLightScatteringRTT;
  80781. };
  80782. // Private methods
  80783. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  80784. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  80785. return true;
  80786. }
  80787. return false;
  80788. };
  80789. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  80790. var _this = this;
  80791. var engine = scene.getEngine();
  80792. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80793. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80794. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80795. this._volumetricLightScatteringRTT.renderList = null;
  80796. this._volumetricLightScatteringRTT.renderParticles = false;
  80797. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  80798. var camera = this.getCamera();
  80799. if (camera) {
  80800. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80801. }
  80802. else {
  80803. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80804. }
  80805. // Custom render function for submeshes
  80806. var renderSubMesh = function (subMesh) {
  80807. var mesh = subMesh.getRenderingMesh();
  80808. if (_this._meshExcluded(mesh)) {
  80809. return;
  80810. }
  80811. var material = subMesh.getMaterial();
  80812. if (!material) {
  80813. return;
  80814. }
  80815. var scene = mesh.getScene();
  80816. var engine = scene.getEngine();
  80817. // Culling
  80818. engine.setState(material.backFaceCulling);
  80819. // Managing instances
  80820. var batch = mesh._getInstancesRenderList(subMesh._id);
  80821. if (batch.mustReturn) {
  80822. return;
  80823. }
  80824. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80825. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  80826. var effect = _this._volumetricLightScatteringPass;
  80827. if (mesh === _this.mesh) {
  80828. if (subMesh.effect) {
  80829. effect = subMesh.effect;
  80830. }
  80831. else {
  80832. effect = material.getEffect();
  80833. }
  80834. }
  80835. engine.enableEffect(effect);
  80836. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  80837. if (mesh === _this.mesh) {
  80838. material.bind(mesh.getWorldMatrix(), mesh);
  80839. }
  80840. else {
  80841. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  80842. // Alpha test
  80843. if (material && material.needAlphaTesting()) {
  80844. var alphaTexture = material.getAlphaTestTexture();
  80845. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  80846. if (alphaTexture) {
  80847. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80848. }
  80849. }
  80850. // Bones
  80851. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80852. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80853. }
  80854. }
  80855. // Draw
  80856. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  80857. }
  80858. };
  80859. // Render target texture callbacks
  80860. var savedSceneClearColor;
  80861. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  80862. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  80863. savedSceneClearColor = scene.clearColor;
  80864. scene.clearColor = sceneClearColor;
  80865. });
  80866. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  80867. scene.clearColor = savedSceneClearColor;
  80868. });
  80869. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80870. var engine = scene.getEngine();
  80871. var index;
  80872. if (depthOnlySubMeshes.length) {
  80873. engine.setColorWrite(false);
  80874. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80875. renderSubMesh(depthOnlySubMeshes.data[index]);
  80876. }
  80877. engine.setColorWrite(true);
  80878. }
  80879. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80880. renderSubMesh(opaqueSubMeshes.data[index]);
  80881. }
  80882. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80883. renderSubMesh(alphaTestSubMeshes.data[index]);
  80884. }
  80885. if (transparentSubMeshes.length) {
  80886. // Sort sub meshes
  80887. for (index = 0; index < transparentSubMeshes.length; index++) {
  80888. var submesh = transparentSubMeshes.data[index];
  80889. var boundingInfo = submesh.getBoundingInfo();
  80890. if (boundingInfo && scene.activeCamera) {
  80891. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  80892. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  80893. }
  80894. }
  80895. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  80896. sortedArray.sort(function (a, b) {
  80897. // Alpha index first
  80898. if (a._alphaIndex > b._alphaIndex) {
  80899. return 1;
  80900. }
  80901. if (a._alphaIndex < b._alphaIndex) {
  80902. return -1;
  80903. }
  80904. // Then distance to camera
  80905. if (a._distanceToCamera < b._distanceToCamera) {
  80906. return 1;
  80907. }
  80908. if (a._distanceToCamera > b._distanceToCamera) {
  80909. return -1;
  80910. }
  80911. return 0;
  80912. });
  80913. // Render sub meshes
  80914. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  80915. for (index = 0; index < sortedArray.length; index++) {
  80916. renderSubMesh(sortedArray[index]);
  80917. }
  80918. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80919. }
  80920. };
  80921. };
  80922. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  80923. var transform = scene.getTransformMatrix();
  80924. var meshPosition;
  80925. if (this.useCustomMeshPosition) {
  80926. meshPosition = this.customMeshPosition;
  80927. }
  80928. else if (this.attachedNode) {
  80929. meshPosition = this.attachedNode.position;
  80930. }
  80931. else {
  80932. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  80933. }
  80934. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  80935. this._screenCoordinates.x = pos.x / this._viewPort.width;
  80936. this._screenCoordinates.y = pos.y / this._viewPort.height;
  80937. if (this.invert)
  80938. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  80939. };
  80940. // Static methods
  80941. /**
  80942. * Creates a default mesh for the Volumeric Light Scattering post-process
  80943. * @param {string} The mesh name
  80944. * @param {BABYLON.Scene} The scene where to create the mesh
  80945. * @return {BABYLON.Mesh} the default mesh
  80946. */
  80947. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  80948. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  80949. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  80950. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  80951. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  80952. mesh.material = material;
  80953. return mesh;
  80954. };
  80955. __decorate([
  80956. BABYLON.serializeAsVector3()
  80957. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  80958. __decorate([
  80959. BABYLON.serialize()
  80960. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  80961. __decorate([
  80962. BABYLON.serialize()
  80963. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  80964. __decorate([
  80965. BABYLON.serializeAsMeshReference()
  80966. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  80967. __decorate([
  80968. BABYLON.serialize()
  80969. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  80970. __decorate([
  80971. BABYLON.serialize()
  80972. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  80973. __decorate([
  80974. BABYLON.serialize()
  80975. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  80976. __decorate([
  80977. BABYLON.serialize()
  80978. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  80979. __decorate([
  80980. BABYLON.serialize()
  80981. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  80982. return VolumetricLightScatteringPostProcess;
  80983. }(BABYLON.PostProcess));
  80984. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  80985. })(BABYLON || (BABYLON = {}));
  80986. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  80987. //
  80988. // This post-process allows the modification of rendered colors by using
  80989. // a 'look-up table' (LUT). This effect is also called Color Grading.
  80990. //
  80991. // The object needs to be provided an url to a texture containing the color
  80992. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  80993. // Use an image editing software to tweak the LUT to match your needs.
  80994. //
  80995. // For an example of a color LUT, see here:
  80996. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  80997. // For explanations on color grading, see here:
  80998. // http://udn.epicgames.com/Three/ColorGrading.html
  80999. //
  81000. var BABYLON;
  81001. (function (BABYLON) {
  81002. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  81003. __extends(ColorCorrectionPostProcess, _super);
  81004. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  81005. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  81006. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81007. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  81008. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81009. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81010. _this.onApply = function (effect) {
  81011. effect.setTexture("colorTable", _this._colorTableTexture);
  81012. };
  81013. return _this;
  81014. }
  81015. return ColorCorrectionPostProcess;
  81016. }(BABYLON.PostProcess));
  81017. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  81018. })(BABYLON || (BABYLON = {}));
  81019. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  81020. var BABYLON;
  81021. (function (BABYLON) {
  81022. /** Defines operator used for tonemapping */
  81023. var TonemappingOperator;
  81024. (function (TonemappingOperator) {
  81025. /** Hable */
  81026. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  81027. /** Reinhard */
  81028. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  81029. /** HejiDawson */
  81030. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  81031. /** Photographic */
  81032. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  81033. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  81034. ;
  81035. /**
  81036. * Defines a post process to apply tone mapping
  81037. */
  81038. var TonemapPostProcess = /** @class */ (function (_super) {
  81039. __extends(TonemapPostProcess, _super);
  81040. /**
  81041. * Creates a new TonemapPostProcess
  81042. * @param name defines the name of the postprocess
  81043. * @param _operator defines the operator to use
  81044. * @param exposureAdjustment defines the required exposure adjustement
  81045. * @param camera defines the camera to use (can be null)
  81046. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  81047. * @param engine defines the hosting engine (can be ignore if camera is set)
  81048. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  81049. */
  81050. function TonemapPostProcess(name, _operator,
  81051. /** Defines the required exposure adjustement */
  81052. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  81053. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81054. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81055. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  81056. _this._operator = _operator;
  81057. _this.exposureAdjustment = exposureAdjustment;
  81058. var defines = "#define ";
  81059. if (_this._operator === TonemappingOperator.Hable)
  81060. defines += "HABLE_TONEMAPPING";
  81061. else if (_this._operator === TonemappingOperator.Reinhard)
  81062. defines += "REINHARD_TONEMAPPING";
  81063. else if (_this._operator === TonemappingOperator.HejiDawson)
  81064. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  81065. else if (_this._operator === TonemappingOperator.Photographic)
  81066. defines += "PHOTOGRAPHIC_TONEMAPPING";
  81067. //sadly a second call to create the effect.
  81068. _this.updateEffect(defines);
  81069. _this.onApply = function (effect) {
  81070. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  81071. };
  81072. return _this;
  81073. }
  81074. return TonemapPostProcess;
  81075. }(BABYLON.PostProcess));
  81076. BABYLON.TonemapPostProcess = TonemapPostProcess;
  81077. })(BABYLON || (BABYLON = {}));
  81078. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  81079. var BABYLON;
  81080. (function (BABYLON) {
  81081. var DisplayPassPostProcess = /** @class */ (function (_super) {
  81082. __extends(DisplayPassPostProcess, _super);
  81083. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  81084. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  81085. }
  81086. return DisplayPassPostProcess;
  81087. }(BABYLON.PostProcess));
  81088. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  81089. })(BABYLON || (BABYLON = {}));
  81090. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  81091. var BABYLON;
  81092. (function (BABYLON) {
  81093. var HighlightsPostProcess = /** @class */ (function (_super) {
  81094. __extends(HighlightsPostProcess, _super);
  81095. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  81096. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81097. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  81098. }
  81099. return HighlightsPostProcess;
  81100. }(BABYLON.PostProcess));
  81101. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  81102. })(BABYLON || (BABYLON = {}));
  81103. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  81104. var BABYLON;
  81105. (function (BABYLON) {
  81106. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  81107. __extends(ImageProcessingPostProcess, _super);
  81108. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  81109. if (camera === void 0) { camera = null; }
  81110. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81111. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  81112. _this._fromLinearSpace = true;
  81113. /**
  81114. * Defines cache preventing GC.
  81115. */
  81116. _this._defines = {
  81117. IMAGEPROCESSING: false,
  81118. VIGNETTE: false,
  81119. VIGNETTEBLENDMODEMULTIPLY: false,
  81120. VIGNETTEBLENDMODEOPAQUE: false,
  81121. TONEMAPPING: false,
  81122. CONTRAST: false,
  81123. COLORCURVES: false,
  81124. COLORGRADING: false,
  81125. COLORGRADING3D: false,
  81126. FROMLINEARSPACE: false,
  81127. SAMPLER3DGREENDEPTH: false,
  81128. SAMPLER3DBGRMAP: false,
  81129. IMAGEPROCESSINGPOSTPROCESS: false,
  81130. EXPOSURE: false,
  81131. };
  81132. // Setup the configuration as forced by the constructor. This would then not force the
  81133. // scene materials output in linear space and let untouched the default forward pass.
  81134. if (imageProcessingConfiguration) {
  81135. imageProcessingConfiguration.applyByPostProcess = true;
  81136. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  81137. // This will cause the shader to be compiled
  81138. _this.fromLinearSpace = false;
  81139. }
  81140. // Setup the default processing configuration to the scene.
  81141. else {
  81142. _this._attachImageProcessingConfiguration(null, true);
  81143. _this.imageProcessingConfiguration.applyByPostProcess = true;
  81144. }
  81145. _this.onApply = function (effect) {
  81146. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  81147. };
  81148. return _this;
  81149. }
  81150. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  81151. /**
  81152. * Gets the image processing configuration used either in this material.
  81153. */
  81154. get: function () {
  81155. return this._imageProcessingConfiguration;
  81156. },
  81157. /**
  81158. * Sets the Default image processing configuration used either in the this material.
  81159. *
  81160. * If sets to null, the scene one is in use.
  81161. */
  81162. set: function (value) {
  81163. this._attachImageProcessingConfiguration(value);
  81164. },
  81165. enumerable: true,
  81166. configurable: true
  81167. });
  81168. /**
  81169. * Attaches a new image processing configuration to the PBR Material.
  81170. * @param configuration
  81171. */
  81172. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  81173. var _this = this;
  81174. if (doNotBuild === void 0) { doNotBuild = false; }
  81175. if (configuration === this._imageProcessingConfiguration) {
  81176. return;
  81177. }
  81178. // Detaches observer.
  81179. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  81180. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  81181. }
  81182. // Pick the scene configuration if needed.
  81183. if (!configuration) {
  81184. var scene = null;
  81185. var engine = this.getEngine();
  81186. var camera = this.getCamera();
  81187. if (camera) {
  81188. scene = camera.getScene();
  81189. }
  81190. else if (engine && engine.scenes) {
  81191. var scenes = engine.scenes;
  81192. scene = scenes[scenes.length - 1];
  81193. }
  81194. else {
  81195. scene = BABYLON.Engine.LastCreatedScene;
  81196. }
  81197. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  81198. }
  81199. else {
  81200. this._imageProcessingConfiguration = configuration;
  81201. }
  81202. // Attaches observer.
  81203. if (this._imageProcessingConfiguration) {
  81204. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  81205. _this._updateParameters();
  81206. });
  81207. }
  81208. // Ensure the effect will be rebuilt.
  81209. if (!doNotBuild) {
  81210. this._updateParameters();
  81211. }
  81212. };
  81213. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  81214. /**
  81215. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  81216. */
  81217. get: function () {
  81218. return this.imageProcessingConfiguration.colorCurves;
  81219. },
  81220. /**
  81221. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  81222. */
  81223. set: function (value) {
  81224. this.imageProcessingConfiguration.colorCurves = value;
  81225. },
  81226. enumerable: true,
  81227. configurable: true
  81228. });
  81229. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  81230. /**
  81231. * Gets wether the color curves effect is enabled.
  81232. */
  81233. get: function () {
  81234. return this.imageProcessingConfiguration.colorCurvesEnabled;
  81235. },
  81236. /**
  81237. * Sets wether the color curves effect is enabled.
  81238. */
  81239. set: function (value) {
  81240. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  81241. },
  81242. enumerable: true,
  81243. configurable: true
  81244. });
  81245. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  81246. /**
  81247. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  81248. */
  81249. get: function () {
  81250. return this.imageProcessingConfiguration.colorGradingTexture;
  81251. },
  81252. /**
  81253. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  81254. */
  81255. set: function (value) {
  81256. this.imageProcessingConfiguration.colorGradingTexture = value;
  81257. },
  81258. enumerable: true,
  81259. configurable: true
  81260. });
  81261. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  81262. /**
  81263. * Gets wether the color grading effect is enabled.
  81264. */
  81265. get: function () {
  81266. return this.imageProcessingConfiguration.colorGradingEnabled;
  81267. },
  81268. /**
  81269. * Gets wether the color grading effect is enabled.
  81270. */
  81271. set: function (value) {
  81272. this.imageProcessingConfiguration.colorGradingEnabled = value;
  81273. },
  81274. enumerable: true,
  81275. configurable: true
  81276. });
  81277. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  81278. /**
  81279. * Gets exposure used in the effect.
  81280. */
  81281. get: function () {
  81282. return this.imageProcessingConfiguration.exposure;
  81283. },
  81284. /**
  81285. * Sets exposure used in the effect.
  81286. */
  81287. set: function (value) {
  81288. this.imageProcessingConfiguration.exposure = value;
  81289. },
  81290. enumerable: true,
  81291. configurable: true
  81292. });
  81293. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  81294. /**
  81295. * Gets wether tonemapping is enabled or not.
  81296. */
  81297. get: function () {
  81298. return this._imageProcessingConfiguration.toneMappingEnabled;
  81299. },
  81300. /**
  81301. * Sets wether tonemapping is enabled or not
  81302. */
  81303. set: function (value) {
  81304. this._imageProcessingConfiguration.toneMappingEnabled = value;
  81305. },
  81306. enumerable: true,
  81307. configurable: true
  81308. });
  81309. ;
  81310. ;
  81311. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  81312. /**
  81313. * Gets contrast used in the effect.
  81314. */
  81315. get: function () {
  81316. return this.imageProcessingConfiguration.contrast;
  81317. },
  81318. /**
  81319. * Sets contrast used in the effect.
  81320. */
  81321. set: function (value) {
  81322. this.imageProcessingConfiguration.contrast = value;
  81323. },
  81324. enumerable: true,
  81325. configurable: true
  81326. });
  81327. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  81328. /**
  81329. * Gets Vignette stretch size.
  81330. */
  81331. get: function () {
  81332. return this.imageProcessingConfiguration.vignetteStretch;
  81333. },
  81334. /**
  81335. * Sets Vignette stretch size.
  81336. */
  81337. set: function (value) {
  81338. this.imageProcessingConfiguration.vignetteStretch = value;
  81339. },
  81340. enumerable: true,
  81341. configurable: true
  81342. });
  81343. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  81344. /**
  81345. * Gets Vignette centre X Offset.
  81346. */
  81347. get: function () {
  81348. return this.imageProcessingConfiguration.vignetteCentreX;
  81349. },
  81350. /**
  81351. * Sets Vignette centre X Offset.
  81352. */
  81353. set: function (value) {
  81354. this.imageProcessingConfiguration.vignetteCentreX = value;
  81355. },
  81356. enumerable: true,
  81357. configurable: true
  81358. });
  81359. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  81360. /**
  81361. * Gets Vignette centre Y Offset.
  81362. */
  81363. get: function () {
  81364. return this.imageProcessingConfiguration.vignetteCentreY;
  81365. },
  81366. /**
  81367. * Sets Vignette centre Y Offset.
  81368. */
  81369. set: function (value) {
  81370. this.imageProcessingConfiguration.vignetteCentreY = value;
  81371. },
  81372. enumerable: true,
  81373. configurable: true
  81374. });
  81375. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  81376. /**
  81377. * Gets Vignette weight or intensity of the vignette effect.
  81378. */
  81379. get: function () {
  81380. return this.imageProcessingConfiguration.vignetteWeight;
  81381. },
  81382. /**
  81383. * Sets Vignette weight or intensity of the vignette effect.
  81384. */
  81385. set: function (value) {
  81386. this.imageProcessingConfiguration.vignetteWeight = value;
  81387. },
  81388. enumerable: true,
  81389. configurable: true
  81390. });
  81391. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  81392. /**
  81393. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81394. * if vignetteEnabled is set to true.
  81395. */
  81396. get: function () {
  81397. return this.imageProcessingConfiguration.vignetteColor;
  81398. },
  81399. /**
  81400. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81401. * if vignetteEnabled is set to true.
  81402. */
  81403. set: function (value) {
  81404. this.imageProcessingConfiguration.vignetteColor = value;
  81405. },
  81406. enumerable: true,
  81407. configurable: true
  81408. });
  81409. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  81410. /**
  81411. * Gets Camera field of view used by the Vignette effect.
  81412. */
  81413. get: function () {
  81414. return this.imageProcessingConfiguration.vignetteCameraFov;
  81415. },
  81416. /**
  81417. * Sets Camera field of view used by the Vignette effect.
  81418. */
  81419. set: function (value) {
  81420. this.imageProcessingConfiguration.vignetteCameraFov = value;
  81421. },
  81422. enumerable: true,
  81423. configurable: true
  81424. });
  81425. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  81426. /**
  81427. * Gets the vignette blend mode allowing different kind of effect.
  81428. */
  81429. get: function () {
  81430. return this.imageProcessingConfiguration.vignetteBlendMode;
  81431. },
  81432. /**
  81433. * Sets the vignette blend mode allowing different kind of effect.
  81434. */
  81435. set: function (value) {
  81436. this.imageProcessingConfiguration.vignetteBlendMode = value;
  81437. },
  81438. enumerable: true,
  81439. configurable: true
  81440. });
  81441. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  81442. /**
  81443. * Gets wether the vignette effect is enabled.
  81444. */
  81445. get: function () {
  81446. return this.imageProcessingConfiguration.vignetteEnabled;
  81447. },
  81448. /**
  81449. * Sets wether the vignette effect is enabled.
  81450. */
  81451. set: function (value) {
  81452. this.imageProcessingConfiguration.vignetteEnabled = value;
  81453. },
  81454. enumerable: true,
  81455. configurable: true
  81456. });
  81457. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  81458. /**
  81459. * Gets wether the input of the processing is in Gamma or Linear Space.
  81460. */
  81461. get: function () {
  81462. return this._fromLinearSpace;
  81463. },
  81464. /**
  81465. * Sets wether the input of the processing is in Gamma or Linear Space.
  81466. */
  81467. set: function (value) {
  81468. if (this._fromLinearSpace === value) {
  81469. return;
  81470. }
  81471. this._fromLinearSpace = value;
  81472. this._updateParameters();
  81473. },
  81474. enumerable: true,
  81475. configurable: true
  81476. });
  81477. ImageProcessingPostProcess.prototype.getClassName = function () {
  81478. return "ImageProcessingPostProcess";
  81479. };
  81480. ImageProcessingPostProcess.prototype._updateParameters = function () {
  81481. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  81482. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  81483. var defines = "";
  81484. for (var define in this._defines) {
  81485. if (this._defines[define]) {
  81486. defines += "#define " + define + ";\r\n";
  81487. }
  81488. }
  81489. var samplers = ["textureSampler"];
  81490. var uniforms = ["scale"];
  81491. if (BABYLON.ImageProcessingConfiguration) {
  81492. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  81493. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  81494. }
  81495. this.updateEffect(defines, uniforms, samplers);
  81496. };
  81497. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  81498. _super.prototype.dispose.call(this, camera);
  81499. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  81500. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  81501. }
  81502. if (this._imageProcessingConfiguration) {
  81503. this.imageProcessingConfiguration.applyByPostProcess = false;
  81504. }
  81505. };
  81506. __decorate([
  81507. BABYLON.serialize()
  81508. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  81509. return ImageProcessingPostProcess;
  81510. }(BABYLON.PostProcess));
  81511. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  81512. })(BABYLON || (BABYLON = {}));
  81513. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  81514. var BABYLON;
  81515. (function (BABYLON) {
  81516. /**
  81517. * Class used to store bone information
  81518. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81519. */
  81520. var Bone = /** @class */ (function (_super) {
  81521. __extends(Bone, _super);
  81522. /**
  81523. * Create a new bone
  81524. * @param name defines the bone name
  81525. * @param skeleton defines the parent skeleton
  81526. * @param parentBone defines the parent (can be null if the bone is the root)
  81527. * @param localMatrix defines the local matrix
  81528. * @param restPose defines the rest pose matrix
  81529. * @param baseMatrix defines the base matrix
  81530. * @param index defines index of the bone in the hiearchy
  81531. */
  81532. function Bone(
  81533. /**
  81534. * defines the bone name
  81535. */
  81536. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  81537. if (parentBone === void 0) { parentBone = null; }
  81538. if (localMatrix === void 0) { localMatrix = null; }
  81539. if (restPose === void 0) { restPose = null; }
  81540. if (baseMatrix === void 0) { baseMatrix = null; }
  81541. if (index === void 0) { index = null; }
  81542. var _this = _super.call(this, name, skeleton.getScene()) || this;
  81543. _this.name = name;
  81544. /**
  81545. * Gets the list of child bones
  81546. */
  81547. _this.children = new Array();
  81548. /** Gets the animations associated with this bone */
  81549. _this.animations = new Array();
  81550. /**
  81551. * @hidden Internal only
  81552. * Set this value to map this bone to a different index in the transform matrices
  81553. * Set this value to -1 to exclude the bone from the transform matrices
  81554. */
  81555. _this._index = null;
  81556. _this._absoluteTransform = new BABYLON.Matrix();
  81557. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  81558. _this._scalingDeterminant = 1;
  81559. _this._worldTransform = new BABYLON.Matrix();
  81560. _this._needToDecompose = true;
  81561. _this._needToCompose = false;
  81562. _this._skeleton = skeleton;
  81563. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  81564. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  81565. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  81566. _this._index = index;
  81567. skeleton.bones.push(_this);
  81568. _this.setParent(parentBone, false);
  81569. if (baseMatrix || localMatrix) {
  81570. _this._updateDifferenceMatrix();
  81571. }
  81572. return _this;
  81573. }
  81574. Object.defineProperty(Bone.prototype, "_matrix", {
  81575. /** @hidden */
  81576. get: function () {
  81577. this._compose();
  81578. return this._localMatrix;
  81579. },
  81580. /** @hidden */
  81581. set: function (value) {
  81582. this._localMatrix.copyFrom(value);
  81583. this._needToDecompose = true;
  81584. },
  81585. enumerable: true,
  81586. configurable: true
  81587. });
  81588. // Members
  81589. /**
  81590. * Gets the parent skeleton
  81591. * @returns a skeleton
  81592. */
  81593. Bone.prototype.getSkeleton = function () {
  81594. return this._skeleton;
  81595. };
  81596. /**
  81597. * Gets parent bone
  81598. * @returns a bone or null if the bone is the root of the bone hierarchy
  81599. */
  81600. Bone.prototype.getParent = function () {
  81601. return this._parent;
  81602. };
  81603. /**
  81604. * Sets the parent bone
  81605. * @param parent defines the parent (can be null if the bone is the root)
  81606. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  81607. */
  81608. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  81609. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  81610. if (this._parent === parent) {
  81611. return;
  81612. }
  81613. if (this._parent) {
  81614. var index = this._parent.children.indexOf(this);
  81615. if (index !== -1) {
  81616. this._parent.children.splice(index, 1);
  81617. }
  81618. }
  81619. this._parent = parent;
  81620. if (this._parent) {
  81621. this._parent.children.push(this);
  81622. }
  81623. if (updateDifferenceMatrix) {
  81624. this._updateDifferenceMatrix();
  81625. }
  81626. this.markAsDirty();
  81627. };
  81628. /**
  81629. * Gets the local matrix
  81630. * @returns a matrix
  81631. */
  81632. Bone.prototype.getLocalMatrix = function () {
  81633. this._compose();
  81634. return this._localMatrix;
  81635. };
  81636. /**
  81637. * Gets the base matrix (initial matrix which remains unchanged)
  81638. * @returns a matrix
  81639. */
  81640. Bone.prototype.getBaseMatrix = function () {
  81641. return this._baseMatrix;
  81642. };
  81643. /**
  81644. * Gets the rest pose matrix
  81645. * @returns a matrix
  81646. */
  81647. Bone.prototype.getRestPose = function () {
  81648. return this._restPose;
  81649. };
  81650. /**
  81651. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  81652. */
  81653. Bone.prototype.getWorldMatrix = function () {
  81654. return this._worldTransform;
  81655. };
  81656. /**
  81657. * Sets the local matrix to rest pose matrix
  81658. */
  81659. Bone.prototype.returnToRest = function () {
  81660. this.updateMatrix(this._restPose.clone());
  81661. };
  81662. /**
  81663. * Gets the inverse of the absolute transform matrix.
  81664. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  81665. * @returns a matrix
  81666. */
  81667. Bone.prototype.getInvertedAbsoluteTransform = function () {
  81668. return this._invertedAbsoluteTransform;
  81669. };
  81670. /**
  81671. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  81672. * @returns a matrix
  81673. */
  81674. Bone.prototype.getAbsoluteTransform = function () {
  81675. return this._absoluteTransform;
  81676. };
  81677. Object.defineProperty(Bone.prototype, "position", {
  81678. // Properties (matches AbstractMesh properties)
  81679. /** Gets or sets current position (in local space) */
  81680. get: function () {
  81681. this._decompose();
  81682. return this._localPosition;
  81683. },
  81684. set: function (newPosition) {
  81685. this._decompose();
  81686. this._localPosition.copyFrom(newPosition);
  81687. this._markAsDirtyAndCompose();
  81688. },
  81689. enumerable: true,
  81690. configurable: true
  81691. });
  81692. Object.defineProperty(Bone.prototype, "rotation", {
  81693. /** Gets or sets current rotation (in local space) */
  81694. get: function () {
  81695. return this.getRotation();
  81696. },
  81697. set: function (newRotation) {
  81698. this.setRotation(newRotation);
  81699. },
  81700. enumerable: true,
  81701. configurable: true
  81702. });
  81703. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  81704. /** Gets or sets current rotation quaternion (in local space) */
  81705. get: function () {
  81706. this._decompose();
  81707. return this._localRotation;
  81708. },
  81709. set: function (newRotation) {
  81710. this.setRotationQuaternion(newRotation);
  81711. },
  81712. enumerable: true,
  81713. configurable: true
  81714. });
  81715. Object.defineProperty(Bone.prototype, "scaling", {
  81716. /** Gets or sets current scaling (in local space) */
  81717. get: function () {
  81718. return this.getScale();
  81719. },
  81720. set: function (newScaling) {
  81721. this.setScale(newScaling);
  81722. },
  81723. enumerable: true,
  81724. configurable: true
  81725. });
  81726. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  81727. /**
  81728. * Gets the animation properties override
  81729. */
  81730. get: function () {
  81731. return this._skeleton.animationPropertiesOverride;
  81732. },
  81733. enumerable: true,
  81734. configurable: true
  81735. });
  81736. // Methods
  81737. Bone.prototype._decompose = function () {
  81738. if (!this._needToDecompose) {
  81739. return;
  81740. }
  81741. this._needToDecompose = false;
  81742. if (!this._localScaling) {
  81743. this._localScaling = BABYLON.Vector3.Zero();
  81744. this._localRotation = BABYLON.Quaternion.Zero();
  81745. this._localPosition = BABYLON.Vector3.Zero();
  81746. }
  81747. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  81748. };
  81749. Bone.prototype._compose = function () {
  81750. if (!this._needToCompose) {
  81751. return;
  81752. }
  81753. this._needToCompose = false;
  81754. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  81755. };
  81756. /**
  81757. * Update the base and local matrices
  81758. * @param matrix defines the new base or local matrix
  81759. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  81760. * @param updateLocalMatrix defines if the local matrix should be updated
  81761. */
  81762. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  81763. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  81764. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  81765. this._baseMatrix.copyFrom(matrix);
  81766. if (updateDifferenceMatrix) {
  81767. this._updateDifferenceMatrix();
  81768. }
  81769. if (updateLocalMatrix) {
  81770. this._localMatrix.copyFrom(matrix);
  81771. this._markAsDirtyAndDecompose();
  81772. }
  81773. else {
  81774. this.markAsDirty();
  81775. }
  81776. };
  81777. /** @hidden */
  81778. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  81779. if (updateChildren === void 0) { updateChildren = true; }
  81780. if (!rootMatrix) {
  81781. rootMatrix = this._baseMatrix;
  81782. }
  81783. if (this._parent) {
  81784. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81785. }
  81786. else {
  81787. this._absoluteTransform.copyFrom(rootMatrix);
  81788. }
  81789. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  81790. if (updateChildren) {
  81791. for (var index = 0; index < this.children.length; index++) {
  81792. this.children[index]._updateDifferenceMatrix();
  81793. }
  81794. }
  81795. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  81796. };
  81797. /**
  81798. * Flag the bone as dirty (Forcing it to update everything)
  81799. */
  81800. Bone.prototype.markAsDirty = function () {
  81801. this._currentRenderId++;
  81802. this._childRenderId++;
  81803. this._skeleton._markAsDirty();
  81804. };
  81805. Bone.prototype._markAsDirtyAndCompose = function () {
  81806. this.markAsDirty();
  81807. this._needToCompose = true;
  81808. };
  81809. Bone.prototype._markAsDirtyAndDecompose = function () {
  81810. this.markAsDirty();
  81811. this._needToDecompose = true;
  81812. };
  81813. /**
  81814. * Copy an animation range from another bone
  81815. * @param source defines the source bone
  81816. * @param rangeName defines the range name to copy
  81817. * @param frameOffset defines the frame offset
  81818. * @param rescaleAsRequired defines if rescaling must be applied if required
  81819. * @param skelDimensionsRatio defines the scaling ratio
  81820. * @returns true if operation was successful
  81821. */
  81822. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  81823. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81824. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  81825. // all animation may be coming from a library skeleton, so may need to create animation
  81826. if (this.animations.length === 0) {
  81827. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  81828. this.animations[0].setKeys([]);
  81829. }
  81830. // get animation info / verify there is such a range from the source bone
  81831. var sourceRange = source.animations[0].getRange(rangeName);
  81832. if (!sourceRange) {
  81833. return false;
  81834. }
  81835. var from = sourceRange.from;
  81836. var to = sourceRange.to;
  81837. var sourceKeys = source.animations[0].getKeys();
  81838. // rescaling prep
  81839. var sourceBoneLength = source.length;
  81840. var sourceParent = source.getParent();
  81841. var parent = this.getParent();
  81842. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  81843. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  81844. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  81845. var destKeys = this.animations[0].getKeys();
  81846. // loop vars declaration
  81847. var orig;
  81848. var origTranslation;
  81849. var mat;
  81850. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  81851. orig = sourceKeys[key];
  81852. if (orig.frame >= from && orig.frame <= to) {
  81853. if (rescaleAsRequired) {
  81854. mat = orig.value.clone();
  81855. // scale based on parent ratio, when bone has parent
  81856. if (parentScalingReqd) {
  81857. origTranslation = mat.getTranslation();
  81858. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  81859. // scale based on skeleton dimension ratio when root bone, and value is passed
  81860. }
  81861. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  81862. origTranslation = mat.getTranslation();
  81863. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  81864. // use original when root bone, and no data for skelDimensionsRatio
  81865. }
  81866. else {
  81867. mat = orig.value;
  81868. }
  81869. }
  81870. else {
  81871. mat = orig.value;
  81872. }
  81873. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  81874. }
  81875. }
  81876. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  81877. return true;
  81878. };
  81879. /**
  81880. * Translate the bone in local or world space
  81881. * @param vec The amount to translate the bone
  81882. * @param space The space that the translation is in
  81883. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81884. */
  81885. Bone.prototype.translate = function (vec, space, mesh) {
  81886. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81887. var lm = this.getLocalMatrix();
  81888. if (space == BABYLON.Space.LOCAL) {
  81889. lm.m[12] += vec.x;
  81890. lm.m[13] += vec.y;
  81891. lm.m[14] += vec.z;
  81892. }
  81893. else {
  81894. var wm = null;
  81895. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81896. if (mesh) {
  81897. wm = mesh.getWorldMatrix();
  81898. }
  81899. this._skeleton.computeAbsoluteTransforms();
  81900. var tmat = Bone._tmpMats[0];
  81901. var tvec = Bone._tmpVecs[0];
  81902. if (this._parent) {
  81903. if (mesh && wm) {
  81904. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81905. tmat.multiplyToRef(wm, tmat);
  81906. }
  81907. else {
  81908. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81909. }
  81910. }
  81911. tmat.m[12] = 0;
  81912. tmat.m[13] = 0;
  81913. tmat.m[14] = 0;
  81914. tmat.invert();
  81915. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  81916. lm.m[12] += tvec.x;
  81917. lm.m[13] += tvec.y;
  81918. lm.m[14] += tvec.z;
  81919. }
  81920. this._markAsDirtyAndDecompose();
  81921. };
  81922. /**
  81923. * Set the postion of the bone in local or world space
  81924. * @param position The position to set the bone
  81925. * @param space The space that the position is in
  81926. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81927. */
  81928. Bone.prototype.setPosition = function (position, space, mesh) {
  81929. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81930. var lm = this.getLocalMatrix();
  81931. if (space == BABYLON.Space.LOCAL) {
  81932. lm.m[12] = position.x;
  81933. lm.m[13] = position.y;
  81934. lm.m[14] = position.z;
  81935. }
  81936. else {
  81937. var wm = null;
  81938. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81939. if (mesh) {
  81940. wm = mesh.getWorldMatrix();
  81941. }
  81942. this._skeleton.computeAbsoluteTransforms();
  81943. var tmat = Bone._tmpMats[0];
  81944. var vec = Bone._tmpVecs[0];
  81945. if (this._parent) {
  81946. if (mesh && wm) {
  81947. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81948. tmat.multiplyToRef(wm, tmat);
  81949. }
  81950. else {
  81951. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81952. }
  81953. }
  81954. tmat.invert();
  81955. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  81956. lm.m[12] = vec.x;
  81957. lm.m[13] = vec.y;
  81958. lm.m[14] = vec.z;
  81959. }
  81960. this._markAsDirtyAndDecompose();
  81961. };
  81962. /**
  81963. * Set the absolute position of the bone (world space)
  81964. * @param position The position to set the bone
  81965. * @param mesh The mesh that this bone is attached to
  81966. */
  81967. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  81968. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  81969. };
  81970. /**
  81971. * Scale the bone on the x, y and z axes (in local space)
  81972. * @param x The amount to scale the bone on the x axis
  81973. * @param y The amount to scale the bone on the y axis
  81974. * @param z The amount to scale the bone on the z axis
  81975. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  81976. */
  81977. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  81978. if (scaleChildren === void 0) { scaleChildren = false; }
  81979. var locMat = this.getLocalMatrix();
  81980. // Apply new scaling on top of current local matrix
  81981. var scaleMat = Bone._tmpMats[0];
  81982. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  81983. scaleMat.multiplyToRef(locMat, locMat);
  81984. // Invert scaling matrix and apply the inverse to all children
  81985. scaleMat.invert();
  81986. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  81987. var child = _a[_i];
  81988. var cm = child.getLocalMatrix();
  81989. cm.multiplyToRef(scaleMat, cm);
  81990. cm.m[12] *= x;
  81991. cm.m[13] *= y;
  81992. cm.m[14] *= z;
  81993. child._markAsDirtyAndDecompose();
  81994. }
  81995. this._markAsDirtyAndDecompose();
  81996. if (scaleChildren) {
  81997. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  81998. var child = _c[_b];
  81999. child.scale(x, y, z, scaleChildren);
  82000. }
  82001. }
  82002. };
  82003. /**
  82004. * Set the bone scaling in local space
  82005. * @param scale defines the scaling vector
  82006. */
  82007. Bone.prototype.setScale = function (scale) {
  82008. this._decompose();
  82009. this._localScaling.copyFrom(scale);
  82010. this._markAsDirtyAndCompose();
  82011. };
  82012. /**
  82013. * Gets the current scaling in local space
  82014. * @returns the current scaling vector
  82015. */
  82016. Bone.prototype.getScale = function () {
  82017. this._decompose();
  82018. return this._localScaling;
  82019. };
  82020. /**
  82021. * Gets the current scaling in local space and stores it in a target vector
  82022. * @param result defines the target vector
  82023. */
  82024. Bone.prototype.getScaleToRef = function (result) {
  82025. this._decompose();
  82026. result.copyFrom(this._localScaling);
  82027. };
  82028. /**
  82029. * Set the yaw, pitch, and roll of the bone in local or world space
  82030. * @param yaw The rotation of the bone on the y axis
  82031. * @param pitch The rotation of the bone on the x axis
  82032. * @param roll The rotation of the bone on the z axis
  82033. * @param space The space that the axes of rotation are in
  82034. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82035. */
  82036. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  82037. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82038. if (space === BABYLON.Space.LOCAL) {
  82039. var quat = Bone._tmpQuat;
  82040. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  82041. this.setRotationQuaternion(quat, space, mesh);
  82042. return;
  82043. }
  82044. var rotMatInv = Bone._tmpMats[0];
  82045. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82046. return;
  82047. }
  82048. var rotMat = Bone._tmpMats[1];
  82049. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  82050. rotMatInv.multiplyToRef(rotMat, rotMat);
  82051. this._rotateWithMatrix(rotMat, space, mesh);
  82052. };
  82053. /**
  82054. * Add a rotation to the bone on an axis in local or world space
  82055. * @param axis The axis to rotate the bone on
  82056. * @param amount The amount to rotate the bone
  82057. * @param space The space that the axis is in
  82058. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82059. */
  82060. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  82061. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82062. var rmat = Bone._tmpMats[0];
  82063. rmat.m[12] = 0;
  82064. rmat.m[13] = 0;
  82065. rmat.m[14] = 0;
  82066. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  82067. this._rotateWithMatrix(rmat, space, mesh);
  82068. };
  82069. /**
  82070. * Set the rotation of the bone to a particular axis angle in local or world space
  82071. * @param axis The axis to rotate the bone on
  82072. * @param angle The angle that the bone should be rotated to
  82073. * @param space The space that the axis is in
  82074. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82075. */
  82076. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  82077. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82078. if (space === BABYLON.Space.LOCAL) {
  82079. var quat = Bone._tmpQuat;
  82080. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  82081. this.setRotationQuaternion(quat, space, mesh);
  82082. return;
  82083. }
  82084. var rotMatInv = Bone._tmpMats[0];
  82085. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82086. return;
  82087. }
  82088. var rotMat = Bone._tmpMats[1];
  82089. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  82090. rotMatInv.multiplyToRef(rotMat, rotMat);
  82091. this._rotateWithMatrix(rotMat, space, mesh);
  82092. };
  82093. /**
  82094. * Set the euler rotation of the bone in local of world space
  82095. * @param rotation The euler rotation that the bone should be set to
  82096. * @param space The space that the rotation is in
  82097. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82098. */
  82099. Bone.prototype.setRotation = function (rotation, space, mesh) {
  82100. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82101. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  82102. };
  82103. /**
  82104. * Set the quaternion rotation of the bone in local of world space
  82105. * @param quat The quaternion rotation that the bone should be set to
  82106. * @param space The space that the rotation is in
  82107. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82108. */
  82109. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  82110. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82111. if (space === BABYLON.Space.LOCAL) {
  82112. this._decompose();
  82113. this._localRotation.copyFrom(quat);
  82114. this._markAsDirtyAndCompose();
  82115. return;
  82116. }
  82117. var rotMatInv = Bone._tmpMats[0];
  82118. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82119. return;
  82120. }
  82121. var rotMat = Bone._tmpMats[1];
  82122. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  82123. rotMatInv.multiplyToRef(rotMat, rotMat);
  82124. this._rotateWithMatrix(rotMat, space, mesh);
  82125. };
  82126. /**
  82127. * Set the rotation matrix of the bone in local of world space
  82128. * @param rotMat The rotation matrix that the bone should be set to
  82129. * @param space The space that the rotation is in
  82130. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82131. */
  82132. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  82133. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82134. if (space === BABYLON.Space.LOCAL) {
  82135. var quat = Bone._tmpQuat;
  82136. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  82137. this.setRotationQuaternion(quat, space, mesh);
  82138. return;
  82139. }
  82140. var rotMatInv = Bone._tmpMats[0];
  82141. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82142. return;
  82143. }
  82144. var rotMat2 = Bone._tmpMats[1];
  82145. rotMat2.copyFrom(rotMat);
  82146. rotMatInv.multiplyToRef(rotMat, rotMat2);
  82147. this._rotateWithMatrix(rotMat2, space, mesh);
  82148. };
  82149. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  82150. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82151. var lmat = this.getLocalMatrix();
  82152. var lx = lmat.m[12];
  82153. var ly = lmat.m[13];
  82154. var lz = lmat.m[14];
  82155. var parent = this.getParent();
  82156. var parentScale = Bone._tmpMats[3];
  82157. var parentScaleInv = Bone._tmpMats[4];
  82158. if (parent && space == BABYLON.Space.WORLD) {
  82159. if (mesh) {
  82160. parentScale.copyFrom(mesh.getWorldMatrix());
  82161. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  82162. }
  82163. else {
  82164. parentScale.copyFrom(parent.getAbsoluteTransform());
  82165. }
  82166. parentScaleInv.copyFrom(parentScale);
  82167. parentScaleInv.invert();
  82168. lmat.multiplyToRef(parentScale, lmat);
  82169. lmat.multiplyToRef(rmat, lmat);
  82170. lmat.multiplyToRef(parentScaleInv, lmat);
  82171. }
  82172. else {
  82173. if (space == BABYLON.Space.WORLD && mesh) {
  82174. parentScale.copyFrom(mesh.getWorldMatrix());
  82175. parentScaleInv.copyFrom(parentScale);
  82176. parentScaleInv.invert();
  82177. lmat.multiplyToRef(parentScale, lmat);
  82178. lmat.multiplyToRef(rmat, lmat);
  82179. lmat.multiplyToRef(parentScaleInv, lmat);
  82180. }
  82181. else {
  82182. lmat.multiplyToRef(rmat, lmat);
  82183. }
  82184. }
  82185. lmat.m[12] = lx;
  82186. lmat.m[13] = ly;
  82187. lmat.m[14] = lz;
  82188. this.computeAbsoluteTransforms();
  82189. this._markAsDirtyAndDecompose();
  82190. };
  82191. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  82192. var scaleMatrix = Bone._tmpMats[2];
  82193. rotMatInv.copyFrom(this.getAbsoluteTransform());
  82194. if (mesh) {
  82195. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  82196. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  82197. }
  82198. rotMatInv.invert();
  82199. if (isNaN(rotMatInv.m[0])) {
  82200. // Matrix failed to invert.
  82201. // This can happen if scale is zero for example.
  82202. return false;
  82203. }
  82204. scaleMatrix.m[0] *= this._scalingDeterminant;
  82205. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  82206. return true;
  82207. };
  82208. /**
  82209. * Get the position of the bone in local or world space
  82210. * @param space The space that the returned position is in
  82211. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82212. * @returns The position of the bone
  82213. */
  82214. Bone.prototype.getPosition = function (space, mesh) {
  82215. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82216. if (mesh === void 0) { mesh = null; }
  82217. var pos = BABYLON.Vector3.Zero();
  82218. this.getPositionToRef(space, mesh, pos);
  82219. return pos;
  82220. };
  82221. /**
  82222. * Copy the position of the bone to a vector3 in local or world space
  82223. * @param space The space that the returned position is in
  82224. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82225. * @param result The vector3 to copy the position to
  82226. */
  82227. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  82228. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82229. if (space == BABYLON.Space.LOCAL) {
  82230. var lm = this.getLocalMatrix();
  82231. result.x = lm.m[12];
  82232. result.y = lm.m[13];
  82233. result.z = lm.m[14];
  82234. }
  82235. else {
  82236. var wm = null;
  82237. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82238. if (mesh) {
  82239. wm = mesh.getWorldMatrix();
  82240. }
  82241. this._skeleton.computeAbsoluteTransforms();
  82242. var tmat = Bone._tmpMats[0];
  82243. if (mesh && wm) {
  82244. tmat.copyFrom(this.getAbsoluteTransform());
  82245. tmat.multiplyToRef(wm, tmat);
  82246. }
  82247. else {
  82248. tmat = this.getAbsoluteTransform();
  82249. }
  82250. result.x = tmat.m[12];
  82251. result.y = tmat.m[13];
  82252. result.z = tmat.m[14];
  82253. }
  82254. };
  82255. /**
  82256. * Get the absolute position of the bone (world space)
  82257. * @param mesh The mesh that this bone is attached to
  82258. * @returns The absolute position of the bone
  82259. */
  82260. Bone.prototype.getAbsolutePosition = function (mesh) {
  82261. if (mesh === void 0) { mesh = null; }
  82262. var pos = BABYLON.Vector3.Zero();
  82263. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  82264. return pos;
  82265. };
  82266. /**
  82267. * Copy the absolute position of the bone (world space) to the result param
  82268. * @param mesh The mesh that this bone is attached to
  82269. * @param result The vector3 to copy the absolute position to
  82270. */
  82271. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  82272. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  82273. };
  82274. /**
  82275. * Compute the absolute transforms of this bone and its children
  82276. */
  82277. Bone.prototype.computeAbsoluteTransforms = function () {
  82278. this._compose();
  82279. if (this._parent) {
  82280. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  82281. }
  82282. else {
  82283. this._absoluteTransform.copyFrom(this._localMatrix);
  82284. var poseMatrix = this._skeleton.getPoseMatrix();
  82285. if (poseMatrix) {
  82286. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  82287. }
  82288. }
  82289. var children = this.children;
  82290. var len = children.length;
  82291. for (var i = 0; i < len; i++) {
  82292. children[i].computeAbsoluteTransforms();
  82293. }
  82294. };
  82295. /**
  82296. * Get the world direction from an axis that is in the local space of the bone
  82297. * @param localAxis The local direction that is used to compute the world direction
  82298. * @param mesh The mesh that this bone is attached to
  82299. * @returns The world direction
  82300. */
  82301. Bone.prototype.getDirection = function (localAxis, mesh) {
  82302. if (mesh === void 0) { mesh = null; }
  82303. var result = BABYLON.Vector3.Zero();
  82304. this.getDirectionToRef(localAxis, mesh, result);
  82305. return result;
  82306. };
  82307. /**
  82308. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  82309. * @param localAxis The local direction that is used to compute the world direction
  82310. * @param mesh The mesh that this bone is attached to
  82311. * @param result The vector3 that the world direction will be copied to
  82312. */
  82313. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  82314. if (mesh === void 0) { mesh = null; }
  82315. var wm = null;
  82316. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82317. if (mesh) {
  82318. wm = mesh.getWorldMatrix();
  82319. }
  82320. this._skeleton.computeAbsoluteTransforms();
  82321. var mat = Bone._tmpMats[0];
  82322. mat.copyFrom(this.getAbsoluteTransform());
  82323. if (mesh && wm) {
  82324. mat.multiplyToRef(wm, mat);
  82325. }
  82326. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  82327. result.normalize();
  82328. };
  82329. /**
  82330. * Get the euler rotation of the bone in local or world space
  82331. * @param space The space that the rotation should be in
  82332. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82333. * @returns The euler rotation
  82334. */
  82335. Bone.prototype.getRotation = function (space, mesh) {
  82336. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82337. if (mesh === void 0) { mesh = null; }
  82338. var result = BABYLON.Vector3.Zero();
  82339. this.getRotationToRef(space, mesh, result);
  82340. return result;
  82341. };
  82342. /**
  82343. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  82344. * @param space The space that the rotation should be in
  82345. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82346. * @param result The vector3 that the rotation should be copied to
  82347. */
  82348. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  82349. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82350. if (mesh === void 0) { mesh = null; }
  82351. var quat = Bone._tmpQuat;
  82352. this.getRotationQuaternionToRef(space, mesh, quat);
  82353. quat.toEulerAnglesToRef(result);
  82354. };
  82355. /**
  82356. * Get the quaternion rotation of the bone in either local or world space
  82357. * @param space The space that the rotation should be in
  82358. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82359. * @returns The quaternion rotation
  82360. */
  82361. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  82362. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82363. if (mesh === void 0) { mesh = null; }
  82364. var result = BABYLON.Quaternion.Identity();
  82365. this.getRotationQuaternionToRef(space, mesh, result);
  82366. return result;
  82367. };
  82368. /**
  82369. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  82370. * @param space The space that the rotation should be in
  82371. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82372. * @param result The quaternion that the rotation should be copied to
  82373. */
  82374. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  82375. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82376. if (mesh === void 0) { mesh = null; }
  82377. if (space == BABYLON.Space.LOCAL) {
  82378. this._decompose();
  82379. result.copyFrom(this._localRotation);
  82380. }
  82381. else {
  82382. var mat = Bone._tmpMats[0];
  82383. var amat = this.getAbsoluteTransform();
  82384. if (mesh) {
  82385. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  82386. }
  82387. else {
  82388. mat.copyFrom(amat);
  82389. }
  82390. mat.m[0] *= this._scalingDeterminant;
  82391. mat.m[1] *= this._scalingDeterminant;
  82392. mat.m[2] *= this._scalingDeterminant;
  82393. mat.decompose(undefined, result, undefined);
  82394. }
  82395. };
  82396. /**
  82397. * Get the rotation matrix of the bone in local or world space
  82398. * @param space The space that the rotation should be in
  82399. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82400. * @returns The rotation matrix
  82401. */
  82402. Bone.prototype.getRotationMatrix = function (space, mesh) {
  82403. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82404. var result = BABYLON.Matrix.Identity();
  82405. this.getRotationMatrixToRef(space, mesh, result);
  82406. return result;
  82407. };
  82408. /**
  82409. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  82410. * @param space The space that the rotation should be in
  82411. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82412. * @param result The quaternion that the rotation should be copied to
  82413. */
  82414. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  82415. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82416. if (space == BABYLON.Space.LOCAL) {
  82417. this.getLocalMatrix().getRotationMatrixToRef(result);
  82418. }
  82419. else {
  82420. var mat = Bone._tmpMats[0];
  82421. var amat = this.getAbsoluteTransform();
  82422. if (mesh) {
  82423. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  82424. }
  82425. else {
  82426. mat.copyFrom(amat);
  82427. }
  82428. mat.m[0] *= this._scalingDeterminant;
  82429. mat.m[1] *= this._scalingDeterminant;
  82430. mat.m[2] *= this._scalingDeterminant;
  82431. mat.getRotationMatrixToRef(result);
  82432. }
  82433. };
  82434. /**
  82435. * Get the world position of a point that is in the local space of the bone
  82436. * @param position The local position
  82437. * @param mesh The mesh that this bone is attached to
  82438. * @returns The world position
  82439. */
  82440. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  82441. if (mesh === void 0) { mesh = null; }
  82442. var result = BABYLON.Vector3.Zero();
  82443. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  82444. return result;
  82445. };
  82446. /**
  82447. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  82448. * @param position The local position
  82449. * @param mesh The mesh that this bone is attached to
  82450. * @param result The vector3 that the world position should be copied to
  82451. */
  82452. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  82453. if (mesh === void 0) { mesh = null; }
  82454. var wm = null;
  82455. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82456. if (mesh) {
  82457. wm = mesh.getWorldMatrix();
  82458. }
  82459. this._skeleton.computeAbsoluteTransforms();
  82460. var tmat = Bone._tmpMats[0];
  82461. if (mesh && wm) {
  82462. tmat.copyFrom(this.getAbsoluteTransform());
  82463. tmat.multiplyToRef(wm, tmat);
  82464. }
  82465. else {
  82466. tmat = this.getAbsoluteTransform();
  82467. }
  82468. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  82469. };
  82470. /**
  82471. * Get the local position of a point that is in world space
  82472. * @param position The world position
  82473. * @param mesh The mesh that this bone is attached to
  82474. * @returns The local position
  82475. */
  82476. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  82477. if (mesh === void 0) { mesh = null; }
  82478. var result = BABYLON.Vector3.Zero();
  82479. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  82480. return result;
  82481. };
  82482. /**
  82483. * Get the local position of a point that is in world space and copy it to the result param
  82484. * @param position The world position
  82485. * @param mesh The mesh that this bone is attached to
  82486. * @param result The vector3 that the local position should be copied to
  82487. */
  82488. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  82489. if (mesh === void 0) { mesh = null; }
  82490. var wm = null;
  82491. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82492. if (mesh) {
  82493. wm = mesh.getWorldMatrix();
  82494. }
  82495. this._skeleton.computeAbsoluteTransforms();
  82496. var tmat = Bone._tmpMats[0];
  82497. tmat.copyFrom(this.getAbsoluteTransform());
  82498. if (mesh && wm) {
  82499. tmat.multiplyToRef(wm, tmat);
  82500. }
  82501. tmat.invert();
  82502. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  82503. };
  82504. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82505. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  82506. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82507. return Bone;
  82508. }(BABYLON.Node));
  82509. BABYLON.Bone = Bone;
  82510. })(BABYLON || (BABYLON = {}));
  82511. //# sourceMappingURL=babylon.bone.js.map
  82512. var BABYLON;
  82513. (function (BABYLON) {
  82514. /**
  82515. * Class used to apply inverse kinematics to bones
  82516. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  82517. */
  82518. var BoneIKController = /** @class */ (function () {
  82519. /**
  82520. * Creates a new BoneIKController
  82521. * @param mesh defines the mesh to control
  82522. * @param bone defines the bone to control
  82523. * @param options defines options to set up the controller
  82524. */
  82525. function BoneIKController(mesh, bone, options) {
  82526. /**
  82527. * Gets or sets the target position
  82528. */
  82529. this.targetPosition = BABYLON.Vector3.Zero();
  82530. /**
  82531. * Gets or sets the pole target position
  82532. */
  82533. this.poleTargetPosition = BABYLON.Vector3.Zero();
  82534. /**
  82535. * Gets or sets the pole target local offset
  82536. */
  82537. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  82538. /**
  82539. * Gets or sets the pole angle
  82540. */
  82541. this.poleAngle = 0;
  82542. /**
  82543. * 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)
  82544. */
  82545. this.slerpAmount = 1;
  82546. this._bone1Quat = BABYLON.Quaternion.Identity();
  82547. this._bone1Mat = BABYLON.Matrix.Identity();
  82548. this._bone2Ang = Math.PI;
  82549. this._maxAngle = Math.PI;
  82550. this._rightHandedSystem = false;
  82551. this._bendAxis = BABYLON.Vector3.Right();
  82552. this._slerping = false;
  82553. this._adjustRoll = 0;
  82554. this._bone2 = bone;
  82555. this._bone1 = bone.getParent();
  82556. if (!this._bone1) {
  82557. return;
  82558. }
  82559. this.mesh = mesh;
  82560. var bonePos = bone.getPosition();
  82561. if (bone.getAbsoluteTransform().determinant() > 0) {
  82562. this._rightHandedSystem = true;
  82563. this._bendAxis.x = 0;
  82564. this._bendAxis.y = 0;
  82565. this._bendAxis.z = -1;
  82566. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  82567. this._adjustRoll = Math.PI * .5;
  82568. this._bendAxis.z = 1;
  82569. }
  82570. }
  82571. if (this._bone1.length) {
  82572. var boneScale1 = this._bone1.getScale();
  82573. var boneScale2 = this._bone2.getScale();
  82574. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  82575. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  82576. }
  82577. else if (this._bone1.children[0]) {
  82578. mesh.computeWorldMatrix(true);
  82579. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  82580. var pos2 = this._bone2.getAbsolutePosition(mesh);
  82581. var pos3 = this._bone1.getAbsolutePosition(mesh);
  82582. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  82583. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  82584. }
  82585. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  82586. this.maxAngle = Math.PI;
  82587. if (options) {
  82588. if (options.targetMesh) {
  82589. this.targetMesh = options.targetMesh;
  82590. this.targetMesh.computeWorldMatrix(true);
  82591. }
  82592. if (options.poleTargetMesh) {
  82593. this.poleTargetMesh = options.poleTargetMesh;
  82594. this.poleTargetMesh.computeWorldMatrix(true);
  82595. }
  82596. else if (options.poleTargetBone) {
  82597. this.poleTargetBone = options.poleTargetBone;
  82598. }
  82599. else if (this._bone1.getParent()) {
  82600. this.poleTargetBone = this._bone1.getParent();
  82601. }
  82602. if (options.poleTargetLocalOffset) {
  82603. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  82604. }
  82605. if (options.poleAngle) {
  82606. this.poleAngle = options.poleAngle;
  82607. }
  82608. if (options.bendAxis) {
  82609. this._bendAxis.copyFrom(options.bendAxis);
  82610. }
  82611. if (options.maxAngle) {
  82612. this.maxAngle = options.maxAngle;
  82613. }
  82614. if (options.slerpAmount) {
  82615. this.slerpAmount = options.slerpAmount;
  82616. }
  82617. }
  82618. }
  82619. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  82620. /**
  82621. * Gets or sets maximum allowed angle
  82622. */
  82623. get: function () {
  82624. return this._maxAngle;
  82625. },
  82626. set: function (value) {
  82627. this._setMaxAngle(value);
  82628. },
  82629. enumerable: true,
  82630. configurable: true
  82631. });
  82632. BoneIKController.prototype._setMaxAngle = function (ang) {
  82633. if (ang < 0) {
  82634. ang = 0;
  82635. }
  82636. if (ang > Math.PI || ang == undefined) {
  82637. ang = Math.PI;
  82638. }
  82639. this._maxAngle = ang;
  82640. var a = this._bone1Length;
  82641. var b = this._bone2Length;
  82642. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  82643. };
  82644. /**
  82645. * Force the controller to update the bones
  82646. */
  82647. BoneIKController.prototype.update = function () {
  82648. var bone1 = this._bone1;
  82649. if (!bone1) {
  82650. return;
  82651. }
  82652. var target = this.targetPosition;
  82653. var poleTarget = this.poleTargetPosition;
  82654. var mat1 = BoneIKController._tmpMats[0];
  82655. var mat2 = BoneIKController._tmpMats[1];
  82656. if (this.targetMesh) {
  82657. target.copyFrom(this.targetMesh.getAbsolutePosition());
  82658. }
  82659. if (this.poleTargetBone) {
  82660. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  82661. }
  82662. else if (this.poleTargetMesh) {
  82663. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  82664. }
  82665. var bonePos = BoneIKController._tmpVecs[0];
  82666. var zaxis = BoneIKController._tmpVecs[1];
  82667. var xaxis = BoneIKController._tmpVecs[2];
  82668. var yaxis = BoneIKController._tmpVecs[3];
  82669. var upAxis = BoneIKController._tmpVecs[4];
  82670. var _tmpQuat = BoneIKController._tmpQuat;
  82671. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  82672. poleTarget.subtractToRef(bonePos, upAxis);
  82673. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  82674. upAxis.y = 1;
  82675. }
  82676. else {
  82677. upAxis.normalize();
  82678. }
  82679. target.subtractToRef(bonePos, yaxis);
  82680. yaxis.normalize();
  82681. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  82682. zaxis.normalize();
  82683. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  82684. xaxis.normalize();
  82685. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  82686. var a = this._bone1Length;
  82687. var b = this._bone2Length;
  82688. var c = BABYLON.Vector3.Distance(bonePos, target);
  82689. if (this._maxReach > 0) {
  82690. c = Math.min(this._maxReach, c);
  82691. }
  82692. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  82693. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  82694. if (acosa > 1) {
  82695. acosa = 1;
  82696. }
  82697. if (acosb > 1) {
  82698. acosb = 1;
  82699. }
  82700. if (acosa < -1) {
  82701. acosa = -1;
  82702. }
  82703. if (acosb < -1) {
  82704. acosb = -1;
  82705. }
  82706. var angA = Math.acos(acosa);
  82707. var angB = Math.acos(acosb);
  82708. var angC = -angA - angB;
  82709. if (this._rightHandedSystem) {
  82710. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  82711. mat2.multiplyToRef(mat1, mat1);
  82712. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  82713. mat2.multiplyToRef(mat1, mat1);
  82714. }
  82715. else {
  82716. var _tmpVec = BoneIKController._tmpVecs[5];
  82717. _tmpVec.copyFrom(this._bendAxis);
  82718. _tmpVec.x *= -1;
  82719. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  82720. mat2.multiplyToRef(mat1, mat1);
  82721. }
  82722. if (this.poleAngle) {
  82723. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  82724. mat1.multiplyToRef(mat2, mat1);
  82725. }
  82726. if (this._bone1) {
  82727. if (this.slerpAmount < 1) {
  82728. if (!this._slerping) {
  82729. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  82730. }
  82731. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  82732. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  82733. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  82734. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  82735. this._slerping = true;
  82736. }
  82737. else {
  82738. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  82739. this._bone1Mat.copyFrom(mat1);
  82740. this._slerping = false;
  82741. }
  82742. }
  82743. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  82744. this._bone2Ang = angC;
  82745. };
  82746. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82747. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  82748. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82749. return BoneIKController;
  82750. }());
  82751. BABYLON.BoneIKController = BoneIKController;
  82752. })(BABYLON || (BABYLON = {}));
  82753. //# sourceMappingURL=babylon.boneIKController.js.map
  82754. var BABYLON;
  82755. (function (BABYLON) {
  82756. /**
  82757. * Class used to make a bone look toward a point in space
  82758. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  82759. */
  82760. var BoneLookController = /** @class */ (function () {
  82761. /**
  82762. * Create a BoneLookController
  82763. * @param mesh the mesh that the bone belongs to
  82764. * @param bone the bone that will be looking to the target
  82765. * @param target the target Vector3 to look at
  82766. * @param settings optional settings:
  82767. * * maxYaw: the maximum angle the bone will yaw to
  82768. * * minYaw: the minimum angle the bone will yaw to
  82769. * * maxPitch: the maximum angle the bone will pitch to
  82770. * * minPitch: the minimum angle the bone will yaw to
  82771. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  82772. * * upAxis: the up axis of the coordinate system
  82773. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  82774. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  82775. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  82776. * * adjustYaw: used to make an adjustment to the yaw of the bone
  82777. * * adjustPitch: used to make an adjustment to the pitch of the bone
  82778. * * adjustRoll: used to make an adjustment to the roll of the bone
  82779. **/
  82780. function BoneLookController(mesh, bone, target, options) {
  82781. /**
  82782. * The up axis of the coordinate system that is used when the bone is rotated
  82783. */
  82784. this.upAxis = BABYLON.Vector3.Up();
  82785. /**
  82786. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  82787. */
  82788. this.upAxisSpace = BABYLON.Space.LOCAL;
  82789. /**
  82790. * Used to make an adjustment to the yaw of the bone
  82791. */
  82792. this.adjustYaw = 0;
  82793. /**
  82794. * Used to make an adjustment to the pitch of the bone
  82795. */
  82796. this.adjustPitch = 0;
  82797. /**
  82798. * Used to make an adjustment to the roll of the bone
  82799. */
  82800. this.adjustRoll = 0;
  82801. /**
  82802. * 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)
  82803. */
  82804. this.slerpAmount = 1;
  82805. this._boneQuat = BABYLON.Quaternion.Identity();
  82806. this._slerping = false;
  82807. this._firstFrameSkipped = false;
  82808. this._fowardAxis = BABYLON.Vector3.Forward();
  82809. this.mesh = mesh;
  82810. this.bone = bone;
  82811. this.target = target;
  82812. if (options) {
  82813. if (options.adjustYaw) {
  82814. this.adjustYaw = options.adjustYaw;
  82815. }
  82816. if (options.adjustPitch) {
  82817. this.adjustPitch = options.adjustPitch;
  82818. }
  82819. if (options.adjustRoll) {
  82820. this.adjustRoll = options.adjustRoll;
  82821. }
  82822. if (options.maxYaw != null) {
  82823. this.maxYaw = options.maxYaw;
  82824. }
  82825. else {
  82826. this.maxYaw = Math.PI;
  82827. }
  82828. if (options.minYaw != null) {
  82829. this.minYaw = options.minYaw;
  82830. }
  82831. else {
  82832. this.minYaw = -Math.PI;
  82833. }
  82834. if (options.maxPitch != null) {
  82835. this.maxPitch = options.maxPitch;
  82836. }
  82837. else {
  82838. this.maxPitch = Math.PI;
  82839. }
  82840. if (options.minPitch != null) {
  82841. this.minPitch = options.minPitch;
  82842. }
  82843. else {
  82844. this.minPitch = -Math.PI;
  82845. }
  82846. if (options.slerpAmount != null) {
  82847. this.slerpAmount = options.slerpAmount;
  82848. }
  82849. if (options.upAxis != null) {
  82850. this.upAxis = options.upAxis;
  82851. }
  82852. if (options.upAxisSpace != null) {
  82853. this.upAxisSpace = options.upAxisSpace;
  82854. }
  82855. if (options.yawAxis != null || options.pitchAxis != null) {
  82856. var newYawAxis = BABYLON.Axis.Y;
  82857. var newPitchAxis = BABYLON.Axis.X;
  82858. if (options.yawAxis != null) {
  82859. newYawAxis = options.yawAxis.clone();
  82860. newYawAxis.normalize();
  82861. }
  82862. if (options.pitchAxis != null) {
  82863. newPitchAxis = options.pitchAxis.clone();
  82864. newPitchAxis.normalize();
  82865. }
  82866. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  82867. this._transformYawPitch = BABYLON.Matrix.Identity();
  82868. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  82869. this._transformYawPitchInv = this._transformYawPitch.clone();
  82870. this._transformYawPitch.invert();
  82871. }
  82872. }
  82873. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  82874. this.upAxisSpace = BABYLON.Space.LOCAL;
  82875. }
  82876. }
  82877. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  82878. /**
  82879. * Gets or sets the minimum yaw angle that the bone can look to
  82880. */
  82881. get: function () {
  82882. return this._minYaw;
  82883. },
  82884. set: function (value) {
  82885. this._minYaw = value;
  82886. this._minYawSin = Math.sin(value);
  82887. this._minYawCos = Math.cos(value);
  82888. if (this._maxYaw != null) {
  82889. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82890. this._yawRange = this._maxYaw - this._minYaw;
  82891. }
  82892. },
  82893. enumerable: true,
  82894. configurable: true
  82895. });
  82896. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  82897. /**
  82898. * Gets or sets the maximum yaw angle that the bone can look to
  82899. */
  82900. get: function () {
  82901. return this._maxYaw;
  82902. },
  82903. set: function (value) {
  82904. this._maxYaw = value;
  82905. this._maxYawSin = Math.sin(value);
  82906. this._maxYawCos = Math.cos(value);
  82907. if (this._minYaw != null) {
  82908. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82909. this._yawRange = this._maxYaw - this._minYaw;
  82910. }
  82911. },
  82912. enumerable: true,
  82913. configurable: true
  82914. });
  82915. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  82916. /**
  82917. * Gets or sets the minimum pitch angle that the bone can look to
  82918. */
  82919. get: function () {
  82920. return this._minPitch;
  82921. },
  82922. set: function (value) {
  82923. this._minPitch = value;
  82924. this._minPitchTan = Math.tan(value);
  82925. },
  82926. enumerable: true,
  82927. configurable: true
  82928. });
  82929. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  82930. /**
  82931. * Gets or sets the maximum pitch angle that the bone can look to
  82932. */
  82933. get: function () {
  82934. return this._maxPitch;
  82935. },
  82936. set: function (value) {
  82937. this._maxPitch = value;
  82938. this._maxPitchTan = Math.tan(value);
  82939. },
  82940. enumerable: true,
  82941. configurable: true
  82942. });
  82943. /**
  82944. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  82945. */
  82946. BoneLookController.prototype.update = function () {
  82947. //skip the first frame when slerping so that the mesh rotation is correct
  82948. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  82949. this._firstFrameSkipped = true;
  82950. return;
  82951. }
  82952. var bone = this.bone;
  82953. var bonePos = BoneLookController._tmpVecs[0];
  82954. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  82955. var target = this.target;
  82956. var _tmpMat1 = BoneLookController._tmpMats[0];
  82957. var _tmpMat2 = BoneLookController._tmpMats[1];
  82958. var mesh = this.mesh;
  82959. var parentBone = bone.getParent();
  82960. var upAxis = BoneLookController._tmpVecs[1];
  82961. upAxis.copyFrom(this.upAxis);
  82962. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  82963. if (this._transformYawPitch) {
  82964. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  82965. }
  82966. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  82967. }
  82968. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  82969. mesh.getDirectionToRef(upAxis, upAxis);
  82970. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  82971. upAxis.normalize();
  82972. }
  82973. }
  82974. var checkYaw = false;
  82975. var checkPitch = false;
  82976. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  82977. checkYaw = true;
  82978. }
  82979. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  82980. checkPitch = true;
  82981. }
  82982. if (checkYaw || checkPitch) {
  82983. var spaceMat = BoneLookController._tmpMats[2];
  82984. var spaceMatInv = BoneLookController._tmpMats[3];
  82985. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  82986. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  82987. }
  82988. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  82989. spaceMat.copyFrom(mesh.getWorldMatrix());
  82990. }
  82991. else {
  82992. var forwardAxis = BoneLookController._tmpVecs[2];
  82993. forwardAxis.copyFrom(this._fowardAxis);
  82994. if (this._transformYawPitch) {
  82995. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  82996. }
  82997. if (parentBone) {
  82998. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  82999. }
  83000. else {
  83001. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  83002. }
  83003. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  83004. rightAxis.normalize();
  83005. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  83006. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  83007. }
  83008. spaceMat.invertToRef(spaceMatInv);
  83009. var xzlen = null;
  83010. if (checkPitch) {
  83011. var localTarget = BoneLookController._tmpVecs[3];
  83012. target.subtractToRef(bonePos, localTarget);
  83013. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  83014. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  83015. var pitch = Math.atan2(localTarget.y, xzlen);
  83016. var newPitch = pitch;
  83017. if (pitch > this._maxPitch) {
  83018. localTarget.y = this._maxPitchTan * xzlen;
  83019. newPitch = this._maxPitch;
  83020. }
  83021. else if (pitch < this._minPitch) {
  83022. localTarget.y = this._minPitchTan * xzlen;
  83023. newPitch = this._minPitch;
  83024. }
  83025. if (pitch != newPitch) {
  83026. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  83027. localTarget.addInPlace(bonePos);
  83028. target = localTarget;
  83029. }
  83030. }
  83031. if (checkYaw) {
  83032. var localTarget = BoneLookController._tmpVecs[4];
  83033. target.subtractToRef(bonePos, localTarget);
  83034. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  83035. var yaw = Math.atan2(localTarget.x, localTarget.z);
  83036. var newYaw = yaw;
  83037. if (yaw > this._maxYaw || yaw < this._minYaw) {
  83038. if (xzlen == null) {
  83039. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  83040. }
  83041. if (this._yawRange > Math.PI) {
  83042. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  83043. localTarget.z = this._maxYawCos * xzlen;
  83044. localTarget.x = this._maxYawSin * xzlen;
  83045. newYaw = this._maxYaw;
  83046. }
  83047. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  83048. localTarget.z = this._minYawCos * xzlen;
  83049. localTarget.x = this._minYawSin * xzlen;
  83050. newYaw = this._minYaw;
  83051. }
  83052. }
  83053. else {
  83054. if (yaw > this._maxYaw) {
  83055. localTarget.z = this._maxYawCos * xzlen;
  83056. localTarget.x = this._maxYawSin * xzlen;
  83057. newYaw = this._maxYaw;
  83058. }
  83059. else if (yaw < this._minYaw) {
  83060. localTarget.z = this._minYawCos * xzlen;
  83061. localTarget.x = this._minYawSin * xzlen;
  83062. newYaw = this._minYaw;
  83063. }
  83064. }
  83065. }
  83066. if (this._slerping && this._yawRange > Math.PI) {
  83067. //are we going to be crossing into the min/max region?
  83068. var boneFwd = BoneLookController._tmpVecs[8];
  83069. boneFwd.copyFrom(BABYLON.Axis.Z);
  83070. if (this._transformYawPitch) {
  83071. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  83072. }
  83073. var boneRotMat = BoneLookController._tmpMats[4];
  83074. this._boneQuat.toRotationMatrix(boneRotMat);
  83075. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  83076. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  83077. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  83078. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  83079. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  83080. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  83081. if (angBtwTar > angBtwMidYaw) {
  83082. if (xzlen == null) {
  83083. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  83084. }
  83085. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  83086. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  83087. if (angBtwMin < angBtwMax) {
  83088. newYaw = boneYaw + Math.PI * .75;
  83089. localTarget.z = Math.cos(newYaw) * xzlen;
  83090. localTarget.x = Math.sin(newYaw) * xzlen;
  83091. }
  83092. else {
  83093. newYaw = boneYaw - Math.PI * .75;
  83094. localTarget.z = Math.cos(newYaw) * xzlen;
  83095. localTarget.x = Math.sin(newYaw) * xzlen;
  83096. }
  83097. }
  83098. }
  83099. if (yaw != newYaw) {
  83100. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  83101. localTarget.addInPlace(bonePos);
  83102. target = localTarget;
  83103. }
  83104. }
  83105. }
  83106. var zaxis = BoneLookController._tmpVecs[5];
  83107. var xaxis = BoneLookController._tmpVecs[6];
  83108. var yaxis = BoneLookController._tmpVecs[7];
  83109. var _tmpQuat = BoneLookController._tmpQuat;
  83110. target.subtractToRef(bonePos, zaxis);
  83111. zaxis.normalize();
  83112. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  83113. xaxis.normalize();
  83114. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  83115. yaxis.normalize();
  83116. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  83117. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  83118. return;
  83119. }
  83120. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  83121. return;
  83122. }
  83123. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  83124. return;
  83125. }
  83126. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  83127. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  83128. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  83129. }
  83130. if (this.slerpAmount < 1) {
  83131. if (!this._slerping) {
  83132. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  83133. }
  83134. if (this._transformYawPitch) {
  83135. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  83136. }
  83137. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  83138. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  83139. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  83140. this._slerping = true;
  83141. }
  83142. else {
  83143. if (this._transformYawPitch) {
  83144. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  83145. }
  83146. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  83147. this._slerping = false;
  83148. }
  83149. };
  83150. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  83151. var angDiff = ang2 - ang1;
  83152. angDiff %= Math.PI * 2;
  83153. if (angDiff > Math.PI) {
  83154. angDiff -= Math.PI * 2;
  83155. }
  83156. else if (angDiff < -Math.PI) {
  83157. angDiff += Math.PI * 2;
  83158. }
  83159. return angDiff;
  83160. };
  83161. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  83162. ang1 %= (2 * Math.PI);
  83163. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  83164. ang2 %= (2 * Math.PI);
  83165. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  83166. var ab = 0;
  83167. if (ang1 < ang2) {
  83168. ab = ang2 - ang1;
  83169. }
  83170. else {
  83171. ab = ang1 - ang2;
  83172. }
  83173. if (ab > Math.PI) {
  83174. ab = Math.PI * 2 - ab;
  83175. }
  83176. return ab;
  83177. };
  83178. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  83179. ang %= (2 * Math.PI);
  83180. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  83181. ang1 %= (2 * Math.PI);
  83182. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  83183. ang2 %= (2 * Math.PI);
  83184. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  83185. if (ang1 < ang2) {
  83186. if (ang > ang1 && ang < ang2) {
  83187. return true;
  83188. }
  83189. }
  83190. else {
  83191. if (ang > ang2 && ang < ang1) {
  83192. return true;
  83193. }
  83194. }
  83195. return false;
  83196. };
  83197. 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()];
  83198. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  83199. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83200. return BoneLookController;
  83201. }());
  83202. BABYLON.BoneLookController = BoneLookController;
  83203. })(BABYLON || (BABYLON = {}));
  83204. //# sourceMappingURL=babylon.boneLookController.js.map
  83205. var BABYLON;
  83206. (function (BABYLON) {
  83207. /**
  83208. * Class used to handle skinning animations
  83209. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  83210. */
  83211. var Skeleton = /** @class */ (function () {
  83212. /**
  83213. * Creates a new skeleton
  83214. * @param name defines the skeleton name
  83215. * @param id defines the skeleton Id
  83216. * @param scene defines the hosting scene
  83217. */
  83218. function Skeleton(
  83219. /** defines the skeleton name */
  83220. name,
  83221. /** defines the skeleton Id */
  83222. id, scene) {
  83223. this.name = name;
  83224. this.id = id;
  83225. /**
  83226. * Gets the list of child bones
  83227. */
  83228. this.bones = new Array();
  83229. /**
  83230. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  83231. */
  83232. this.needInitialSkinMatrix = false;
  83233. this._isDirty = true;
  83234. this._meshesWithPoseMatrix = new Array();
  83235. this._identity = BABYLON.Matrix.Identity();
  83236. this._ranges = {};
  83237. this._lastAbsoluteTransformsUpdateId = -1;
  83238. /**
  83239. * Specifies if the skeleton should be serialized
  83240. */
  83241. this.doNotSerialize = false;
  83242. this._animationPropertiesOverride = null;
  83243. // Events
  83244. /**
  83245. * An observable triggered before computing the skeleton's matrices
  83246. */
  83247. this.onBeforeComputeObservable = new BABYLON.Observable();
  83248. this.bones = [];
  83249. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83250. scene.skeletons.push(this);
  83251. //make sure it will recalculate the matrix next time prepare is called.
  83252. this._isDirty = true;
  83253. }
  83254. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  83255. /**
  83256. * Gets or sets the animation properties override
  83257. */
  83258. get: function () {
  83259. if (!this._animationPropertiesOverride) {
  83260. return this._scene.animationPropertiesOverride;
  83261. }
  83262. return this._animationPropertiesOverride;
  83263. },
  83264. set: function (value) {
  83265. this._animationPropertiesOverride = value;
  83266. },
  83267. enumerable: true,
  83268. configurable: true
  83269. });
  83270. // Members
  83271. /**
  83272. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  83273. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  83274. * @returns a Float32Array containing matrices data
  83275. */
  83276. Skeleton.prototype.getTransformMatrices = function (mesh) {
  83277. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  83278. return mesh._bonesTransformMatrices;
  83279. }
  83280. if (!this._transformMatrices) {
  83281. this.prepare();
  83282. }
  83283. return this._transformMatrices;
  83284. };
  83285. /**
  83286. * Gets the current hosting scene
  83287. * @returns a scene object
  83288. */
  83289. Skeleton.prototype.getScene = function () {
  83290. return this._scene;
  83291. };
  83292. // Methods
  83293. /**
  83294. * Gets a string representing the current skeleton data
  83295. * @param fullDetails defines a boolean indicating if we want a verbose version
  83296. * @returns a string representing the current skeleton data
  83297. */
  83298. Skeleton.prototype.toString = function (fullDetails) {
  83299. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  83300. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  83301. if (fullDetails) {
  83302. ret += ", Ranges: {";
  83303. var first = true;
  83304. for (var name_1 in this._ranges) {
  83305. if (first) {
  83306. ret += ", ";
  83307. first = false;
  83308. }
  83309. ret += name_1;
  83310. }
  83311. ret += "}";
  83312. }
  83313. return ret;
  83314. };
  83315. /**
  83316. * Get bone's index searching by name
  83317. * @param name defines bone's name to search for
  83318. * @return the indice of the bone. Returns -1 if not found
  83319. */
  83320. Skeleton.prototype.getBoneIndexByName = function (name) {
  83321. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  83322. if (this.bones[boneIndex].name === name) {
  83323. return boneIndex;
  83324. }
  83325. }
  83326. return -1;
  83327. };
  83328. /**
  83329. * Creater a new animation range
  83330. * @param name defines the name of the range
  83331. * @param from defines the start key
  83332. * @param to defines the end key
  83333. */
  83334. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  83335. // check name not already in use
  83336. if (!this._ranges[name]) {
  83337. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  83338. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83339. if (this.bones[i].animations[0]) {
  83340. this.bones[i].animations[0].createRange(name, from, to);
  83341. }
  83342. }
  83343. }
  83344. };
  83345. /**
  83346. * Delete a specific animation range
  83347. * @param name defines the name of the range
  83348. * @param deleteFrames defines if frames must be removed as well
  83349. */
  83350. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  83351. if (deleteFrames === void 0) { deleteFrames = true; }
  83352. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83353. if (this.bones[i].animations[0]) {
  83354. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  83355. }
  83356. }
  83357. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  83358. };
  83359. /**
  83360. * Gets a specific animation range
  83361. * @param name defines the name of the range to look for
  83362. * @returns the requested animation range or null if not found
  83363. */
  83364. Skeleton.prototype.getAnimationRange = function (name) {
  83365. return this._ranges[name];
  83366. };
  83367. /**
  83368. * Gets the list of all animation ranges defined on this skeleton
  83369. * @returns an array
  83370. */
  83371. Skeleton.prototype.getAnimationRanges = function () {
  83372. var animationRanges = [];
  83373. var name;
  83374. var i = 0;
  83375. for (name in this._ranges) {
  83376. animationRanges[i] = this._ranges[name];
  83377. i++;
  83378. }
  83379. return animationRanges;
  83380. };
  83381. /**
  83382. * Copy animation range from a source skeleton.
  83383. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  83384. * @param source defines the source skeleton
  83385. * @param name defines the name of the range to copy
  83386. * @param rescaleAsRequired defines if rescaling must be applied if required
  83387. * @returns true if operation was successful
  83388. */
  83389. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  83390. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  83391. if (this._ranges[name] || !source.getAnimationRange(name)) {
  83392. return false;
  83393. }
  83394. var ret = true;
  83395. var frameOffset = this._getHighestAnimationFrame() + 1;
  83396. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  83397. var boneDict = {};
  83398. var sourceBones = source.bones;
  83399. var nBones;
  83400. var i;
  83401. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  83402. boneDict[sourceBones[i].name] = sourceBones[i];
  83403. }
  83404. if (this.bones.length !== sourceBones.length) {
  83405. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  83406. ret = false;
  83407. }
  83408. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  83409. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  83410. var boneName = this.bones[i].name;
  83411. var sourceBone = boneDict[boneName];
  83412. if (sourceBone) {
  83413. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  83414. }
  83415. else {
  83416. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  83417. ret = false;
  83418. }
  83419. }
  83420. // do not call createAnimationRange(), since it also is done to bones, which was already done
  83421. var range = source.getAnimationRange(name);
  83422. if (range) {
  83423. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  83424. }
  83425. return ret;
  83426. };
  83427. /**
  83428. * Forces the skeleton to go to rest pose
  83429. */
  83430. Skeleton.prototype.returnToRest = function () {
  83431. for (var index = 0; index < this.bones.length; index++) {
  83432. this.bones[index].returnToRest();
  83433. }
  83434. };
  83435. Skeleton.prototype._getHighestAnimationFrame = function () {
  83436. var ret = 0;
  83437. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83438. if (this.bones[i].animations[0]) {
  83439. var highest = this.bones[i].animations[0].getHighestFrame();
  83440. if (ret < highest) {
  83441. ret = highest;
  83442. }
  83443. }
  83444. }
  83445. return ret;
  83446. };
  83447. /**
  83448. * Begin a specific animation range
  83449. * @param name defines the name of the range to start
  83450. * @param loop defines if looping must be turned on (false by default)
  83451. * @param speedRatio defines the speed ratio to apply (1 by default)
  83452. * @param onAnimationEnd defines a callback which will be called when animation will end
  83453. * @returns a new animatable
  83454. */
  83455. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  83456. var range = this.getAnimationRange(name);
  83457. if (!range) {
  83458. return null;
  83459. }
  83460. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  83461. };
  83462. /** @hidden */
  83463. Skeleton.prototype._markAsDirty = function () {
  83464. this._isDirty = true;
  83465. };
  83466. /** @hidden */
  83467. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  83468. this._meshesWithPoseMatrix.push(mesh);
  83469. };
  83470. /** @hidden */
  83471. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  83472. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  83473. if (index > -1) {
  83474. this._meshesWithPoseMatrix.splice(index, 1);
  83475. }
  83476. };
  83477. /** @hidden */
  83478. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  83479. this.onBeforeComputeObservable.notifyObservers(this);
  83480. for (var index = 0; index < this.bones.length; index++) {
  83481. var bone = this.bones[index];
  83482. var parentBone = bone.getParent();
  83483. if (parentBone) {
  83484. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  83485. }
  83486. else {
  83487. if (initialSkinMatrix) {
  83488. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  83489. }
  83490. else {
  83491. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  83492. }
  83493. }
  83494. if (bone._index !== -1) {
  83495. var mappedIndex = bone._index === null ? index : bone._index;
  83496. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  83497. }
  83498. }
  83499. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  83500. };
  83501. /**
  83502. * Build all resources required to render a skeleton
  83503. */
  83504. Skeleton.prototype.prepare = function () {
  83505. if (!this._isDirty) {
  83506. return;
  83507. }
  83508. if (this.needInitialSkinMatrix) {
  83509. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  83510. var mesh = this._meshesWithPoseMatrix[index];
  83511. var poseMatrix = mesh.getPoseMatrix();
  83512. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  83513. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  83514. }
  83515. if (this._synchronizedWithMesh !== mesh) {
  83516. this._synchronizedWithMesh = mesh;
  83517. // Prepare bones
  83518. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  83519. var bone = this.bones[boneIndex];
  83520. if (!bone.getParent()) {
  83521. var matrix = bone.getBaseMatrix();
  83522. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  83523. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  83524. }
  83525. }
  83526. }
  83527. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  83528. }
  83529. }
  83530. else {
  83531. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  83532. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  83533. }
  83534. this._computeTransformMatrices(this._transformMatrices, null);
  83535. }
  83536. this._isDirty = false;
  83537. this._scene._activeBones.addCount(this.bones.length, false);
  83538. };
  83539. /**
  83540. * Gets the list of animatables currently running for this skeleton
  83541. * @returns an array of animatables
  83542. */
  83543. Skeleton.prototype.getAnimatables = function () {
  83544. if (!this._animatables || this._animatables.length !== this.bones.length) {
  83545. this._animatables = [];
  83546. for (var index = 0; index < this.bones.length; index++) {
  83547. this._animatables.push(this.bones[index]);
  83548. }
  83549. }
  83550. return this._animatables;
  83551. };
  83552. /**
  83553. * Clone the current skeleton
  83554. * @param name defines the name of the new skeleton
  83555. * @param id defines the id of the enw skeleton
  83556. * @returns the new skeleton
  83557. */
  83558. Skeleton.prototype.clone = function (name, id) {
  83559. var result = new Skeleton(name, id || name, this._scene);
  83560. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  83561. for (var index = 0; index < this.bones.length; index++) {
  83562. var source = this.bones[index];
  83563. var parentBone = null;
  83564. var parent_1 = source.getParent();
  83565. if (parent_1) {
  83566. var parentIndex = this.bones.indexOf(parent_1);
  83567. parentBone = result.bones[parentIndex];
  83568. }
  83569. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  83570. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  83571. }
  83572. if (this._ranges) {
  83573. result._ranges = {};
  83574. for (var rangeName in this._ranges) {
  83575. var range = this._ranges[rangeName];
  83576. if (range) {
  83577. result._ranges[rangeName] = range.clone();
  83578. }
  83579. }
  83580. }
  83581. this._isDirty = true;
  83582. return result;
  83583. };
  83584. /**
  83585. * Enable animation blending for this skeleton
  83586. * @param blendingSpeed defines the blending speed to apply
  83587. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  83588. */
  83589. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  83590. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  83591. this.bones.forEach(function (bone) {
  83592. bone.animations.forEach(function (animation) {
  83593. animation.enableBlending = true;
  83594. animation.blendingSpeed = blendingSpeed;
  83595. });
  83596. });
  83597. };
  83598. /**
  83599. * Releases all resources associated with the current skeleton
  83600. */
  83601. Skeleton.prototype.dispose = function () {
  83602. this._meshesWithPoseMatrix = [];
  83603. // Animations
  83604. this.getScene().stopAnimation(this);
  83605. // Remove from scene
  83606. this.getScene().removeSkeleton(this);
  83607. };
  83608. /**
  83609. * Serialize the skeleton in a JSON object
  83610. * @returns a JSON object
  83611. */
  83612. Skeleton.prototype.serialize = function () {
  83613. var serializationObject = {};
  83614. serializationObject.name = this.name;
  83615. serializationObject.id = this.id;
  83616. if (this.dimensionsAtRest) {
  83617. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  83618. }
  83619. serializationObject.bones = [];
  83620. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  83621. for (var index = 0; index < this.bones.length; index++) {
  83622. var bone = this.bones[index];
  83623. var parent_2 = bone.getParent();
  83624. var serializedBone = {
  83625. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  83626. name: bone.name,
  83627. matrix: bone.getBaseMatrix().toArray(),
  83628. rest: bone.getRestPose().toArray()
  83629. };
  83630. serializationObject.bones.push(serializedBone);
  83631. if (bone.length) {
  83632. serializedBone.length = bone.length;
  83633. }
  83634. if (bone.metadata) {
  83635. serializedBone.metadata = bone.metadata;
  83636. }
  83637. if (bone.animations && bone.animations.length > 0) {
  83638. serializedBone.animation = bone.animations[0].serialize();
  83639. }
  83640. serializationObject.ranges = [];
  83641. for (var name in this._ranges) {
  83642. var source = this._ranges[name];
  83643. if (!source) {
  83644. continue;
  83645. }
  83646. var range = {};
  83647. range.name = name;
  83648. range.from = source.from;
  83649. range.to = source.to;
  83650. serializationObject.ranges.push(range);
  83651. }
  83652. }
  83653. return serializationObject;
  83654. };
  83655. /**
  83656. * Creates a new skeleton from serialized data
  83657. * @param parsedSkeleton defines the serialized data
  83658. * @param scene defines the hosting scene
  83659. * @returns a new skeleton
  83660. */
  83661. Skeleton.Parse = function (parsedSkeleton, scene) {
  83662. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  83663. if (parsedSkeleton.dimensionsAtRest) {
  83664. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  83665. }
  83666. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  83667. var index;
  83668. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  83669. var parsedBone = parsedSkeleton.bones[index];
  83670. var parentBone = null;
  83671. if (parsedBone.parentBoneIndex > -1) {
  83672. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  83673. }
  83674. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  83675. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  83676. if (parsedBone.length) {
  83677. bone.length = parsedBone.length;
  83678. }
  83679. if (parsedBone.metadata) {
  83680. bone.metadata = parsedBone.metadata;
  83681. }
  83682. if (parsedBone.animation) {
  83683. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  83684. }
  83685. }
  83686. // placed after bones, so createAnimationRange can cascade down
  83687. if (parsedSkeleton.ranges) {
  83688. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  83689. var data = parsedSkeleton.ranges[index];
  83690. skeleton.createAnimationRange(data.name, data.from, data.to);
  83691. }
  83692. }
  83693. return skeleton;
  83694. };
  83695. /**
  83696. * Compute all node absolute transforms
  83697. * @param forceUpdate defines if computation must be done even if cache is up to date
  83698. */
  83699. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  83700. if (forceUpdate === void 0) { forceUpdate = false; }
  83701. var renderId = this._scene.getRenderId();
  83702. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  83703. this.bones[0].computeAbsoluteTransforms();
  83704. this._lastAbsoluteTransformsUpdateId = renderId;
  83705. }
  83706. };
  83707. /**
  83708. * Gets the root pose matrix
  83709. * @returns a matrix
  83710. */
  83711. Skeleton.prototype.getPoseMatrix = function () {
  83712. var poseMatrix = null;
  83713. if (this._meshesWithPoseMatrix.length > 0) {
  83714. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  83715. }
  83716. return poseMatrix;
  83717. };
  83718. /**
  83719. * Sorts bones per internal index
  83720. */
  83721. Skeleton.prototype.sortBones = function () {
  83722. var bones = new Array();
  83723. var visited = new Array(this.bones.length);
  83724. for (var index = 0; index < this.bones.length; index++) {
  83725. this._sortBones(index, bones, visited);
  83726. }
  83727. this.bones = bones;
  83728. };
  83729. Skeleton.prototype._sortBones = function (index, bones, visited) {
  83730. if (visited[index]) {
  83731. return;
  83732. }
  83733. visited[index] = true;
  83734. var bone = this.bones[index];
  83735. if (bone._index === undefined) {
  83736. bone._index = index;
  83737. }
  83738. var parentBone = bone.getParent();
  83739. if (parentBone) {
  83740. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  83741. }
  83742. bones.push(bone);
  83743. };
  83744. return Skeleton;
  83745. }());
  83746. BABYLON.Skeleton = Skeleton;
  83747. })(BABYLON || (BABYLON = {}));
  83748. //# sourceMappingURL=babylon.skeleton.js.map
  83749. var BABYLON;
  83750. (function (BABYLON) {
  83751. ;
  83752. /**
  83753. * This groups tools to convert HDR texture to native colors array.
  83754. */
  83755. var HDRTools = /** @class */ (function () {
  83756. function HDRTools() {
  83757. }
  83758. HDRTools.Ldexp = function (mantissa, exponent) {
  83759. if (exponent > 1023) {
  83760. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  83761. }
  83762. if (exponent < -1074) {
  83763. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  83764. }
  83765. return mantissa * Math.pow(2, exponent);
  83766. };
  83767. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  83768. if (exponent > 0) { /*nonzero pixel*/
  83769. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  83770. float32array[index + 0] = red * exponent;
  83771. float32array[index + 1] = green * exponent;
  83772. float32array[index + 2] = blue * exponent;
  83773. }
  83774. else {
  83775. float32array[index + 0] = 0;
  83776. float32array[index + 1] = 0;
  83777. float32array[index + 2] = 0;
  83778. }
  83779. };
  83780. HDRTools.readStringLine = function (uint8array, startIndex) {
  83781. var line = "";
  83782. var character = "";
  83783. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  83784. character = String.fromCharCode(uint8array[i]);
  83785. if (character == "\n") {
  83786. break;
  83787. }
  83788. line += character;
  83789. }
  83790. return line;
  83791. };
  83792. /**
  83793. * Reads header information from an RGBE texture stored in a native array.
  83794. * More information on this format are available here:
  83795. * https://en.wikipedia.org/wiki/RGBE_image_format
  83796. *
  83797. * @param uint8array The binary file stored in native array.
  83798. * @return The header information.
  83799. */
  83800. HDRTools.RGBE_ReadHeader = function (uint8array) {
  83801. var height = 0;
  83802. var width = 0;
  83803. var line = this.readStringLine(uint8array, 0);
  83804. if (line[0] != '#' || line[1] != '?') {
  83805. throw "Bad HDR Format.";
  83806. }
  83807. var endOfHeader = false;
  83808. var findFormat = false;
  83809. var lineIndex = 0;
  83810. do {
  83811. lineIndex += (line.length + 1);
  83812. line = this.readStringLine(uint8array, lineIndex);
  83813. if (line == "FORMAT=32-bit_rle_rgbe") {
  83814. findFormat = true;
  83815. }
  83816. else if (line.length == 0) {
  83817. endOfHeader = true;
  83818. }
  83819. } while (!endOfHeader);
  83820. if (!findFormat) {
  83821. throw "HDR Bad header format, unsupported FORMAT";
  83822. }
  83823. lineIndex += (line.length + 1);
  83824. line = this.readStringLine(uint8array, lineIndex);
  83825. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  83826. var match = sizeRegexp.exec(line);
  83827. // TODO. Support +Y and -X if needed.
  83828. if (!match || match.length < 3) {
  83829. throw "HDR Bad header format, no size";
  83830. }
  83831. width = parseInt(match[2]);
  83832. height = parseInt(match[1]);
  83833. if (width < 8 || width > 0x7fff) {
  83834. throw "HDR Bad header format, unsupported size";
  83835. }
  83836. lineIndex += (line.length + 1);
  83837. return {
  83838. height: height,
  83839. width: width,
  83840. dataPosition: lineIndex
  83841. };
  83842. };
  83843. /**
  83844. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  83845. * This RGBE texture needs to store the information as a panorama.
  83846. *
  83847. * More information on this format are available here:
  83848. * https://en.wikipedia.org/wiki/RGBE_image_format
  83849. *
  83850. * @param buffer The binary file stored in an array buffer.
  83851. * @param size The expected size of the extracted cubemap.
  83852. * @return The Cube Map information.
  83853. */
  83854. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  83855. var uint8array = new Uint8Array(buffer);
  83856. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  83857. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83858. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  83859. return cubeMapData;
  83860. };
  83861. /**
  83862. * Returns the pixels data extracted from an RGBE texture.
  83863. * This pixels will be stored left to right up to down in the R G B order in one array.
  83864. *
  83865. * More information on this format are available here:
  83866. * https://en.wikipedia.org/wiki/RGBE_image_format
  83867. *
  83868. * @param uint8array The binary file stored in an array buffer.
  83869. * @param hdrInfo The header information of the file.
  83870. * @return The pixels data in RGB right to left up to down order.
  83871. */
  83872. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  83873. // Keep for multi format supports.
  83874. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83875. };
  83876. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  83877. var num_scanlines = hdrInfo.height;
  83878. var scanline_width = hdrInfo.width;
  83879. var a, b, c, d, count;
  83880. var dataIndex = hdrInfo.dataPosition;
  83881. var index = 0, endIndex = 0, i = 0;
  83882. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  83883. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  83884. // 3 channels of 4 bytes per pixel in float.
  83885. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  83886. var resultArray = new Float32Array(resultBuffer);
  83887. // read in each successive scanline
  83888. while (num_scanlines > 0) {
  83889. a = uint8array[dataIndex++];
  83890. b = uint8array[dataIndex++];
  83891. c = uint8array[dataIndex++];
  83892. d = uint8array[dataIndex++];
  83893. if (a != 2 || b != 2 || (c & 0x80)) {
  83894. // this file is not run length encoded
  83895. throw "HDR Bad header format, not RLE";
  83896. }
  83897. if (((c << 8) | d) != scanline_width) {
  83898. throw "HDR Bad header format, wrong scan line width";
  83899. }
  83900. index = 0;
  83901. // read each of the four channels for the scanline into the buffer
  83902. for (i = 0; i < 4; i++) {
  83903. endIndex = (i + 1) * scanline_width;
  83904. while (index < endIndex) {
  83905. a = uint8array[dataIndex++];
  83906. b = uint8array[dataIndex++];
  83907. if (a > 128) {
  83908. // a run of the same value
  83909. count = a - 128;
  83910. if ((count == 0) || (count > endIndex - index)) {
  83911. throw "HDR Bad Format, bad scanline data (run)";
  83912. }
  83913. while (count-- > 0) {
  83914. scanLineArray[index++] = b;
  83915. }
  83916. }
  83917. else {
  83918. // a non-run
  83919. count = a;
  83920. if ((count == 0) || (count > endIndex - index)) {
  83921. throw "HDR Bad Format, bad scanline data (non-run)";
  83922. }
  83923. scanLineArray[index++] = b;
  83924. if (--count > 0) {
  83925. for (var j = 0; j < count; j++) {
  83926. scanLineArray[index++] = uint8array[dataIndex++];
  83927. }
  83928. }
  83929. }
  83930. }
  83931. }
  83932. // now convert data from buffer into floats
  83933. for (i = 0; i < scanline_width; i++) {
  83934. a = scanLineArray[i];
  83935. b = scanLineArray[i + scanline_width];
  83936. c = scanLineArray[i + 2 * scanline_width];
  83937. d = scanLineArray[i + 3 * scanline_width];
  83938. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  83939. }
  83940. num_scanlines--;
  83941. }
  83942. return resultArray;
  83943. };
  83944. return HDRTools;
  83945. }());
  83946. BABYLON.HDRTools = HDRTools;
  83947. })(BABYLON || (BABYLON = {}));
  83948. //# sourceMappingURL=babylon.hdr.js.map
  83949. var BABYLON;
  83950. (function (BABYLON) {
  83951. /**
  83952. * This represents a texture coming from an HDR input.
  83953. *
  83954. * The only supported format is currently panorama picture stored in RGBE format.
  83955. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83956. */
  83957. var HDRCubeTexture = /** @class */ (function (_super) {
  83958. __extends(HDRCubeTexture, _super);
  83959. /**
  83960. * Instantiates an HDRTexture from the following parameters.
  83961. *
  83962. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83963. * @param scene The scene the texture will be used in
  83964. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83965. * @param noMipmap Forces to not generate the mipmap if true
  83966. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83967. * @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)
  83968. * @param reserved Reserved flag for internal use.
  83969. */
  83970. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83971. if (noMipmap === void 0) { noMipmap = false; }
  83972. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83973. if (gammaSpace === void 0) { gammaSpace = false; }
  83974. if (reserved === void 0) { reserved = false; }
  83975. if (onLoad === void 0) { onLoad = null; }
  83976. if (onError === void 0) { onError = null; }
  83977. var _this = _super.call(this, scene) || this;
  83978. _this._generateHarmonics = true;
  83979. _this._onLoad = null;
  83980. _this._onError = null;
  83981. /**
  83982. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83983. */
  83984. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83985. _this._isBlocking = true;
  83986. _this._rotationY = 0;
  83987. /**
  83988. * Gets or sets the center of the bounding box associated with the cube texture
  83989. * It must define where the camera used to render the texture was set
  83990. */
  83991. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83992. if (!url) {
  83993. return _this;
  83994. }
  83995. _this.name = url;
  83996. _this.url = url;
  83997. _this.hasAlpha = false;
  83998. _this.isCube = true;
  83999. _this._textureMatrix = BABYLON.Matrix.Identity();
  84000. _this._onLoad = onLoad;
  84001. _this._onError = onError;
  84002. _this.gammaSpace = gammaSpace;
  84003. _this._noMipmap = noMipmap;
  84004. _this._size = size;
  84005. _this._texture = _this._getFromCache(url, _this._noMipmap);
  84006. if (!_this._texture) {
  84007. if (!scene.useDelayedTextureLoading) {
  84008. _this.loadTexture();
  84009. }
  84010. else {
  84011. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  84012. }
  84013. }
  84014. return _this;
  84015. }
  84016. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  84017. /**
  84018. * Gets wether or not the texture is blocking during loading.
  84019. */
  84020. get: function () {
  84021. return this._isBlocking;
  84022. },
  84023. /**
  84024. * Sets wether or not the texture is blocking during loading.
  84025. */
  84026. set: function (value) {
  84027. this._isBlocking = value;
  84028. },
  84029. enumerable: true,
  84030. configurable: true
  84031. });
  84032. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  84033. /**
  84034. * Gets texture matrix rotation angle around Y axis radians.
  84035. */
  84036. get: function () {
  84037. return this._rotationY;
  84038. },
  84039. /**
  84040. * Sets texture matrix rotation angle around Y axis in radians.
  84041. */
  84042. set: function (value) {
  84043. this._rotationY = value;
  84044. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  84045. },
  84046. enumerable: true,
  84047. configurable: true
  84048. });
  84049. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  84050. get: function () {
  84051. return this._boundingBoxSize;
  84052. },
  84053. /**
  84054. * Gets or sets the size of the bounding box associated with the cube texture
  84055. * When defined, the cubemap will switch to local mode
  84056. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  84057. * @example https://www.babylonjs-playground.com/#RNASML
  84058. */
  84059. set: function (value) {
  84060. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  84061. return;
  84062. }
  84063. this._boundingBoxSize = value;
  84064. var scene = this.getScene();
  84065. if (scene) {
  84066. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  84067. }
  84068. },
  84069. enumerable: true,
  84070. configurable: true
  84071. });
  84072. /**
  84073. * Occurs when the file is raw .hdr file.
  84074. */
  84075. HDRCubeTexture.prototype.loadTexture = function () {
  84076. var _this = this;
  84077. var callback = function (buffer) {
  84078. _this.lodGenerationOffset = 0.0;
  84079. _this.lodGenerationScale = 0.8;
  84080. var scene = _this.getScene();
  84081. if (!scene) {
  84082. return null;
  84083. }
  84084. // Extract the raw linear data.
  84085. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  84086. // Generate harmonics if needed.
  84087. if (_this._generateHarmonics) {
  84088. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  84089. _this.sphericalPolynomial = sphericalPolynomial;
  84090. }
  84091. var results = [];
  84092. var byteArray = null;
  84093. // Push each faces.
  84094. for (var j = 0; j < 6; j++) {
  84095. // Create uintarray fallback.
  84096. if (!scene.getEngine().getCaps().textureFloat) {
  84097. // 3 channels of 1 bytes per pixel in bytes.
  84098. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  84099. byteArray = new Uint8Array(byteBuffer);
  84100. }
  84101. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  84102. // If special cases.
  84103. if (_this.gammaSpace || byteArray) {
  84104. for (var i = 0; i < _this._size * _this._size; i++) {
  84105. // Put in gamma space if requested.
  84106. if (_this.gammaSpace) {
  84107. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  84108. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  84109. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  84110. }
  84111. // Convert to int texture for fallback.
  84112. if (byteArray) {
  84113. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  84114. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  84115. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  84116. // May use luminance instead if the result is not accurate.
  84117. var max = Math.max(Math.max(r, g), b);
  84118. if (max > 255) {
  84119. var scale = 255 / max;
  84120. r *= scale;
  84121. g *= scale;
  84122. b *= scale;
  84123. }
  84124. byteArray[(i * 3) + 0] = r;
  84125. byteArray[(i * 3) + 1] = g;
  84126. byteArray[(i * 3) + 2] = b;
  84127. }
  84128. }
  84129. }
  84130. if (byteArray) {
  84131. results.push(byteArray);
  84132. }
  84133. else {
  84134. results.push(dataFace);
  84135. }
  84136. }
  84137. return results;
  84138. };
  84139. var scene = this.getScene();
  84140. if (scene) {
  84141. 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);
  84142. }
  84143. };
  84144. HDRCubeTexture.prototype.clone = function () {
  84145. var scene = this.getScene();
  84146. if (!scene) {
  84147. return this;
  84148. }
  84149. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  84150. // Base texture
  84151. newTexture.level = this.level;
  84152. newTexture.wrapU = this.wrapU;
  84153. newTexture.wrapV = this.wrapV;
  84154. newTexture.coordinatesIndex = this.coordinatesIndex;
  84155. newTexture.coordinatesMode = this.coordinatesMode;
  84156. return newTexture;
  84157. };
  84158. // Methods
  84159. HDRCubeTexture.prototype.delayLoad = function () {
  84160. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  84161. return;
  84162. }
  84163. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  84164. this._texture = this._getFromCache(this.url, this._noMipmap);
  84165. if (!this._texture) {
  84166. this.loadTexture();
  84167. }
  84168. };
  84169. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  84170. return this._textureMatrix;
  84171. };
  84172. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  84173. this._textureMatrix = value;
  84174. };
  84175. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  84176. var texture = null;
  84177. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  84178. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  84179. texture.name = parsedTexture.name;
  84180. texture.hasAlpha = parsedTexture.hasAlpha;
  84181. texture.level = parsedTexture.level;
  84182. texture.coordinatesMode = parsedTexture.coordinatesMode;
  84183. texture.isBlocking = parsedTexture.isBlocking;
  84184. }
  84185. if (texture) {
  84186. if (parsedTexture.boundingBoxPosition) {
  84187. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  84188. }
  84189. if (parsedTexture.boundingBoxSize) {
  84190. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  84191. }
  84192. if (parsedTexture.rotationY) {
  84193. texture.rotationY = parsedTexture.rotationY;
  84194. }
  84195. }
  84196. return texture;
  84197. };
  84198. HDRCubeTexture.prototype.serialize = function () {
  84199. if (!this.name) {
  84200. return null;
  84201. }
  84202. var serializationObject = {};
  84203. serializationObject.name = this.name;
  84204. serializationObject.hasAlpha = this.hasAlpha;
  84205. serializationObject.isCube = true;
  84206. serializationObject.level = this.level;
  84207. serializationObject.size = this._size;
  84208. serializationObject.coordinatesMode = this.coordinatesMode;
  84209. serializationObject.useInGammaSpace = this.gammaSpace;
  84210. serializationObject.generateHarmonics = this._generateHarmonics;
  84211. serializationObject.customType = "BABYLON.HDRCubeTexture";
  84212. serializationObject.noMipmap = this._noMipmap;
  84213. serializationObject.isBlocking = this._isBlocking;
  84214. serializationObject.rotationY = this._rotationY;
  84215. return serializationObject;
  84216. };
  84217. HDRCubeTexture._facesMapping = [
  84218. "right",
  84219. "left",
  84220. "up",
  84221. "down",
  84222. "front",
  84223. "back"
  84224. ];
  84225. return HDRCubeTexture;
  84226. }(BABYLON.BaseTexture));
  84227. BABYLON.HDRCubeTexture = HDRCubeTexture;
  84228. })(BABYLON || (BABYLON = {}));
  84229. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  84230. var BABYLON;
  84231. (function (BABYLON) {
  84232. /**
  84233. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  84234. */
  84235. var PanoramaToCubeMapTools = /** @class */ (function () {
  84236. function PanoramaToCubeMapTools() {
  84237. }
  84238. /**
  84239. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  84240. *
  84241. * @param float32Array The source data.
  84242. * @param inputWidth The width of the input panorama.
  84243. * @param inputhHeight The height of the input panorama.
  84244. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  84245. * @return The cubemap data
  84246. */
  84247. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  84248. if (!float32Array) {
  84249. throw "ConvertPanoramaToCubemap: input cannot be null";
  84250. }
  84251. if (float32Array.length != inputWidth * inputHeight * 3) {
  84252. throw "ConvertPanoramaToCubemap: input size is wrong";
  84253. }
  84254. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  84255. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  84256. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  84257. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  84258. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  84259. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  84260. return {
  84261. front: textureFront,
  84262. back: textureBack,
  84263. left: textureLeft,
  84264. right: textureRight,
  84265. up: textureUp,
  84266. down: textureDown,
  84267. size: size,
  84268. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84269. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  84270. gammaSpace: false,
  84271. };
  84272. };
  84273. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  84274. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  84275. var textureArray = new Float32Array(buffer);
  84276. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  84277. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  84278. var dy = 1 / texSize;
  84279. var fy = 0;
  84280. for (var y = 0; y < texSize; y++) {
  84281. var xv1 = faceData[0];
  84282. var xv2 = faceData[2];
  84283. for (var x = 0; x < texSize; x++) {
  84284. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  84285. v.normalize();
  84286. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  84287. // 3 channels per pixels
  84288. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  84289. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  84290. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  84291. xv1 = xv1.add(rotDX1);
  84292. xv2 = xv2.add(rotDX2);
  84293. }
  84294. fy += dy;
  84295. }
  84296. return textureArray;
  84297. };
  84298. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  84299. var theta = Math.atan2(vDir.z, vDir.x);
  84300. var phi = Math.acos(vDir.y);
  84301. while (theta < -Math.PI)
  84302. theta += 2 * Math.PI;
  84303. while (theta > Math.PI)
  84304. theta -= 2 * Math.PI;
  84305. var dx = theta / Math.PI;
  84306. var dy = phi / Math.PI;
  84307. // recenter.
  84308. dx = dx * 0.5 + 0.5;
  84309. var px = Math.round(dx * inputWidth);
  84310. if (px < 0)
  84311. px = 0;
  84312. else if (px >= inputWidth)
  84313. px = inputWidth - 1;
  84314. var py = Math.round(dy * inputHeight);
  84315. if (py < 0)
  84316. py = 0;
  84317. else if (py >= inputHeight)
  84318. py = inputHeight - 1;
  84319. var inputY = (inputHeight - py - 1);
  84320. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  84321. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  84322. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  84323. return {
  84324. r: r,
  84325. g: g,
  84326. b: b
  84327. };
  84328. };
  84329. PanoramaToCubeMapTools.FACE_FRONT = [
  84330. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84331. new BABYLON.Vector3(1.0, -1.0, -1.0),
  84332. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  84333. new BABYLON.Vector3(1.0, 1.0, -1.0)
  84334. ];
  84335. PanoramaToCubeMapTools.FACE_BACK = [
  84336. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84337. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84338. new BABYLON.Vector3(1.0, 1.0, 1.0),
  84339. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  84340. ];
  84341. PanoramaToCubeMapTools.FACE_RIGHT = [
  84342. new BABYLON.Vector3(1.0, -1.0, -1.0),
  84343. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84344. new BABYLON.Vector3(1.0, 1.0, -1.0),
  84345. new BABYLON.Vector3(1.0, 1.0, 1.0)
  84346. ];
  84347. PanoramaToCubeMapTools.FACE_LEFT = [
  84348. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84349. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84350. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  84351. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  84352. ];
  84353. PanoramaToCubeMapTools.FACE_DOWN = [
  84354. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  84355. new BABYLON.Vector3(1.0, 1.0, -1.0),
  84356. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  84357. new BABYLON.Vector3(1.0, 1.0, 1.0)
  84358. ];
  84359. PanoramaToCubeMapTools.FACE_UP = [
  84360. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84361. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84362. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84363. new BABYLON.Vector3(1.0, -1.0, -1.0)
  84364. ];
  84365. return PanoramaToCubeMapTools;
  84366. }());
  84367. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  84368. })(BABYLON || (BABYLON = {}));
  84369. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  84370. var BABYLON;
  84371. (function (BABYLON) {
  84372. var IndexedVector2 = /** @class */ (function (_super) {
  84373. __extends(IndexedVector2, _super);
  84374. function IndexedVector2(original, index) {
  84375. var _this = _super.call(this, original.x, original.y) || this;
  84376. _this.index = index;
  84377. return _this;
  84378. }
  84379. return IndexedVector2;
  84380. }(BABYLON.Vector2));
  84381. var PolygonPoints = /** @class */ (function () {
  84382. function PolygonPoints() {
  84383. this.elements = new Array();
  84384. }
  84385. PolygonPoints.prototype.add = function (originalPoints) {
  84386. var _this = this;
  84387. var result = new Array();
  84388. originalPoints.forEach(function (point) {
  84389. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  84390. var newPoint = new IndexedVector2(point, _this.elements.length);
  84391. result.push(newPoint);
  84392. _this.elements.push(newPoint);
  84393. }
  84394. });
  84395. return result;
  84396. };
  84397. PolygonPoints.prototype.computeBounds = function () {
  84398. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  84399. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  84400. this.elements.forEach(function (point) {
  84401. // x
  84402. if (point.x < lmin.x) {
  84403. lmin.x = point.x;
  84404. }
  84405. else if (point.x > lmax.x) {
  84406. lmax.x = point.x;
  84407. }
  84408. // y
  84409. if (point.y < lmin.y) {
  84410. lmin.y = point.y;
  84411. }
  84412. else if (point.y > lmax.y) {
  84413. lmax.y = point.y;
  84414. }
  84415. });
  84416. return {
  84417. min: lmin,
  84418. max: lmax,
  84419. width: lmax.x - lmin.x,
  84420. height: lmax.y - lmin.y
  84421. };
  84422. };
  84423. return PolygonPoints;
  84424. }());
  84425. var Polygon = /** @class */ (function () {
  84426. function Polygon() {
  84427. }
  84428. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  84429. return [
  84430. new BABYLON.Vector2(xmin, ymin),
  84431. new BABYLON.Vector2(xmax, ymin),
  84432. new BABYLON.Vector2(xmax, ymax),
  84433. new BABYLON.Vector2(xmin, ymax)
  84434. ];
  84435. };
  84436. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  84437. if (cx === void 0) { cx = 0; }
  84438. if (cy === void 0) { cy = 0; }
  84439. if (numberOfSides === void 0) { numberOfSides = 32; }
  84440. var result = new Array();
  84441. var angle = 0;
  84442. var increment = (Math.PI * 2) / numberOfSides;
  84443. for (var i = 0; i < numberOfSides; i++) {
  84444. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  84445. angle -= increment;
  84446. }
  84447. return result;
  84448. };
  84449. Polygon.Parse = function (input) {
  84450. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  84451. var i, result = [];
  84452. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  84453. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  84454. }
  84455. return result;
  84456. };
  84457. Polygon.StartingAt = function (x, y) {
  84458. return BABYLON.Path2.StartingAt(x, y);
  84459. };
  84460. return Polygon;
  84461. }());
  84462. BABYLON.Polygon = Polygon;
  84463. var PolygonMeshBuilder = /** @class */ (function () {
  84464. function PolygonMeshBuilder(name, contours, scene) {
  84465. this._points = new PolygonPoints();
  84466. this._outlinepoints = new PolygonPoints();
  84467. this._holes = new Array();
  84468. this._epoints = new Array();
  84469. this._eholes = new Array();
  84470. this._name = name;
  84471. this._scene = scene;
  84472. var points;
  84473. if (contours instanceof BABYLON.Path2) {
  84474. points = contours.getPoints();
  84475. }
  84476. else {
  84477. points = contours;
  84478. }
  84479. this._addToepoint(points);
  84480. this._points.add(points);
  84481. this._outlinepoints.add(points);
  84482. if (typeof earcut === 'undefined') {
  84483. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  84484. }
  84485. }
  84486. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  84487. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  84488. var p = points_1[_i];
  84489. this._epoints.push(p.x, p.y);
  84490. }
  84491. };
  84492. PolygonMeshBuilder.prototype.addHole = function (hole) {
  84493. this._points.add(hole);
  84494. var holepoints = new PolygonPoints();
  84495. holepoints.add(hole);
  84496. this._holes.push(holepoints);
  84497. this._eholes.push(this._epoints.length / 2);
  84498. this._addToepoint(hole);
  84499. return this;
  84500. };
  84501. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  84502. var _this = this;
  84503. if (updatable === void 0) { updatable = false; }
  84504. if (depth === void 0) { depth = 0; }
  84505. var result = new BABYLON.Mesh(this._name, this._scene);
  84506. var normals = new Array();
  84507. var positions = new Array();
  84508. var uvs = new Array();
  84509. var bounds = this._points.computeBounds();
  84510. this._points.elements.forEach(function (p) {
  84511. normals.push(0, 1.0, 0);
  84512. positions.push(p.x, 0, p.y);
  84513. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  84514. });
  84515. var indices = new Array();
  84516. var res = earcut(this._epoints, this._eholes, 2);
  84517. for (var i = 0; i < res.length; i++) {
  84518. indices.push(res[i]);
  84519. }
  84520. if (depth > 0) {
  84521. var positionscount = (positions.length / 3); //get the current pointcount
  84522. this._points.elements.forEach(function (p) {
  84523. normals.push(0, -1.0, 0);
  84524. positions.push(p.x, -depth, p.y);
  84525. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  84526. });
  84527. var totalCount = indices.length;
  84528. for (var i = 0; i < totalCount; i += 3) {
  84529. var i0 = indices[i + 0];
  84530. var i1 = indices[i + 1];
  84531. var i2 = indices[i + 2];
  84532. indices.push(i2 + positionscount);
  84533. indices.push(i1 + positionscount);
  84534. indices.push(i0 + positionscount);
  84535. }
  84536. //Add the sides
  84537. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  84538. this._holes.forEach(function (hole) {
  84539. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  84540. });
  84541. }
  84542. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  84543. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  84544. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  84545. result.setIndices(indices);
  84546. return result;
  84547. };
  84548. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  84549. var StartIndex = positions.length / 3;
  84550. var ulength = 0;
  84551. for (var i = 0; i < points.elements.length; i++) {
  84552. var p = points.elements[i];
  84553. var p1;
  84554. if ((i + 1) > points.elements.length - 1) {
  84555. p1 = points.elements[0];
  84556. }
  84557. else {
  84558. p1 = points.elements[i + 1];
  84559. }
  84560. positions.push(p.x, 0, p.y);
  84561. positions.push(p.x, -depth, p.y);
  84562. positions.push(p1.x, 0, p1.y);
  84563. positions.push(p1.x, -depth, p1.y);
  84564. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  84565. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  84566. var v3 = v2.subtract(v1);
  84567. var v4 = new BABYLON.Vector3(0, 1, 0);
  84568. var vn = BABYLON.Vector3.Cross(v3, v4);
  84569. vn = vn.normalize();
  84570. uvs.push(ulength / bounds.width, 0);
  84571. uvs.push(ulength / bounds.width, 1);
  84572. ulength += v3.length();
  84573. uvs.push((ulength / bounds.width), 0);
  84574. uvs.push((ulength / bounds.width), 1);
  84575. if (!flip) {
  84576. normals.push(-vn.x, -vn.y, -vn.z);
  84577. normals.push(-vn.x, -vn.y, -vn.z);
  84578. normals.push(-vn.x, -vn.y, -vn.z);
  84579. normals.push(-vn.x, -vn.y, -vn.z);
  84580. indices.push(StartIndex);
  84581. indices.push(StartIndex + 1);
  84582. indices.push(StartIndex + 2);
  84583. indices.push(StartIndex + 1);
  84584. indices.push(StartIndex + 3);
  84585. indices.push(StartIndex + 2);
  84586. }
  84587. else {
  84588. normals.push(vn.x, vn.y, vn.z);
  84589. normals.push(vn.x, vn.y, vn.z);
  84590. normals.push(vn.x, vn.y, vn.z);
  84591. normals.push(vn.x, vn.y, vn.z);
  84592. indices.push(StartIndex);
  84593. indices.push(StartIndex + 2);
  84594. indices.push(StartIndex + 1);
  84595. indices.push(StartIndex + 1);
  84596. indices.push(StartIndex + 2);
  84597. indices.push(StartIndex + 3);
  84598. }
  84599. StartIndex += 4;
  84600. }
  84601. ;
  84602. };
  84603. return PolygonMeshBuilder;
  84604. }());
  84605. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  84606. })(BABYLON || (BABYLON = {}));
  84607. //# sourceMappingURL=babylon.polygonMesh.js.map
  84608. var BABYLON;
  84609. (function (BABYLON) {
  84610. // Unique ID when we import meshes from Babylon to CSG
  84611. var currentCSGMeshId = 0;
  84612. // # class Vertex
  84613. // Represents a vertex of a polygon. Use your own vertex class instead of this
  84614. // one to provide additional features like texture coordinates and vertex
  84615. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  84616. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  84617. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  84618. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  84619. // is not used anywhere else.
  84620. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  84621. var Vertex = /** @class */ (function () {
  84622. function Vertex(pos, normal, uv) {
  84623. this.pos = pos;
  84624. this.normal = normal;
  84625. this.uv = uv;
  84626. }
  84627. Vertex.prototype.clone = function () {
  84628. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  84629. };
  84630. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  84631. // orientation of a polygon is flipped.
  84632. Vertex.prototype.flip = function () {
  84633. this.normal = this.normal.scale(-1);
  84634. };
  84635. // Create a new vertex between this vertex and `other` by linearly
  84636. // interpolating all properties using a parameter of `t`. Subclasses should
  84637. // override this to interpolate additional properties.
  84638. Vertex.prototype.interpolate = function (other, t) {
  84639. 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));
  84640. };
  84641. return Vertex;
  84642. }());
  84643. // # class Plane
  84644. // Represents a plane in 3D space.
  84645. var Plane = /** @class */ (function () {
  84646. function Plane(normal, w) {
  84647. this.normal = normal;
  84648. this.w = w;
  84649. }
  84650. Plane.FromPoints = function (a, b, c) {
  84651. var v0 = c.subtract(a);
  84652. var v1 = b.subtract(a);
  84653. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  84654. return null;
  84655. }
  84656. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  84657. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  84658. };
  84659. Plane.prototype.clone = function () {
  84660. return new Plane(this.normal.clone(), this.w);
  84661. };
  84662. Plane.prototype.flip = function () {
  84663. this.normal.scaleInPlace(-1);
  84664. this.w = -this.w;
  84665. };
  84666. // Split `polygon` by this plane if needed, then put the polygon or polygon
  84667. // fragments in the appropriate lists. Coplanar polygons go into either
  84668. // `coplanarFront` or `coplanarBack` depending on their orientation with
  84669. // respect to this plane. Polygons in front or in back of this plane go into
  84670. // either `front` or `back`.
  84671. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  84672. var COPLANAR = 0;
  84673. var FRONT = 1;
  84674. var BACK = 2;
  84675. var SPANNING = 3;
  84676. // Classify each point as well as the entire polygon into one of the above
  84677. // four classes.
  84678. var polygonType = 0;
  84679. var types = [];
  84680. var i;
  84681. var t;
  84682. for (i = 0; i < polygon.vertices.length; i++) {
  84683. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  84684. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  84685. polygonType |= type;
  84686. types.push(type);
  84687. }
  84688. // Put the polygon in the correct list, splitting it when necessary.
  84689. switch (polygonType) {
  84690. case COPLANAR:
  84691. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  84692. break;
  84693. case FRONT:
  84694. front.push(polygon);
  84695. break;
  84696. case BACK:
  84697. back.push(polygon);
  84698. break;
  84699. case SPANNING:
  84700. var f = [], b = [];
  84701. for (i = 0; i < polygon.vertices.length; i++) {
  84702. var j = (i + 1) % polygon.vertices.length;
  84703. var ti = types[i], tj = types[j];
  84704. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  84705. if (ti !== BACK)
  84706. f.push(vi);
  84707. if (ti !== FRONT)
  84708. b.push(ti !== BACK ? vi.clone() : vi);
  84709. if ((ti | tj) === SPANNING) {
  84710. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  84711. var v = vi.interpolate(vj, t);
  84712. f.push(v);
  84713. b.push(v.clone());
  84714. }
  84715. }
  84716. var poly;
  84717. if (f.length >= 3) {
  84718. poly = new Polygon(f, polygon.shared);
  84719. if (poly.plane)
  84720. front.push(poly);
  84721. }
  84722. if (b.length >= 3) {
  84723. poly = new Polygon(b, polygon.shared);
  84724. if (poly.plane)
  84725. back.push(poly);
  84726. }
  84727. break;
  84728. }
  84729. };
  84730. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  84731. // point is on the plane.
  84732. Plane.EPSILON = 1e-5;
  84733. return Plane;
  84734. }());
  84735. // # class Polygon
  84736. // Represents a convex polygon. The vertices used to initialize a polygon must
  84737. // be coplanar and form a convex loop.
  84738. //
  84739. // Each convex polygon has a `shared` property, which is shared between all
  84740. // polygons that are clones of each other or were split from the same polygon.
  84741. // This can be used to define per-polygon properties (such as surface color).
  84742. var Polygon = /** @class */ (function () {
  84743. function Polygon(vertices, shared) {
  84744. this.vertices = vertices;
  84745. this.shared = shared;
  84746. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  84747. }
  84748. Polygon.prototype.clone = function () {
  84749. var vertices = this.vertices.map(function (v) { return v.clone(); });
  84750. return new Polygon(vertices, this.shared);
  84751. };
  84752. Polygon.prototype.flip = function () {
  84753. this.vertices.reverse().map(function (v) { v.flip(); });
  84754. this.plane.flip();
  84755. };
  84756. return Polygon;
  84757. }());
  84758. // # class Node
  84759. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  84760. // by picking a polygon to split along. That polygon (and all other coplanar
  84761. // polygons) are added directly to that node and the other polygons are added to
  84762. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  84763. // no distinction between internal and leaf nodes.
  84764. var Node = /** @class */ (function () {
  84765. function Node(polygons) {
  84766. this.plane = null;
  84767. this.front = null;
  84768. this.back = null;
  84769. this.polygons = new Array();
  84770. if (polygons) {
  84771. this.build(polygons);
  84772. }
  84773. }
  84774. Node.prototype.clone = function () {
  84775. var node = new Node();
  84776. node.plane = this.plane && this.plane.clone();
  84777. node.front = this.front && this.front.clone();
  84778. node.back = this.back && this.back.clone();
  84779. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  84780. return node;
  84781. };
  84782. // Convert solid space to empty space and empty space to solid space.
  84783. Node.prototype.invert = function () {
  84784. for (var i = 0; i < this.polygons.length; i++) {
  84785. this.polygons[i].flip();
  84786. }
  84787. if (this.plane) {
  84788. this.plane.flip();
  84789. }
  84790. if (this.front) {
  84791. this.front.invert();
  84792. }
  84793. if (this.back) {
  84794. this.back.invert();
  84795. }
  84796. var temp = this.front;
  84797. this.front = this.back;
  84798. this.back = temp;
  84799. };
  84800. // Recursively remove all polygons in `polygons` that are inside this BSP
  84801. // tree.
  84802. Node.prototype.clipPolygons = function (polygons) {
  84803. if (!this.plane)
  84804. return polygons.slice();
  84805. var front = new Array(), back = new Array();
  84806. for (var i = 0; i < polygons.length; i++) {
  84807. this.plane.splitPolygon(polygons[i], front, back, front, back);
  84808. }
  84809. if (this.front) {
  84810. front = this.front.clipPolygons(front);
  84811. }
  84812. if (this.back) {
  84813. back = this.back.clipPolygons(back);
  84814. }
  84815. else {
  84816. back = [];
  84817. }
  84818. return front.concat(back);
  84819. };
  84820. // Remove all polygons in this BSP tree that are inside the other BSP tree
  84821. // `bsp`.
  84822. Node.prototype.clipTo = function (bsp) {
  84823. this.polygons = bsp.clipPolygons(this.polygons);
  84824. if (this.front)
  84825. this.front.clipTo(bsp);
  84826. if (this.back)
  84827. this.back.clipTo(bsp);
  84828. };
  84829. // Return a list of all polygons in this BSP tree.
  84830. Node.prototype.allPolygons = function () {
  84831. var polygons = this.polygons.slice();
  84832. if (this.front)
  84833. polygons = polygons.concat(this.front.allPolygons());
  84834. if (this.back)
  84835. polygons = polygons.concat(this.back.allPolygons());
  84836. return polygons;
  84837. };
  84838. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  84839. // new polygons are filtered down to the bottom of the tree and become new
  84840. // nodes there. Each set of polygons is partitioned using the first polygon
  84841. // (no heuristic is used to pick a good split).
  84842. Node.prototype.build = function (polygons) {
  84843. if (!polygons.length)
  84844. return;
  84845. if (!this.plane)
  84846. this.plane = polygons[0].plane.clone();
  84847. var front = new Array(), back = new Array();
  84848. for (var i = 0; i < polygons.length; i++) {
  84849. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  84850. }
  84851. if (front.length) {
  84852. if (!this.front)
  84853. this.front = new Node();
  84854. this.front.build(front);
  84855. }
  84856. if (back.length) {
  84857. if (!this.back)
  84858. this.back = new Node();
  84859. this.back.build(back);
  84860. }
  84861. };
  84862. return Node;
  84863. }());
  84864. var CSG = /** @class */ (function () {
  84865. function CSG() {
  84866. this.polygons = new Array();
  84867. }
  84868. // Convert BABYLON.Mesh to BABYLON.CSG
  84869. CSG.FromMesh = function (mesh) {
  84870. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  84871. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  84872. if (mesh instanceof BABYLON.Mesh) {
  84873. mesh.computeWorldMatrix(true);
  84874. matrix = mesh.getWorldMatrix();
  84875. meshPosition = mesh.position.clone();
  84876. meshRotation = mesh.rotation.clone();
  84877. if (mesh.rotationQuaternion) {
  84878. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  84879. }
  84880. meshScaling = mesh.scaling.clone();
  84881. }
  84882. else {
  84883. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  84884. }
  84885. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84886. var subMeshes = mesh.subMeshes;
  84887. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  84888. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  84889. vertices = [];
  84890. for (var j = 0; j < 3; j++) {
  84891. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  84892. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  84893. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  84894. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  84895. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  84896. vertex = new Vertex(position, normal, uv);
  84897. vertices.push(vertex);
  84898. }
  84899. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  84900. // To handle the case of degenerated triangle
  84901. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  84902. if (polygon.plane)
  84903. polygons.push(polygon);
  84904. }
  84905. }
  84906. var csg = CSG.FromPolygons(polygons);
  84907. csg.matrix = matrix;
  84908. csg.position = meshPosition;
  84909. csg.rotation = meshRotation;
  84910. csg.scaling = meshScaling;
  84911. csg.rotationQuaternion = meshRotationQuaternion;
  84912. currentCSGMeshId++;
  84913. return csg;
  84914. };
  84915. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  84916. CSG.FromPolygons = function (polygons) {
  84917. var csg = new CSG();
  84918. csg.polygons = polygons;
  84919. return csg;
  84920. };
  84921. CSG.prototype.clone = function () {
  84922. var csg = new CSG();
  84923. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  84924. csg.copyTransformAttributes(this);
  84925. return csg;
  84926. };
  84927. CSG.prototype.union = function (csg) {
  84928. var a = new Node(this.clone().polygons);
  84929. var b = new Node(csg.clone().polygons);
  84930. a.clipTo(b);
  84931. b.clipTo(a);
  84932. b.invert();
  84933. b.clipTo(a);
  84934. b.invert();
  84935. a.build(b.allPolygons());
  84936. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84937. };
  84938. CSG.prototype.unionInPlace = function (csg) {
  84939. var a = new Node(this.polygons);
  84940. var b = new Node(csg.polygons);
  84941. a.clipTo(b);
  84942. b.clipTo(a);
  84943. b.invert();
  84944. b.clipTo(a);
  84945. b.invert();
  84946. a.build(b.allPolygons());
  84947. this.polygons = a.allPolygons();
  84948. };
  84949. CSG.prototype.subtract = function (csg) {
  84950. var a = new Node(this.clone().polygons);
  84951. var b = new Node(csg.clone().polygons);
  84952. a.invert();
  84953. a.clipTo(b);
  84954. b.clipTo(a);
  84955. b.invert();
  84956. b.clipTo(a);
  84957. b.invert();
  84958. a.build(b.allPolygons());
  84959. a.invert();
  84960. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84961. };
  84962. CSG.prototype.subtractInPlace = function (csg) {
  84963. var a = new Node(this.polygons);
  84964. var b = new Node(csg.polygons);
  84965. a.invert();
  84966. a.clipTo(b);
  84967. b.clipTo(a);
  84968. b.invert();
  84969. b.clipTo(a);
  84970. b.invert();
  84971. a.build(b.allPolygons());
  84972. a.invert();
  84973. this.polygons = a.allPolygons();
  84974. };
  84975. CSG.prototype.intersect = function (csg) {
  84976. var a = new Node(this.clone().polygons);
  84977. var b = new Node(csg.clone().polygons);
  84978. a.invert();
  84979. b.clipTo(a);
  84980. b.invert();
  84981. a.clipTo(b);
  84982. b.clipTo(a);
  84983. a.build(b.allPolygons());
  84984. a.invert();
  84985. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84986. };
  84987. CSG.prototype.intersectInPlace = function (csg) {
  84988. var a = new Node(this.polygons);
  84989. var b = new Node(csg.polygons);
  84990. a.invert();
  84991. b.clipTo(a);
  84992. b.invert();
  84993. a.clipTo(b);
  84994. b.clipTo(a);
  84995. a.build(b.allPolygons());
  84996. a.invert();
  84997. this.polygons = a.allPolygons();
  84998. };
  84999. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  85000. // not modified.
  85001. CSG.prototype.inverse = function () {
  85002. var csg = this.clone();
  85003. csg.inverseInPlace();
  85004. return csg;
  85005. };
  85006. CSG.prototype.inverseInPlace = function () {
  85007. this.polygons.map(function (p) { p.flip(); });
  85008. };
  85009. // This is used to keep meshes transformations so they can be restored
  85010. // when we build back a Babylon Mesh
  85011. // NB : All CSG operations are performed in world coordinates
  85012. CSG.prototype.copyTransformAttributes = function (csg) {
  85013. this.matrix = csg.matrix;
  85014. this.position = csg.position;
  85015. this.rotation = csg.rotation;
  85016. this.scaling = csg.scaling;
  85017. this.rotationQuaternion = csg.rotationQuaternion;
  85018. return this;
  85019. };
  85020. // Build Raw mesh from CSG
  85021. // Coordinates here are in world space
  85022. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  85023. var matrix = this.matrix.clone();
  85024. matrix.invert();
  85025. 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;
  85026. if (keepSubMeshes) {
  85027. // Sort Polygons, since subMeshes are indices range
  85028. polygons.sort(function (a, b) {
  85029. if (a.shared.meshId === b.shared.meshId) {
  85030. return a.shared.subMeshId - b.shared.subMeshId;
  85031. }
  85032. else {
  85033. return a.shared.meshId - b.shared.meshId;
  85034. }
  85035. });
  85036. }
  85037. for (var i = 0, il = polygons.length; i < il; i++) {
  85038. polygon = polygons[i];
  85039. // Building SubMeshes
  85040. if (!subMesh_dict[polygon.shared.meshId]) {
  85041. subMesh_dict[polygon.shared.meshId] = {};
  85042. }
  85043. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  85044. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  85045. indexStart: +Infinity,
  85046. indexEnd: -Infinity,
  85047. materialIndex: polygon.shared.materialIndex
  85048. };
  85049. }
  85050. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  85051. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  85052. polygonIndices[0] = 0;
  85053. polygonIndices[1] = j - 1;
  85054. polygonIndices[2] = j;
  85055. for (var k = 0; k < 3; k++) {
  85056. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  85057. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  85058. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  85059. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  85060. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  85061. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  85062. // Check if 2 points can be merged
  85063. if (!(typeof vertex_idx !== 'undefined' &&
  85064. normals[vertex_idx * 3] === localNormal.x &&
  85065. normals[vertex_idx * 3 + 1] === localNormal.y &&
  85066. normals[vertex_idx * 3 + 2] === localNormal.z &&
  85067. uvs[vertex_idx * 2] === uv.x &&
  85068. uvs[vertex_idx * 2 + 1] === uv.y)) {
  85069. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  85070. uvs.push(uv.x, uv.y);
  85071. normals.push(normal.x, normal.y, normal.z);
  85072. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  85073. }
  85074. indices.push(vertex_idx);
  85075. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  85076. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  85077. currentIndex++;
  85078. }
  85079. }
  85080. }
  85081. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  85082. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  85083. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  85084. mesh.setIndices(indices, null);
  85085. if (keepSubMeshes) {
  85086. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  85087. var materialIndexOffset = 0, materialMaxIndex;
  85088. mesh.subMeshes = new Array();
  85089. for (var m in subMesh_dict) {
  85090. materialMaxIndex = -1;
  85091. for (var sm in subMesh_dict[m]) {
  85092. subMesh_obj = subMesh_dict[m][sm];
  85093. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  85094. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  85095. }
  85096. materialIndexOffset += ++materialMaxIndex;
  85097. }
  85098. }
  85099. return mesh;
  85100. };
  85101. // Build Mesh from CSG taking material and transforms into account
  85102. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  85103. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  85104. mesh.material = material;
  85105. mesh.position.copyFrom(this.position);
  85106. mesh.rotation.copyFrom(this.rotation);
  85107. if (this.rotationQuaternion) {
  85108. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  85109. }
  85110. mesh.scaling.copyFrom(this.scaling);
  85111. mesh.computeWorldMatrix(true);
  85112. return mesh;
  85113. };
  85114. return CSG;
  85115. }());
  85116. BABYLON.CSG = CSG;
  85117. })(BABYLON || (BABYLON = {}));
  85118. //# sourceMappingURL=babylon.csg.js.map
  85119. var BABYLON;
  85120. (function (BABYLON) {
  85121. var LensFlare = /** @class */ (function () {
  85122. function LensFlare(size, position, color, imgUrl, system) {
  85123. this.size = size;
  85124. this.position = position;
  85125. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  85126. this.color = color || new BABYLON.Color3(1, 1, 1);
  85127. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  85128. this._system = system;
  85129. system.lensFlares.push(this);
  85130. }
  85131. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  85132. return new LensFlare(size, position, color, imgUrl, system);
  85133. };
  85134. LensFlare.prototype.dispose = function () {
  85135. if (this.texture) {
  85136. this.texture.dispose();
  85137. }
  85138. // Remove from scene
  85139. var index = this._system.lensFlares.indexOf(this);
  85140. this._system.lensFlares.splice(index, 1);
  85141. };
  85142. ;
  85143. return LensFlare;
  85144. }());
  85145. BABYLON.LensFlare = LensFlare;
  85146. })(BABYLON || (BABYLON = {}));
  85147. //# sourceMappingURL=babylon.lensFlare.js.map
  85148. var BABYLON;
  85149. (function (BABYLON) {
  85150. // Adds the parser to the scene parsers.
  85151. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  85152. // Lens flares
  85153. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  85154. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  85155. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  85156. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  85157. container.lensFlareSystems.push(lf);
  85158. }
  85159. }
  85160. });
  85161. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  85162. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  85163. if (this.lensFlareSystems[index].name === name) {
  85164. return this.lensFlareSystems[index];
  85165. }
  85166. }
  85167. return null;
  85168. };
  85169. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  85170. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  85171. if (this.lensFlareSystems[index].id === id) {
  85172. return this.lensFlareSystems[index];
  85173. }
  85174. }
  85175. return null;
  85176. };
  85177. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  85178. var index = this.lensFlareSystems.indexOf(toRemove);
  85179. if (index !== -1) {
  85180. this.lensFlareSystems.splice(index, 1);
  85181. }
  85182. return index;
  85183. };
  85184. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  85185. this.lensFlareSystems.push(newLensFlareSystem);
  85186. };
  85187. /**
  85188. * Defines the lens flare scene component responsible to manage any lens flares
  85189. * in a given scene.
  85190. */
  85191. var LensFlareSystemSceneComponent = /** @class */ (function () {
  85192. /**
  85193. * Creates a new instance of the component for the given scene
  85194. * @param scene Defines the scene to register the component in
  85195. */
  85196. function LensFlareSystemSceneComponent(scene) {
  85197. /**
  85198. * The component name helpfull to identify the component in the list of scene components.
  85199. */
  85200. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  85201. this.scene = scene;
  85202. scene.lensFlareSystems = new Array();
  85203. }
  85204. /**
  85205. * Registers the component in a given scene
  85206. */
  85207. LensFlareSystemSceneComponent.prototype.register = function () {
  85208. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  85209. };
  85210. /**
  85211. * Rebuilds the elements related to this component in case of
  85212. * context lost for instance.
  85213. */
  85214. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  85215. // Nothing to do for lens flare
  85216. };
  85217. /**
  85218. * Adds all the element from the container to the scene
  85219. * @param container the container holding the elements
  85220. */
  85221. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  85222. var _this = this;
  85223. if (!container.lensFlareSystems) {
  85224. return;
  85225. }
  85226. container.lensFlareSystems.forEach(function (o) {
  85227. _this.scene.addLensFlareSystem(o);
  85228. });
  85229. };
  85230. /**
  85231. * Removes all the elements in the container from the scene
  85232. * @param container contains the elements to remove
  85233. */
  85234. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  85235. var _this = this;
  85236. if (!container.lensFlareSystems) {
  85237. return;
  85238. }
  85239. container.lensFlareSystems.forEach(function (o) {
  85240. _this.scene.removeLensFlareSystem(o);
  85241. });
  85242. };
  85243. /**
  85244. * Serializes the component data to the specified json object
  85245. * @param serializationObject The object to serialize to
  85246. */
  85247. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  85248. // Lens flares
  85249. serializationObject.lensFlareSystems = [];
  85250. var lensFlareSystems = this.scene.lensFlareSystems;
  85251. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  85252. var lensFlareSystem = lensFlareSystems_1[_i];
  85253. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  85254. }
  85255. };
  85256. /**
  85257. * Disposes the component and the associated ressources.
  85258. */
  85259. LensFlareSystemSceneComponent.prototype.dispose = function () {
  85260. var lensFlareSystems = this.scene.lensFlareSystems;
  85261. while (lensFlareSystems.length) {
  85262. lensFlareSystems[0].dispose();
  85263. }
  85264. };
  85265. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  85266. // Lens flares
  85267. if (this.scene.lensFlaresEnabled) {
  85268. var lensFlareSystems = this.scene.lensFlareSystems;
  85269. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  85270. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  85271. var lensFlareSystem = lensFlareSystems_2[_i];
  85272. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  85273. lensFlareSystem.render();
  85274. }
  85275. }
  85276. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  85277. }
  85278. };
  85279. return LensFlareSystemSceneComponent;
  85280. }());
  85281. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  85282. })(BABYLON || (BABYLON = {}));
  85283. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  85284. var BABYLON;
  85285. (function (BABYLON) {
  85286. var LensFlareSystem = /** @class */ (function () {
  85287. function LensFlareSystem(name, emitter, scene) {
  85288. this.name = name;
  85289. this.lensFlares = new Array();
  85290. this.borderLimit = 300;
  85291. this.viewportBorder = 0;
  85292. this.layerMask = 0x0FFFFFFF;
  85293. this._vertexBuffers = {};
  85294. this._isEnabled = true;
  85295. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85296. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  85297. if (!component) {
  85298. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  85299. scene._addComponent(component);
  85300. }
  85301. this._emitter = emitter;
  85302. this.id = name;
  85303. scene.lensFlareSystems.push(this);
  85304. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  85305. var engine = scene.getEngine();
  85306. // VBO
  85307. var vertices = [];
  85308. vertices.push(1, 1);
  85309. vertices.push(-1, 1);
  85310. vertices.push(-1, -1);
  85311. vertices.push(1, -1);
  85312. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85313. // Indices
  85314. var indices = [];
  85315. indices.push(0);
  85316. indices.push(1);
  85317. indices.push(2);
  85318. indices.push(0);
  85319. indices.push(2);
  85320. indices.push(3);
  85321. this._indexBuffer = engine.createIndexBuffer(indices);
  85322. // Effects
  85323. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  85324. }
  85325. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  85326. get: function () {
  85327. return this._isEnabled;
  85328. },
  85329. set: function (value) {
  85330. this._isEnabled = value;
  85331. },
  85332. enumerable: true,
  85333. configurable: true
  85334. });
  85335. LensFlareSystem.prototype.getScene = function () {
  85336. return this._scene;
  85337. };
  85338. LensFlareSystem.prototype.getEmitter = function () {
  85339. return this._emitter;
  85340. };
  85341. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  85342. this._emitter = newEmitter;
  85343. };
  85344. LensFlareSystem.prototype.getEmitterPosition = function () {
  85345. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  85346. };
  85347. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  85348. var position = this.getEmitterPosition();
  85349. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  85350. this._positionX = position.x;
  85351. this._positionY = position.y;
  85352. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  85353. if (this.viewportBorder > 0) {
  85354. globalViewport.x -= this.viewportBorder;
  85355. globalViewport.y -= this.viewportBorder;
  85356. globalViewport.width += this.viewportBorder * 2;
  85357. globalViewport.height += this.viewportBorder * 2;
  85358. position.x += this.viewportBorder;
  85359. position.y += this.viewportBorder;
  85360. this._positionX += this.viewportBorder;
  85361. this._positionY += this.viewportBorder;
  85362. }
  85363. if (position.z > 0) {
  85364. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  85365. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  85366. return true;
  85367. }
  85368. return true;
  85369. }
  85370. return false;
  85371. };
  85372. LensFlareSystem.prototype._isVisible = function () {
  85373. if (!this._isEnabled || !this._scene.activeCamera) {
  85374. return false;
  85375. }
  85376. var emitterPosition = this.getEmitterPosition();
  85377. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  85378. var distance = direction.length();
  85379. direction.normalize();
  85380. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  85381. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  85382. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  85383. };
  85384. LensFlareSystem.prototype.render = function () {
  85385. if (!this._effect.isReady() || !this._scene.activeCamera)
  85386. return false;
  85387. var engine = this._scene.getEngine();
  85388. var viewport = this._scene.activeCamera.viewport;
  85389. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  85390. // Position
  85391. if (!this.computeEffectivePosition(globalViewport)) {
  85392. return false;
  85393. }
  85394. // Visibility
  85395. if (!this._isVisible()) {
  85396. return false;
  85397. }
  85398. // Intensity
  85399. var awayX;
  85400. var awayY;
  85401. if (this._positionX < this.borderLimit + globalViewport.x) {
  85402. awayX = this.borderLimit + globalViewport.x - this._positionX;
  85403. }
  85404. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  85405. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  85406. }
  85407. else {
  85408. awayX = 0;
  85409. }
  85410. if (this._positionY < this.borderLimit + globalViewport.y) {
  85411. awayY = this.borderLimit + globalViewport.y - this._positionY;
  85412. }
  85413. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  85414. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  85415. }
  85416. else {
  85417. awayY = 0;
  85418. }
  85419. var away = (awayX > awayY) ? awayX : awayY;
  85420. away -= this.viewportBorder;
  85421. if (away > this.borderLimit) {
  85422. away = this.borderLimit;
  85423. }
  85424. var intensity = 1.0 - (away / this.borderLimit);
  85425. if (intensity < 0) {
  85426. return false;
  85427. }
  85428. if (intensity > 1.0) {
  85429. intensity = 1.0;
  85430. }
  85431. if (this.viewportBorder > 0) {
  85432. globalViewport.x += this.viewportBorder;
  85433. globalViewport.y += this.viewportBorder;
  85434. globalViewport.width -= this.viewportBorder * 2;
  85435. globalViewport.height -= this.viewportBorder * 2;
  85436. this._positionX -= this.viewportBorder;
  85437. this._positionY -= this.viewportBorder;
  85438. }
  85439. // Position
  85440. var centerX = globalViewport.x + globalViewport.width / 2;
  85441. var centerY = globalViewport.y + globalViewport.height / 2;
  85442. var distX = centerX - this._positionX;
  85443. var distY = centerY - this._positionY;
  85444. // Effects
  85445. engine.enableEffect(this._effect);
  85446. engine.setState(false);
  85447. engine.setDepthBuffer(false);
  85448. // VBOs
  85449. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  85450. // Flares
  85451. for (var index = 0; index < this.lensFlares.length; index++) {
  85452. var flare = this.lensFlares[index];
  85453. engine.setAlphaMode(flare.alphaMode);
  85454. var x = centerX - (distX * flare.position);
  85455. var y = centerY - (distY * flare.position);
  85456. var cw = flare.size;
  85457. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  85458. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  85459. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  85460. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  85461. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  85462. // Texture
  85463. this._effect.setTexture("textureSampler", flare.texture);
  85464. // Color
  85465. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  85466. // Draw order
  85467. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85468. }
  85469. engine.setDepthBuffer(true);
  85470. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85471. return true;
  85472. };
  85473. LensFlareSystem.prototype.dispose = function () {
  85474. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85475. if (vertexBuffer) {
  85476. vertexBuffer.dispose();
  85477. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85478. }
  85479. if (this._indexBuffer) {
  85480. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85481. this._indexBuffer = null;
  85482. }
  85483. while (this.lensFlares.length) {
  85484. this.lensFlares[0].dispose();
  85485. }
  85486. // Remove from scene
  85487. var index = this._scene.lensFlareSystems.indexOf(this);
  85488. this._scene.lensFlareSystems.splice(index, 1);
  85489. };
  85490. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  85491. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  85492. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  85493. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  85494. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  85495. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  85496. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  85497. var parsedFlare = parsedLensFlareSystem.flares[index];
  85498. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  85499. }
  85500. return lensFlareSystem;
  85501. };
  85502. LensFlareSystem.prototype.serialize = function () {
  85503. var serializationObject = {};
  85504. serializationObject.id = this.id;
  85505. serializationObject.name = this.name;
  85506. serializationObject.emitterId = this.getEmitter().id;
  85507. serializationObject.borderLimit = this.borderLimit;
  85508. serializationObject.flares = [];
  85509. for (var index = 0; index < this.lensFlares.length; index++) {
  85510. var flare = this.lensFlares[index];
  85511. serializationObject.flares.push({
  85512. size: flare.size,
  85513. position: flare.position,
  85514. color: flare.color.asArray(),
  85515. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  85516. });
  85517. }
  85518. return serializationObject;
  85519. };
  85520. return LensFlareSystem;
  85521. }());
  85522. BABYLON.LensFlareSystem = LensFlareSystem;
  85523. })(BABYLON || (BABYLON = {}));
  85524. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  85525. var BABYLON;
  85526. (function (BABYLON) {
  85527. /**
  85528. * This is a holder class for the physics joint created by the physics plugin.
  85529. * It holds a set of functions to control the underlying joint.
  85530. */
  85531. var PhysicsJoint = /** @class */ (function () {
  85532. function PhysicsJoint(type, jointData) {
  85533. this.type = type;
  85534. this.jointData = jointData;
  85535. jointData.nativeParams = jointData.nativeParams || {};
  85536. }
  85537. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  85538. get: function () {
  85539. return this._physicsJoint;
  85540. },
  85541. set: function (newJoint) {
  85542. if (this._physicsJoint) {
  85543. //remove from the wolrd
  85544. }
  85545. this._physicsJoint = newJoint;
  85546. },
  85547. enumerable: true,
  85548. configurable: true
  85549. });
  85550. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  85551. set: function (physicsPlugin) {
  85552. this._physicsPlugin = physicsPlugin;
  85553. },
  85554. enumerable: true,
  85555. configurable: true
  85556. });
  85557. /**
  85558. * Execute a function that is physics-plugin specific.
  85559. * @param {Function} func the function that will be executed.
  85560. * It accepts two parameters: the physics world and the physics joint.
  85561. */
  85562. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  85563. func(this._physicsPlugin.world, this._physicsJoint);
  85564. };
  85565. //TODO check if the native joints are the same
  85566. //Joint Types
  85567. PhysicsJoint.DistanceJoint = 0;
  85568. PhysicsJoint.HingeJoint = 1;
  85569. PhysicsJoint.BallAndSocketJoint = 2;
  85570. PhysicsJoint.WheelJoint = 3;
  85571. PhysicsJoint.SliderJoint = 4;
  85572. //OIMO
  85573. PhysicsJoint.PrismaticJoint = 5;
  85574. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  85575. PhysicsJoint.UniversalJoint = 6;
  85576. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  85577. //Cannon
  85578. //Similar to a Ball-Joint. Different in params
  85579. PhysicsJoint.PointToPointJoint = 8;
  85580. //Cannon only at the moment
  85581. PhysicsJoint.SpringJoint = 9;
  85582. PhysicsJoint.LockJoint = 10;
  85583. return PhysicsJoint;
  85584. }());
  85585. BABYLON.PhysicsJoint = PhysicsJoint;
  85586. /**
  85587. * A class representing a physics distance joint.
  85588. */
  85589. var DistanceJoint = /** @class */ (function (_super) {
  85590. __extends(DistanceJoint, _super);
  85591. function DistanceJoint(jointData) {
  85592. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  85593. }
  85594. /**
  85595. * Update the predefined distance.
  85596. */
  85597. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  85598. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  85599. };
  85600. return DistanceJoint;
  85601. }(PhysicsJoint));
  85602. BABYLON.DistanceJoint = DistanceJoint;
  85603. var MotorEnabledJoint = /** @class */ (function (_super) {
  85604. __extends(MotorEnabledJoint, _super);
  85605. function MotorEnabledJoint(type, jointData) {
  85606. return _super.call(this, type, jointData) || this;
  85607. }
  85608. /**
  85609. * Set the motor values.
  85610. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85611. * @param {number} force the force to apply
  85612. * @param {number} maxForce max force for this motor.
  85613. */
  85614. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  85615. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  85616. };
  85617. /**
  85618. * Set the motor's limits.
  85619. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85620. */
  85621. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  85622. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  85623. };
  85624. return MotorEnabledJoint;
  85625. }(PhysicsJoint));
  85626. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  85627. /**
  85628. * This class represents a single hinge physics joint
  85629. */
  85630. var HingeJoint = /** @class */ (function (_super) {
  85631. __extends(HingeJoint, _super);
  85632. function HingeJoint(jointData) {
  85633. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  85634. }
  85635. /**
  85636. * Set the motor values.
  85637. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85638. * @param {number} force the force to apply
  85639. * @param {number} maxForce max force for this motor.
  85640. */
  85641. HingeJoint.prototype.setMotor = function (force, maxForce) {
  85642. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  85643. };
  85644. /**
  85645. * Set the motor's limits.
  85646. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85647. */
  85648. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  85649. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  85650. };
  85651. return HingeJoint;
  85652. }(MotorEnabledJoint));
  85653. BABYLON.HingeJoint = HingeJoint;
  85654. /**
  85655. * This class represents a dual hinge physics joint (same as wheel joint)
  85656. */
  85657. var Hinge2Joint = /** @class */ (function (_super) {
  85658. __extends(Hinge2Joint, _super);
  85659. function Hinge2Joint(jointData) {
  85660. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  85661. }
  85662. /**
  85663. * Set the motor values.
  85664. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85665. * @param {number} force the force to apply
  85666. * @param {number} maxForce max force for this motor.
  85667. * @param {motorIndex} the motor's index, 0 or 1.
  85668. */
  85669. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  85670. if (motorIndex === void 0) { motorIndex = 0; }
  85671. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  85672. };
  85673. /**
  85674. * Set the motor limits.
  85675. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85676. * @param {number} upperLimit the upper limit
  85677. * @param {number} lowerLimit lower limit
  85678. * @param {motorIndex} the motor's index, 0 or 1.
  85679. */
  85680. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  85681. if (motorIndex === void 0) { motorIndex = 0; }
  85682. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  85683. };
  85684. return Hinge2Joint;
  85685. }(MotorEnabledJoint));
  85686. BABYLON.Hinge2Joint = Hinge2Joint;
  85687. })(BABYLON || (BABYLON = {}));
  85688. //# sourceMappingURL=babylon.physicsJoint.js.map
  85689. var BABYLON;
  85690. (function (BABYLON) {
  85691. var PhysicsImpostor = /** @class */ (function () {
  85692. function PhysicsImpostor(object, type, _options, _scene) {
  85693. if (_options === void 0) { _options = { mass: 0 }; }
  85694. var _this = this;
  85695. this.object = object;
  85696. this.type = type;
  85697. this._options = _options;
  85698. this._scene = _scene;
  85699. this._bodyUpdateRequired = false;
  85700. this._onBeforePhysicsStepCallbacks = new Array();
  85701. this._onAfterPhysicsStepCallbacks = new Array();
  85702. this._onPhysicsCollideCallbacks = [];
  85703. this._deltaPosition = BABYLON.Vector3.Zero();
  85704. this._isDisposed = false;
  85705. //temp variables for parent rotation calculations
  85706. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  85707. this._tmpQuat = new BABYLON.Quaternion();
  85708. this._tmpQuat2 = new BABYLON.Quaternion();
  85709. /**
  85710. * this function is executed by the physics engine.
  85711. */
  85712. this.beforeStep = function () {
  85713. if (!_this._physicsEngine) {
  85714. return;
  85715. }
  85716. _this.object.translate(_this._deltaPosition, -1);
  85717. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  85718. _this.object.computeWorldMatrix(false);
  85719. if (_this.object.parent && _this.object.rotationQuaternion) {
  85720. _this.getParentsRotation();
  85721. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  85722. }
  85723. else {
  85724. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  85725. }
  85726. if (!_this._options.disableBidirectionalTransformation) {
  85727. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  85728. }
  85729. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  85730. func(_this);
  85731. });
  85732. };
  85733. /**
  85734. * this function is executed by the physics engine.
  85735. */
  85736. this.afterStep = function () {
  85737. if (!_this._physicsEngine) {
  85738. return;
  85739. }
  85740. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  85741. func(_this);
  85742. });
  85743. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  85744. // object has now its world rotation. needs to be converted to local.
  85745. if (_this.object.parent && _this.object.rotationQuaternion) {
  85746. _this.getParentsRotation();
  85747. _this._tmpQuat.conjugateInPlace();
  85748. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  85749. }
  85750. // take the position set and make it the absolute position of this object.
  85751. _this.object.setAbsolutePosition(_this.object.position);
  85752. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  85753. _this.object.translate(_this._deltaPosition, 1);
  85754. };
  85755. /**
  85756. * Legacy collision detection event support
  85757. */
  85758. this.onCollideEvent = null;
  85759. //event and body object due to cannon's event-based architecture.
  85760. this.onCollide = function (e) {
  85761. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  85762. return;
  85763. }
  85764. if (!_this._physicsEngine) {
  85765. return;
  85766. }
  85767. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  85768. if (otherImpostor) {
  85769. // Legacy collision detection event support
  85770. if (_this.onCollideEvent) {
  85771. _this.onCollideEvent(_this, otherImpostor);
  85772. }
  85773. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  85774. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  85775. }).forEach(function (obj) {
  85776. obj.callback(_this, otherImpostor);
  85777. });
  85778. }
  85779. };
  85780. //sanity check!
  85781. if (!this.object) {
  85782. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  85783. return;
  85784. }
  85785. //legacy support for old syntax.
  85786. if (!this._scene && object.getScene) {
  85787. this._scene = object.getScene();
  85788. }
  85789. if (!this._scene) {
  85790. return;
  85791. }
  85792. this._physicsEngine = this._scene.getPhysicsEngine();
  85793. if (!this._physicsEngine) {
  85794. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  85795. }
  85796. else {
  85797. //set the object's quaternion, if not set
  85798. if (!this.object.rotationQuaternion) {
  85799. if (this.object.rotation) {
  85800. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  85801. }
  85802. else {
  85803. this.object.rotationQuaternion = new BABYLON.Quaternion();
  85804. }
  85805. }
  85806. //default options params
  85807. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  85808. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  85809. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  85810. this._joints = [];
  85811. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  85812. if (!this.object.parent || this._options.ignoreParent) {
  85813. this._init();
  85814. }
  85815. else if (this.object.parent.physicsImpostor) {
  85816. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  85817. }
  85818. }
  85819. }
  85820. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  85821. get: function () {
  85822. return this._isDisposed;
  85823. },
  85824. enumerable: true,
  85825. configurable: true
  85826. });
  85827. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  85828. get: function () {
  85829. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  85830. },
  85831. set: function (value) {
  85832. this.setMass(value);
  85833. },
  85834. enumerable: true,
  85835. configurable: true
  85836. });
  85837. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  85838. get: function () {
  85839. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  85840. },
  85841. set: function (value) {
  85842. if (!this._physicsEngine) {
  85843. return;
  85844. }
  85845. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  85846. },
  85847. enumerable: true,
  85848. configurable: true
  85849. });
  85850. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  85851. get: function () {
  85852. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  85853. },
  85854. set: function (value) {
  85855. if (!this._physicsEngine) {
  85856. return;
  85857. }
  85858. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  85859. },
  85860. enumerable: true,
  85861. configurable: true
  85862. });
  85863. /**
  85864. * This function will completly initialize this impostor.
  85865. * It will create a new body - but only if this mesh has no parent.
  85866. * If it has, this impostor will not be used other than to define the impostor
  85867. * of the child mesh.
  85868. */
  85869. PhysicsImpostor.prototype._init = function () {
  85870. if (!this._physicsEngine) {
  85871. return;
  85872. }
  85873. this._physicsEngine.removeImpostor(this);
  85874. this.physicsBody = null;
  85875. this._parent = this._parent || this._getPhysicsParent();
  85876. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  85877. this._physicsEngine.addImpostor(this);
  85878. }
  85879. };
  85880. PhysicsImpostor.prototype._getPhysicsParent = function () {
  85881. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  85882. var parentMesh = this.object.parent;
  85883. return parentMesh.physicsImpostor;
  85884. }
  85885. return null;
  85886. };
  85887. /**
  85888. * Should a new body be generated.
  85889. */
  85890. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  85891. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  85892. };
  85893. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  85894. this.forceUpdate();
  85895. };
  85896. /**
  85897. * Force a regeneration of this or the parent's impostor's body.
  85898. * Use under cautious - This will remove all joints already implemented.
  85899. */
  85900. PhysicsImpostor.prototype.forceUpdate = function () {
  85901. this._init();
  85902. if (this.parent && !this._options.ignoreParent) {
  85903. this.parent.forceUpdate();
  85904. }
  85905. };
  85906. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  85907. /*public get mesh(): AbstractMesh {
  85908. return this._mesh;
  85909. }*/
  85910. /**
  85911. * Gets the body that holds this impostor. Either its own, or its parent.
  85912. */
  85913. get: function () {
  85914. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  85915. },
  85916. /**
  85917. * Set the physics body. Used mainly by the physics engine/plugin
  85918. */
  85919. set: function (physicsBody) {
  85920. if (this._physicsBody && this._physicsEngine) {
  85921. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  85922. }
  85923. this._physicsBody = physicsBody;
  85924. this.resetUpdateFlags();
  85925. },
  85926. enumerable: true,
  85927. configurable: true
  85928. });
  85929. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  85930. get: function () {
  85931. return !this._options.ignoreParent && this._parent ? this._parent : null;
  85932. },
  85933. set: function (value) {
  85934. this._parent = value;
  85935. },
  85936. enumerable: true,
  85937. configurable: true
  85938. });
  85939. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  85940. this._bodyUpdateRequired = false;
  85941. };
  85942. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  85943. if (this.object.getBoundingInfo) {
  85944. var q = this.object.rotationQuaternion;
  85945. //reset rotation
  85946. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  85947. //calculate the world matrix with no rotation
  85948. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85949. var boundingInfo = this.object.getBoundingInfo();
  85950. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  85951. //bring back the rotation
  85952. this.object.rotationQuaternion = q;
  85953. //calculate the world matrix with the new rotation
  85954. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85955. return size;
  85956. }
  85957. else {
  85958. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  85959. }
  85960. };
  85961. PhysicsImpostor.prototype.getObjectCenter = function () {
  85962. if (this.object.getBoundingInfo) {
  85963. var boundingInfo = this.object.getBoundingInfo();
  85964. return boundingInfo.boundingBox.centerWorld;
  85965. }
  85966. else {
  85967. return this.object.position;
  85968. }
  85969. };
  85970. /**
  85971. * Get a specific parametes from the options parameter.
  85972. */
  85973. PhysicsImpostor.prototype.getParam = function (paramName) {
  85974. return this._options[paramName];
  85975. };
  85976. /**
  85977. * Sets a specific parameter in the options given to the physics plugin
  85978. */
  85979. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85980. this._options[paramName] = value;
  85981. this._bodyUpdateRequired = true;
  85982. };
  85983. /**
  85984. * Specifically change the body's mass option. Won't recreate the physics body object
  85985. */
  85986. PhysicsImpostor.prototype.setMass = function (mass) {
  85987. if (this.getParam("mass") !== mass) {
  85988. this.setParam("mass", mass);
  85989. }
  85990. if (this._physicsEngine) {
  85991. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85992. }
  85993. };
  85994. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85995. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85996. };
  85997. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85998. if (this._physicsEngine) {
  85999. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  86000. }
  86001. };
  86002. PhysicsImpostor.prototype.getAngularVelocity = function () {
  86003. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  86004. };
  86005. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  86006. if (this._physicsEngine) {
  86007. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  86008. }
  86009. };
  86010. /**
  86011. * Execute a function with the physics plugin native code.
  86012. * Provide a function the will have two variables - the world object and the physics body object.
  86013. */
  86014. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  86015. if (this._physicsEngine) {
  86016. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  86017. }
  86018. };
  86019. /**
  86020. * Register a function that will be executed before the physics world is stepping forward.
  86021. */
  86022. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  86023. this._onBeforePhysicsStepCallbacks.push(func);
  86024. };
  86025. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  86026. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  86027. if (index > -1) {
  86028. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  86029. }
  86030. else {
  86031. BABYLON.Tools.Warn("Function to remove was not found");
  86032. }
  86033. };
  86034. /**
  86035. * Register a function that will be executed after the physics step
  86036. */
  86037. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  86038. this._onAfterPhysicsStepCallbacks.push(func);
  86039. };
  86040. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  86041. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  86042. if (index > -1) {
  86043. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  86044. }
  86045. else {
  86046. BABYLON.Tools.Warn("Function to remove was not found");
  86047. }
  86048. };
  86049. /**
  86050. * register a function that will be executed when this impostor collides against a different body.
  86051. */
  86052. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  86053. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  86054. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  86055. };
  86056. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  86057. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  86058. var index = -1;
  86059. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  86060. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  86061. // chcek the arrays match
  86062. var sameList = cbDef.otherImpostors.every(function (impostor) {
  86063. return collidedAgainstList.indexOf(impostor) > -1;
  86064. });
  86065. if (sameList) {
  86066. index = idx;
  86067. }
  86068. return sameList;
  86069. }
  86070. return false;
  86071. });
  86072. if (found) {
  86073. this._onPhysicsCollideCallbacks.splice(index, 1);
  86074. }
  86075. else {
  86076. BABYLON.Tools.Warn("Function to remove was not found");
  86077. }
  86078. };
  86079. PhysicsImpostor.prototype.getParentsRotation = function () {
  86080. var parent = this.object.parent;
  86081. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  86082. while (parent) {
  86083. if (parent.rotationQuaternion) {
  86084. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  86085. }
  86086. else {
  86087. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  86088. }
  86089. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  86090. parent = parent.parent;
  86091. }
  86092. return this._tmpQuat;
  86093. };
  86094. /**
  86095. * Apply a force
  86096. */
  86097. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  86098. if (this._physicsEngine) {
  86099. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  86100. }
  86101. return this;
  86102. };
  86103. /**
  86104. * Apply an impulse
  86105. */
  86106. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  86107. if (this._physicsEngine) {
  86108. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  86109. }
  86110. return this;
  86111. };
  86112. /**
  86113. * A help function to create a joint.
  86114. */
  86115. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  86116. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  86117. this.addJoint(otherImpostor, joint);
  86118. return this;
  86119. };
  86120. /**
  86121. * Add a joint to this impostor with a different impostor.
  86122. */
  86123. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  86124. this._joints.push({
  86125. otherImpostor: otherImpostor,
  86126. joint: joint
  86127. });
  86128. if (this._physicsEngine) {
  86129. this._physicsEngine.addJoint(this, otherImpostor, joint);
  86130. }
  86131. return this;
  86132. };
  86133. /**
  86134. * Will keep this body still, in a sleep mode.
  86135. */
  86136. PhysicsImpostor.prototype.sleep = function () {
  86137. if (this._physicsEngine) {
  86138. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  86139. }
  86140. return this;
  86141. };
  86142. /**
  86143. * Wake the body up.
  86144. */
  86145. PhysicsImpostor.prototype.wakeUp = function () {
  86146. if (this._physicsEngine) {
  86147. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  86148. }
  86149. return this;
  86150. };
  86151. PhysicsImpostor.prototype.clone = function (newObject) {
  86152. if (!newObject)
  86153. return null;
  86154. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  86155. };
  86156. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  86157. var _this = this;
  86158. //no dispose if no physics engine is available.
  86159. if (!this._physicsEngine) {
  86160. return;
  86161. }
  86162. this._joints.forEach(function (j) {
  86163. if (_this._physicsEngine) {
  86164. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  86165. }
  86166. });
  86167. //dispose the physics body
  86168. this._physicsEngine.removeImpostor(this);
  86169. if (this.parent) {
  86170. this.parent.forceUpdate();
  86171. }
  86172. else {
  86173. /*this._object.getChildMeshes().forEach(function(mesh) {
  86174. if (mesh.physicsImpostor) {
  86175. if (disposeChildren) {
  86176. mesh.physicsImpostor.dispose();
  86177. mesh.physicsImpostor = null;
  86178. }
  86179. }
  86180. })*/
  86181. }
  86182. this._isDisposed = true;
  86183. };
  86184. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  86185. this._deltaPosition.copyFrom(position);
  86186. };
  86187. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  86188. if (!this._deltaRotation) {
  86189. this._deltaRotation = new BABYLON.Quaternion();
  86190. }
  86191. this._deltaRotation.copyFrom(rotation);
  86192. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  86193. };
  86194. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  86195. if (this._physicsEngine) {
  86196. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  86197. }
  86198. return this;
  86199. };
  86200. PhysicsImpostor.prototype.getRadius = function () {
  86201. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  86202. };
  86203. /**
  86204. * Sync a bone with this impostor
  86205. * @param bone The bone to sync to the impostor.
  86206. * @param boneMesh The mesh that the bone is influencing.
  86207. * @param jointPivot The pivot of the joint / bone in local space.
  86208. * @param distToJoint Optional distance from the impostor to the joint.
  86209. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  86210. */
  86211. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  86212. var tempVec = PhysicsImpostor._tmpVecs[0];
  86213. var mesh = this.object;
  86214. if (mesh.rotationQuaternion) {
  86215. if (adjustRotation) {
  86216. var tempQuat = PhysicsImpostor._tmpQuat;
  86217. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  86218. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  86219. }
  86220. else {
  86221. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  86222. }
  86223. }
  86224. tempVec.x = 0;
  86225. tempVec.y = 0;
  86226. tempVec.z = 0;
  86227. if (jointPivot) {
  86228. tempVec.x = jointPivot.x;
  86229. tempVec.y = jointPivot.y;
  86230. tempVec.z = jointPivot.z;
  86231. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  86232. if (distToJoint === undefined || distToJoint === null) {
  86233. distToJoint = jointPivot.length();
  86234. }
  86235. tempVec.x *= distToJoint;
  86236. tempVec.y *= distToJoint;
  86237. tempVec.z *= distToJoint;
  86238. }
  86239. if (bone.getParent()) {
  86240. tempVec.addInPlace(mesh.getAbsolutePosition());
  86241. bone.setAbsolutePosition(tempVec, boneMesh);
  86242. }
  86243. else {
  86244. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  86245. boneMesh.position.x -= tempVec.x;
  86246. boneMesh.position.y -= tempVec.y;
  86247. boneMesh.position.z -= tempVec.z;
  86248. }
  86249. };
  86250. /**
  86251. * Sync impostor to a bone
  86252. * @param bone The bone that the impostor will be synced to.
  86253. * @param boneMesh The mesh that the bone is influencing.
  86254. * @param jointPivot The pivot of the joint / bone in local space.
  86255. * @param distToJoint Optional distance from the impostor to the joint.
  86256. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  86257. * @param boneAxis Optional vector3 axis the bone is aligned with
  86258. */
  86259. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  86260. var mesh = this.object;
  86261. if (mesh.rotationQuaternion) {
  86262. if (adjustRotation) {
  86263. var tempQuat = PhysicsImpostor._tmpQuat;
  86264. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  86265. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  86266. }
  86267. else {
  86268. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  86269. }
  86270. }
  86271. var pos = PhysicsImpostor._tmpVecs[0];
  86272. var boneDir = PhysicsImpostor._tmpVecs[1];
  86273. if (!boneAxis) {
  86274. boneAxis = PhysicsImpostor._tmpVecs[2];
  86275. boneAxis.x = 0;
  86276. boneAxis.y = 1;
  86277. boneAxis.z = 0;
  86278. }
  86279. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  86280. bone.getAbsolutePositionToRef(boneMesh, pos);
  86281. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  86282. distToJoint = jointPivot.length();
  86283. }
  86284. if (distToJoint !== undefined && distToJoint !== null) {
  86285. pos.x += boneDir.x * distToJoint;
  86286. pos.y += boneDir.y * distToJoint;
  86287. pos.z += boneDir.z * distToJoint;
  86288. }
  86289. mesh.setAbsolutePosition(pos);
  86290. };
  86291. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  86292. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  86293. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86294. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  86295. //Impostor types
  86296. PhysicsImpostor.NoImpostor = 0;
  86297. PhysicsImpostor.SphereImpostor = 1;
  86298. PhysicsImpostor.BoxImpostor = 2;
  86299. PhysicsImpostor.PlaneImpostor = 3;
  86300. PhysicsImpostor.MeshImpostor = 4;
  86301. PhysicsImpostor.CylinderImpostor = 7;
  86302. PhysicsImpostor.ParticleImpostor = 8;
  86303. PhysicsImpostor.HeightmapImpostor = 9;
  86304. return PhysicsImpostor;
  86305. }());
  86306. BABYLON.PhysicsImpostor = PhysicsImpostor;
  86307. })(BABYLON || (BABYLON = {}));
  86308. //# sourceMappingURL=babylon.physicsImpostor.js.map
  86309. var BABYLON;
  86310. (function (BABYLON) {
  86311. var PhysicsEngine = /** @class */ (function () {
  86312. function PhysicsEngine(gravity, _physicsPlugin) {
  86313. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  86314. this._physicsPlugin = _physicsPlugin;
  86315. //new methods and parameters
  86316. this._impostors = [];
  86317. this._joints = [];
  86318. if (!this._physicsPlugin.isSupported()) {
  86319. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  86320. + "Please make sure it is included.");
  86321. }
  86322. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  86323. this.setGravity(gravity);
  86324. this.setTimeStep();
  86325. }
  86326. PhysicsEngine.prototype.setGravity = function (gravity) {
  86327. this.gravity = gravity;
  86328. this._physicsPlugin.setGravity(this.gravity);
  86329. };
  86330. /**
  86331. * Set the time step of the physics engine.
  86332. * default is 1/60.
  86333. * To slow it down, enter 1/600 for example.
  86334. * To speed it up, 1/30
  86335. * @param {number} newTimeStep the new timestep to apply to this world.
  86336. */
  86337. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  86338. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  86339. this._physicsPlugin.setTimeStep(newTimeStep);
  86340. };
  86341. /**
  86342. * Get the time step of the physics engine.
  86343. */
  86344. PhysicsEngine.prototype.getTimeStep = function () {
  86345. return this._physicsPlugin.getTimeStep();
  86346. };
  86347. PhysicsEngine.prototype.dispose = function () {
  86348. this._impostors.forEach(function (impostor) {
  86349. impostor.dispose();
  86350. });
  86351. this._physicsPlugin.dispose();
  86352. };
  86353. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  86354. return this._physicsPlugin.name;
  86355. };
  86356. /**
  86357. * Adding a new impostor for the impostor tracking.
  86358. * This will be done by the impostor itself.
  86359. * @param {PhysicsImpostor} impostor the impostor to add
  86360. */
  86361. PhysicsEngine.prototype.addImpostor = function (impostor) {
  86362. impostor.uniqueId = this._impostors.push(impostor);
  86363. //if no parent, generate the body
  86364. if (!impostor.parent) {
  86365. this._physicsPlugin.generatePhysicsBody(impostor);
  86366. }
  86367. };
  86368. /**
  86369. * Remove an impostor from the engine.
  86370. * This impostor and its mesh will not longer be updated by the physics engine.
  86371. * @param {PhysicsImpostor} impostor the impostor to remove
  86372. */
  86373. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  86374. var index = this._impostors.indexOf(impostor);
  86375. if (index > -1) {
  86376. var removed = this._impostors.splice(index, 1);
  86377. //Is it needed?
  86378. if (removed.length) {
  86379. //this will also remove it from the world.
  86380. removed[0].physicsBody = null;
  86381. }
  86382. }
  86383. };
  86384. /**
  86385. * Add a joint to the physics engine
  86386. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  86387. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  86388. * @param {PhysicsJoint} the joint that will connect both impostors.
  86389. */
  86390. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  86391. var impostorJoint = {
  86392. mainImpostor: mainImpostor,
  86393. connectedImpostor: connectedImpostor,
  86394. joint: joint
  86395. };
  86396. joint.physicsPlugin = this._physicsPlugin;
  86397. this._joints.push(impostorJoint);
  86398. this._physicsPlugin.generateJoint(impostorJoint);
  86399. };
  86400. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  86401. var matchingJoints = this._joints.filter(function (impostorJoint) {
  86402. return (impostorJoint.connectedImpostor === connectedImpostor
  86403. && impostorJoint.joint === joint
  86404. && impostorJoint.mainImpostor === mainImpostor);
  86405. });
  86406. if (matchingJoints.length) {
  86407. this._physicsPlugin.removeJoint(matchingJoints[0]);
  86408. //TODO remove it from the list as well
  86409. }
  86410. };
  86411. /**
  86412. * Called by the scene. no need to call it.
  86413. */
  86414. PhysicsEngine.prototype._step = function (delta) {
  86415. var _this = this;
  86416. //check if any mesh has no body / requires an update
  86417. this._impostors.forEach(function (impostor) {
  86418. if (impostor.isBodyInitRequired()) {
  86419. _this._physicsPlugin.generatePhysicsBody(impostor);
  86420. }
  86421. });
  86422. if (delta > 0.1) {
  86423. delta = 0.1;
  86424. }
  86425. else if (delta <= 0) {
  86426. delta = 1.0 / 60.0;
  86427. }
  86428. this._physicsPlugin.executeStep(delta, this._impostors);
  86429. };
  86430. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  86431. return this._physicsPlugin;
  86432. };
  86433. PhysicsEngine.prototype.getImpostors = function () {
  86434. return this._impostors;
  86435. };
  86436. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  86437. for (var i = 0; i < this._impostors.length; ++i) {
  86438. if (this._impostors[i].object === object) {
  86439. return this._impostors[i];
  86440. }
  86441. }
  86442. return null;
  86443. };
  86444. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  86445. for (var i = 0; i < this._impostors.length; ++i) {
  86446. if (this._impostors[i].physicsBody === body) {
  86447. return this._impostors[i];
  86448. }
  86449. }
  86450. return null;
  86451. };
  86452. // Statics
  86453. PhysicsEngine.Epsilon = 0.001;
  86454. return PhysicsEngine;
  86455. }());
  86456. BABYLON.PhysicsEngine = PhysicsEngine;
  86457. })(BABYLON || (BABYLON = {}));
  86458. //# sourceMappingURL=babylon.physicsEngine.js.map
  86459. var BABYLON;
  86460. (function (BABYLON) {
  86461. var PhysicsHelper = /** @class */ (function () {
  86462. function PhysicsHelper(scene) {
  86463. this._scene = scene;
  86464. this._physicsEngine = this._scene.getPhysicsEngine();
  86465. if (!this._physicsEngine) {
  86466. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  86467. }
  86468. }
  86469. /**
  86470. * @param {Vector3} origin the origin of the explosion
  86471. * @param {number} radius the explosion radius
  86472. * @param {number} strength the explosion strength
  86473. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86474. */
  86475. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  86476. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86477. if (!this._physicsEngine) {
  86478. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  86479. return null;
  86480. }
  86481. var impostors = this._physicsEngine.getImpostors();
  86482. if (impostors.length === 0) {
  86483. return null;
  86484. }
  86485. var event = new PhysicsRadialExplosionEvent(this._scene);
  86486. impostors.forEach(function (impostor) {
  86487. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  86488. if (!impostorForceAndContactPoint) {
  86489. return;
  86490. }
  86491. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86492. });
  86493. event.dispose(false);
  86494. return event;
  86495. };
  86496. /**
  86497. * @param {Vector3} origin the origin of the explosion
  86498. * @param {number} radius the explosion radius
  86499. * @param {number} strength the explosion strength
  86500. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86501. */
  86502. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  86503. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86504. if (!this._physicsEngine) {
  86505. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86506. return null;
  86507. }
  86508. var impostors = this._physicsEngine.getImpostors();
  86509. if (impostors.length === 0) {
  86510. return null;
  86511. }
  86512. var event = new PhysicsRadialExplosionEvent(this._scene);
  86513. impostors.forEach(function (impostor) {
  86514. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  86515. if (!impostorForceAndContactPoint) {
  86516. return;
  86517. }
  86518. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86519. });
  86520. event.dispose(false);
  86521. return event;
  86522. };
  86523. /**
  86524. * @param {Vector3} origin the origin of the explosion
  86525. * @param {number} radius the explosion radius
  86526. * @param {number} strength the explosion strength
  86527. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86528. */
  86529. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  86530. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86531. if (!this._physicsEngine) {
  86532. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86533. return null;
  86534. }
  86535. var impostors = this._physicsEngine.getImpostors();
  86536. if (impostors.length === 0) {
  86537. return null;
  86538. }
  86539. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  86540. event.dispose(false);
  86541. return event;
  86542. };
  86543. /**
  86544. * @param {Vector3} origin the origin of the updraft
  86545. * @param {number} radius the radius of the updraft
  86546. * @param {number} strength the strength of the updraft
  86547. * @param {number} height the height of the updraft
  86548. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  86549. */
  86550. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  86551. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  86552. if (!this._physicsEngine) {
  86553. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86554. return null;
  86555. }
  86556. if (this._physicsEngine.getImpostors().length === 0) {
  86557. return null;
  86558. }
  86559. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  86560. event.dispose(false);
  86561. return event;
  86562. };
  86563. /**
  86564. * @param {Vector3} origin the of the vortex
  86565. * @param {number} radius the radius of the vortex
  86566. * @param {number} strength the strength of the vortex
  86567. * @param {number} height the height of the vortex
  86568. */
  86569. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  86570. if (!this._physicsEngine) {
  86571. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86572. return null;
  86573. }
  86574. if (this._physicsEngine.getImpostors().length === 0) {
  86575. return null;
  86576. }
  86577. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  86578. event.dispose(false);
  86579. return event;
  86580. };
  86581. return PhysicsHelper;
  86582. }());
  86583. BABYLON.PhysicsHelper = PhysicsHelper;
  86584. /***** Radial explosion *****/
  86585. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  86586. function PhysicsRadialExplosionEvent(scene) {
  86587. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  86588. this._rays = [];
  86589. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  86590. this._scene = scene;
  86591. }
  86592. /**
  86593. * Returns the data related to the radial explosion event (sphere & rays).
  86594. * @returns {PhysicsRadialExplosionEventData}
  86595. */
  86596. PhysicsRadialExplosionEvent.prototype.getData = function () {
  86597. this._dataFetched = true;
  86598. return {
  86599. sphere: this._sphere,
  86600. rays: this._rays,
  86601. };
  86602. };
  86603. /**
  86604. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  86605. * @param impostor
  86606. * @param {Vector3} origin the origin of the explosion
  86607. * @param {number} radius the explosion radius
  86608. * @param {number} strength the explosion strength
  86609. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  86610. * @returns {Nullable<PhysicsForceAndContactPoint>}
  86611. */
  86612. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  86613. if (impostor.mass === 0) {
  86614. return null;
  86615. }
  86616. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  86617. return null;
  86618. }
  86619. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86620. return null;
  86621. }
  86622. var impostorObjectCenter = impostor.getObjectCenter();
  86623. var direction = impostorObjectCenter.subtract(origin);
  86624. var ray = new BABYLON.Ray(origin, direction, radius);
  86625. this._rays.push(ray);
  86626. var hit = ray.intersectsMesh(impostor.object);
  86627. var contactPoint = hit.pickedPoint;
  86628. if (!contactPoint) {
  86629. return null;
  86630. }
  86631. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  86632. if (distanceFromOrigin > radius) {
  86633. return null;
  86634. }
  86635. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  86636. ? strength
  86637. : strength * (1 - (distanceFromOrigin / radius));
  86638. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86639. return { force: force, contactPoint: contactPoint };
  86640. };
  86641. /**
  86642. * Disposes the sphere.
  86643. * @param {bolean} force
  86644. */
  86645. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  86646. var _this = this;
  86647. if (force === void 0) { force = true; }
  86648. if (force) {
  86649. this._sphere.dispose();
  86650. }
  86651. else {
  86652. setTimeout(function () {
  86653. if (!_this._dataFetched) {
  86654. _this._sphere.dispose();
  86655. }
  86656. }, 0);
  86657. }
  86658. };
  86659. /*** Helpers ***/
  86660. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  86661. if (!this._sphere) {
  86662. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  86663. this._sphere.isVisible = false;
  86664. }
  86665. };
  86666. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  86667. var impostorObject = impostor.object;
  86668. this._prepareSphere();
  86669. this._sphere.position = origin;
  86670. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  86671. this._sphere._updateBoundingInfo();
  86672. this._sphere.computeWorldMatrix(true);
  86673. return this._sphere.intersectsMesh(impostorObject, true);
  86674. };
  86675. return PhysicsRadialExplosionEvent;
  86676. }());
  86677. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  86678. /***** Gravitational Field *****/
  86679. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  86680. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  86681. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86682. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86683. this._physicsHelper = physicsHelper;
  86684. this._scene = scene;
  86685. this._origin = origin;
  86686. this._radius = radius;
  86687. this._strength = strength;
  86688. this._falloff = falloff;
  86689. this._tickCallback = this._tick.bind(this);
  86690. }
  86691. /**
  86692. * Returns the data related to the gravitational field event (sphere).
  86693. * @returns {PhysicsGravitationalFieldEventData}
  86694. */
  86695. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  86696. this._dataFetched = true;
  86697. return {
  86698. sphere: this._sphere,
  86699. };
  86700. };
  86701. /**
  86702. * Enables the gravitational field.
  86703. */
  86704. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  86705. this._tickCallback.call(this);
  86706. this._scene.registerBeforeRender(this._tickCallback);
  86707. };
  86708. /**
  86709. * Disables the gravitational field.
  86710. */
  86711. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  86712. this._scene.unregisterBeforeRender(this._tickCallback);
  86713. };
  86714. /**
  86715. * Disposes the sphere.
  86716. * @param {bolean} force
  86717. */
  86718. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  86719. var _this = this;
  86720. if (force === void 0) { force = true; }
  86721. if (force) {
  86722. this._sphere.dispose();
  86723. }
  86724. else {
  86725. setTimeout(function () {
  86726. if (!_this._dataFetched) {
  86727. _this._sphere.dispose();
  86728. }
  86729. }, 0);
  86730. }
  86731. };
  86732. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  86733. // Since the params won't change, we fetch the event only once
  86734. if (this._sphere) {
  86735. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86736. }
  86737. else {
  86738. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86739. if (radialExplosionEvent) {
  86740. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  86741. }
  86742. }
  86743. };
  86744. return PhysicsGravitationalFieldEvent;
  86745. }());
  86746. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  86747. /***** Updraft *****/
  86748. var PhysicsUpdraftEvent = /** @class */ (function () {
  86749. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  86750. this._scene = _scene;
  86751. this._origin = _origin;
  86752. this._radius = _radius;
  86753. this._strength = _strength;
  86754. this._height = _height;
  86755. this._updraftMode = _updraftMode;
  86756. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86757. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  86758. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86759. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86760. this._physicsEngine = this._scene.getPhysicsEngine();
  86761. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86762. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86763. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86764. this._originDirection = this._origin.subtract(this._originTop).normalize();
  86765. }
  86766. this._tickCallback = this._tick.bind(this);
  86767. }
  86768. /**
  86769. * Returns the data related to the updraft event (cylinder).
  86770. * @returns {PhysicsUpdraftEventData}
  86771. */
  86772. PhysicsUpdraftEvent.prototype.getData = function () {
  86773. this._dataFetched = true;
  86774. return {
  86775. cylinder: this._cylinder,
  86776. };
  86777. };
  86778. /**
  86779. * Enables the updraft.
  86780. */
  86781. PhysicsUpdraftEvent.prototype.enable = function () {
  86782. this._tickCallback.call(this);
  86783. this._scene.registerBeforeRender(this._tickCallback);
  86784. };
  86785. /**
  86786. * Disables the cortex.
  86787. */
  86788. PhysicsUpdraftEvent.prototype.disable = function () {
  86789. this._scene.unregisterBeforeRender(this._tickCallback);
  86790. };
  86791. /**
  86792. * Disposes the sphere.
  86793. * @param {bolean} force
  86794. */
  86795. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  86796. var _this = this;
  86797. if (force === void 0) { force = true; }
  86798. if (force) {
  86799. this._cylinder.dispose();
  86800. }
  86801. else {
  86802. setTimeout(function () {
  86803. if (!_this._dataFetched) {
  86804. _this._cylinder.dispose();
  86805. }
  86806. }, 0);
  86807. }
  86808. };
  86809. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86810. if (impostor.mass === 0) {
  86811. return null;
  86812. }
  86813. if (!this._intersectsWithCylinder(impostor)) {
  86814. return null;
  86815. }
  86816. var impostorObjectCenter = impostor.getObjectCenter();
  86817. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86818. var direction = this._originDirection;
  86819. }
  86820. else {
  86821. var direction = impostorObjectCenter.subtract(this._originTop);
  86822. }
  86823. var multiplier = this._strength * -1;
  86824. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86825. return { force: force, contactPoint: impostorObjectCenter };
  86826. };
  86827. PhysicsUpdraftEvent.prototype._tick = function () {
  86828. var _this = this;
  86829. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86830. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86831. if (!impostorForceAndContactPoint) {
  86832. return;
  86833. }
  86834. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86835. });
  86836. };
  86837. /*** Helpers ***/
  86838. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  86839. if (!this._cylinder) {
  86840. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  86841. height: this._height,
  86842. diameter: this._radius * 2,
  86843. }, this._scene);
  86844. this._cylinder.isVisible = false;
  86845. }
  86846. };
  86847. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  86848. var impostorObject = impostor.object;
  86849. this._prepareCylinder();
  86850. this._cylinder.position = this._cylinderPosition;
  86851. return this._cylinder.intersectsMesh(impostorObject, true);
  86852. };
  86853. return PhysicsUpdraftEvent;
  86854. }());
  86855. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  86856. /***** Vortex *****/
  86857. var PhysicsVortexEvent = /** @class */ (function () {
  86858. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  86859. this._scene = _scene;
  86860. this._origin = _origin;
  86861. this._radius = _radius;
  86862. this._strength = _strength;
  86863. this._height = _height;
  86864. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86865. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  86866. this._updraftMultiplier = 0.02;
  86867. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86868. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86869. this._physicsEngine = this._scene.getPhysicsEngine();
  86870. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86871. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86872. this._tickCallback = this._tick.bind(this);
  86873. }
  86874. /**
  86875. * Returns the data related to the vortex event (cylinder).
  86876. * @returns {PhysicsVortexEventData}
  86877. */
  86878. PhysicsVortexEvent.prototype.getData = function () {
  86879. this._dataFetched = true;
  86880. return {
  86881. cylinder: this._cylinder,
  86882. };
  86883. };
  86884. /**
  86885. * Enables the vortex.
  86886. */
  86887. PhysicsVortexEvent.prototype.enable = function () {
  86888. this._tickCallback.call(this);
  86889. this._scene.registerBeforeRender(this._tickCallback);
  86890. };
  86891. /**
  86892. * Disables the cortex.
  86893. */
  86894. PhysicsVortexEvent.prototype.disable = function () {
  86895. this._scene.unregisterBeforeRender(this._tickCallback);
  86896. };
  86897. /**
  86898. * Disposes the sphere.
  86899. * @param {bolean} force
  86900. */
  86901. PhysicsVortexEvent.prototype.dispose = function (force) {
  86902. var _this = this;
  86903. if (force === void 0) { force = true; }
  86904. if (force) {
  86905. this._cylinder.dispose();
  86906. }
  86907. else {
  86908. setTimeout(function () {
  86909. if (!_this._dataFetched) {
  86910. _this._cylinder.dispose();
  86911. }
  86912. }, 0);
  86913. }
  86914. };
  86915. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86916. if (impostor.mass === 0) {
  86917. return null;
  86918. }
  86919. if (!this._intersectsWithCylinder(impostor)) {
  86920. return null;
  86921. }
  86922. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86923. return null;
  86924. }
  86925. var impostorObjectCenter = impostor.getObjectCenter();
  86926. 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)
  86927. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  86928. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  86929. var hit = ray.intersectsMesh(impostor.object);
  86930. var contactPoint = hit.pickedPoint;
  86931. if (!contactPoint) {
  86932. return null;
  86933. }
  86934. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  86935. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  86936. var directionToOrigin = contactPoint.normalize();
  86937. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86938. directionToOrigin = directionToOrigin.negate();
  86939. }
  86940. // TODO: find a more physically based solution
  86941. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86942. var forceX = directionToOrigin.x * this._strength / 8;
  86943. var forceY = directionToOrigin.y * this._updraftMultiplier;
  86944. var forceZ = directionToOrigin.z * this._strength / 8;
  86945. }
  86946. else {
  86947. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  86948. var forceY = this._originTop.y * this._updraftMultiplier;
  86949. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  86950. }
  86951. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  86952. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  86953. return { force: force, contactPoint: impostorObjectCenter };
  86954. };
  86955. PhysicsVortexEvent.prototype._tick = function () {
  86956. var _this = this;
  86957. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86958. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86959. if (!impostorForceAndContactPoint) {
  86960. return;
  86961. }
  86962. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86963. });
  86964. };
  86965. /*** Helpers ***/
  86966. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86967. if (!this._cylinder) {
  86968. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86969. height: this._height,
  86970. diameter: this._radius * 2,
  86971. }, this._scene);
  86972. this._cylinder.isVisible = false;
  86973. }
  86974. };
  86975. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86976. var impostorObject = impostor.object;
  86977. this._prepareCylinder();
  86978. this._cylinder.position = this._cylinderPosition;
  86979. return this._cylinder.intersectsMesh(impostorObject, true);
  86980. };
  86981. return PhysicsVortexEvent;
  86982. }());
  86983. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86984. /***** Enums *****/
  86985. /**
  86986. * The strenght of the force in correspondence to the distance of the affected object
  86987. */
  86988. var PhysicsRadialImpulseFalloff;
  86989. (function (PhysicsRadialImpulseFalloff) {
  86990. /** Defines that impulse is constant in strength across it's whole radius */
  86991. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86992. /** DEfines that impulse gets weaker if it's further from the origin */
  86993. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86994. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86995. /**
  86996. * The strenght of the force in correspondence to the distance of the affected object
  86997. */
  86998. var PhysicsUpdraftMode;
  86999. (function (PhysicsUpdraftMode) {
  87000. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  87001. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  87002. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  87003. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  87004. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  87005. })(BABYLON || (BABYLON = {}));
  87006. //# sourceMappingURL=babylon.physicsHelper.js.map
  87007. var BABYLON;
  87008. (function (BABYLON) {
  87009. var CannonJSPlugin = /** @class */ (function () {
  87010. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  87011. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  87012. if (iterations === void 0) { iterations = 10; }
  87013. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  87014. this.name = "CannonJSPlugin";
  87015. this._physicsMaterials = new Array();
  87016. this._fixedTimeStep = 1 / 60;
  87017. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  87018. this.BJSCANNON = CANNON;
  87019. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  87020. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  87021. this._tmpPosition = BABYLON.Vector3.Zero();
  87022. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  87023. this._tmpUnityRotation = new BABYLON.Quaternion();
  87024. if (!this.isSupported()) {
  87025. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  87026. return;
  87027. }
  87028. this._extendNamespace();
  87029. this.world = new this.BJSCANNON.World();
  87030. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  87031. this.world.solver.iterations = iterations;
  87032. }
  87033. CannonJSPlugin.prototype.setGravity = function (gravity) {
  87034. this.world.gravity.copy(gravity);
  87035. };
  87036. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  87037. this._fixedTimeStep = timeStep;
  87038. };
  87039. CannonJSPlugin.prototype.getTimeStep = function () {
  87040. return this._fixedTimeStep;
  87041. };
  87042. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  87043. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  87044. };
  87045. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  87046. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  87047. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  87048. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  87049. };
  87050. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  87051. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  87052. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  87053. impostor.physicsBody.applyForce(impulse, worldPoint);
  87054. };
  87055. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  87056. //parent-child relationship. Does this impostor has a parent impostor?
  87057. if (impostor.parent) {
  87058. if (impostor.physicsBody) {
  87059. this.removePhysicsBody(impostor);
  87060. //TODO is that needed?
  87061. impostor.forceUpdate();
  87062. }
  87063. return;
  87064. }
  87065. //should a new body be created for this impostor?
  87066. if (impostor.isBodyInitRequired()) {
  87067. var shape = this._createShape(impostor);
  87068. //unregister events, if body is being changed
  87069. var oldBody = impostor.physicsBody;
  87070. if (oldBody) {
  87071. this.removePhysicsBody(impostor);
  87072. }
  87073. //create the body and material
  87074. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  87075. var bodyCreationObject = {
  87076. mass: impostor.getParam("mass"),
  87077. material: material
  87078. };
  87079. // A simple extend, in case native options were used.
  87080. var nativeOptions = impostor.getParam("nativeOptions");
  87081. for (var key in nativeOptions) {
  87082. if (nativeOptions.hasOwnProperty(key)) {
  87083. bodyCreationObject[key] = nativeOptions[key];
  87084. }
  87085. }
  87086. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  87087. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  87088. this.world.addEventListener("preStep", impostor.beforeStep);
  87089. this.world.addEventListener("postStep", impostor.afterStep);
  87090. impostor.physicsBody.addShape(shape);
  87091. this.world.add(impostor.physicsBody);
  87092. //try to keep the body moving in the right direction by taking old properties.
  87093. //Should be tested!
  87094. if (oldBody) {
  87095. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  87096. impostor.physicsBody[param].copy(oldBody[param]);
  87097. });
  87098. }
  87099. this._processChildMeshes(impostor);
  87100. }
  87101. //now update the body's transformation
  87102. this._updatePhysicsBodyTransformation(impostor);
  87103. };
  87104. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  87105. var _this = this;
  87106. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  87107. var currentRotation = mainImpostor.object.rotationQuaternion;
  87108. if (meshChildren.length) {
  87109. var processMesh = function (localPosition, mesh) {
  87110. if (!currentRotation || !mesh.rotationQuaternion) {
  87111. return;
  87112. }
  87113. var childImpostor = mesh.getPhysicsImpostor();
  87114. if (childImpostor) {
  87115. var parent = childImpostor.parent;
  87116. if (parent !== mainImpostor) {
  87117. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  87118. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  87119. if (childImpostor.physicsBody) {
  87120. _this.removePhysicsBody(childImpostor);
  87121. childImpostor.physicsBody = null;
  87122. }
  87123. childImpostor.parent = mainImpostor;
  87124. childImpostor.resetUpdateFlags();
  87125. 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));
  87126. //Add the mass of the children.
  87127. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  87128. }
  87129. }
  87130. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  87131. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  87132. };
  87133. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  87134. }
  87135. };
  87136. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  87137. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  87138. this.world.removeEventListener("preStep", impostor.beforeStep);
  87139. this.world.removeEventListener("postStep", impostor.afterStep);
  87140. this.world.remove(impostor.physicsBody);
  87141. };
  87142. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  87143. var mainBody = impostorJoint.mainImpostor.physicsBody;
  87144. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  87145. if (!mainBody || !connectedBody) {
  87146. return;
  87147. }
  87148. var constraint;
  87149. var jointData = impostorJoint.joint.jointData;
  87150. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  87151. var constraintData = {
  87152. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  87153. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  87154. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  87155. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  87156. maxForce: jointData.nativeParams.maxForce,
  87157. collideConnected: !!jointData.collision
  87158. };
  87159. switch (impostorJoint.joint.type) {
  87160. case BABYLON.PhysicsJoint.HingeJoint:
  87161. case BABYLON.PhysicsJoint.Hinge2Joint:
  87162. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  87163. break;
  87164. case BABYLON.PhysicsJoint.DistanceJoint:
  87165. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  87166. break;
  87167. case BABYLON.PhysicsJoint.SpringJoint:
  87168. var springData = jointData;
  87169. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  87170. restLength: springData.length,
  87171. stiffness: springData.stiffness,
  87172. damping: springData.damping,
  87173. localAnchorA: constraintData.pivotA,
  87174. localAnchorB: constraintData.pivotB
  87175. });
  87176. break;
  87177. case BABYLON.PhysicsJoint.LockJoint:
  87178. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  87179. break;
  87180. case BABYLON.PhysicsJoint.PointToPointJoint:
  87181. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87182. default:
  87183. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  87184. break;
  87185. }
  87186. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  87187. constraint.collideConnected = !!jointData.collision;
  87188. impostorJoint.joint.physicsJoint = constraint;
  87189. //don't add spring as constraint, as it is not one.
  87190. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  87191. this.world.addConstraint(constraint);
  87192. }
  87193. else {
  87194. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  87195. constraint.applyForce();
  87196. });
  87197. }
  87198. };
  87199. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87200. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  87201. };
  87202. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  87203. var index;
  87204. var mat;
  87205. for (index = 0; index < this._physicsMaterials.length; index++) {
  87206. mat = this._physicsMaterials[index];
  87207. if (mat.friction === friction && mat.restitution === restitution) {
  87208. return mat;
  87209. }
  87210. }
  87211. var currentMat = new this.BJSCANNON.Material(name);
  87212. currentMat.friction = friction;
  87213. currentMat.restitution = restitution;
  87214. this._physicsMaterials.push(currentMat);
  87215. return currentMat;
  87216. };
  87217. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  87218. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  87219. };
  87220. CannonJSPlugin.prototype._createShape = function (impostor) {
  87221. var object = impostor.object;
  87222. var returnValue;
  87223. var extendSize = impostor.getObjectExtendSize();
  87224. switch (impostor.type) {
  87225. case BABYLON.PhysicsImpostor.SphereImpostor:
  87226. var radiusX = extendSize.x;
  87227. var radiusY = extendSize.y;
  87228. var radiusZ = extendSize.z;
  87229. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  87230. break;
  87231. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  87232. case BABYLON.PhysicsImpostor.CylinderImpostor:
  87233. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  87234. break;
  87235. case BABYLON.PhysicsImpostor.BoxImpostor:
  87236. var box = extendSize.scale(0.5);
  87237. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  87238. break;
  87239. case BABYLON.PhysicsImpostor.PlaneImpostor:
  87240. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  87241. returnValue = new this.BJSCANNON.Plane();
  87242. break;
  87243. case BABYLON.PhysicsImpostor.MeshImpostor:
  87244. // should transform the vertex data to world coordinates!!
  87245. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  87246. var rawFaces = object.getIndices ? object.getIndices() : [];
  87247. if (!rawVerts)
  87248. return;
  87249. // get only scale! so the object could transform correctly.
  87250. var oldPosition = object.position.clone();
  87251. var oldRotation = object.rotation && object.rotation.clone();
  87252. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  87253. object.position.copyFromFloats(0, 0, 0);
  87254. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  87255. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  87256. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  87257. var transform = object.computeWorldMatrix(true);
  87258. // convert rawVerts to object space
  87259. var temp = new Array();
  87260. var index;
  87261. for (index = 0; index < rawVerts.length; index += 3) {
  87262. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  87263. }
  87264. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  87265. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  87266. //now set back the transformation!
  87267. object.position.copyFrom(oldPosition);
  87268. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  87269. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  87270. break;
  87271. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  87272. var oldPosition2 = object.position.clone();
  87273. var oldRotation2 = object.rotation && object.rotation.clone();
  87274. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  87275. object.position.copyFromFloats(0, 0, 0);
  87276. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  87277. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  87278. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  87279. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  87280. returnValue = this._createHeightmap(object);
  87281. object.position.copyFrom(oldPosition2);
  87282. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  87283. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  87284. object.computeWorldMatrix(true);
  87285. break;
  87286. case BABYLON.PhysicsImpostor.ParticleImpostor:
  87287. returnValue = new this.BJSCANNON.Particle();
  87288. break;
  87289. }
  87290. return returnValue;
  87291. };
  87292. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  87293. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  87294. var transform = object.computeWorldMatrix(true);
  87295. // convert rawVerts to object space
  87296. var temp = new Array();
  87297. var index;
  87298. for (index = 0; index < pos.length; index += 3) {
  87299. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  87300. }
  87301. pos = temp;
  87302. var matrix = new Array();
  87303. //For now pointDepth will not be used and will be automatically calculated.
  87304. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  87305. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  87306. var boundingInfo = object.getBoundingInfo();
  87307. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  87308. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  87309. var elementSize = dim * 2 / arraySize;
  87310. for (var i = 0; i < pos.length; i = i + 3) {
  87311. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  87312. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  87313. var y = -pos[i + 2] + minY;
  87314. if (!matrix[x]) {
  87315. matrix[x] = [];
  87316. }
  87317. if (!matrix[x][z]) {
  87318. matrix[x][z] = y;
  87319. }
  87320. matrix[x][z] = Math.max(y, matrix[x][z]);
  87321. }
  87322. for (var x = 0; x <= arraySize; ++x) {
  87323. if (!matrix[x]) {
  87324. var loc = 1;
  87325. while (!matrix[(x + loc) % arraySize]) {
  87326. loc++;
  87327. }
  87328. matrix[x] = matrix[(x + loc) % arraySize].slice();
  87329. //console.log("missing x", x);
  87330. }
  87331. for (var z = 0; z <= arraySize; ++z) {
  87332. if (!matrix[x][z]) {
  87333. var loc = 1;
  87334. var newValue;
  87335. while (newValue === undefined) {
  87336. newValue = matrix[x][(z + loc++) % arraySize];
  87337. }
  87338. matrix[x][z] = newValue;
  87339. }
  87340. }
  87341. }
  87342. var shape = new this.BJSCANNON.Heightfield(matrix, {
  87343. elementSize: elementSize
  87344. });
  87345. //For future reference, needed for body transformation
  87346. shape.minY = minY;
  87347. return shape;
  87348. };
  87349. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  87350. var object = impostor.object;
  87351. //make sure it is updated...
  87352. object.computeWorldMatrix && object.computeWorldMatrix(true);
  87353. // The delta between the mesh position and the mesh bounding box center
  87354. var bInfo = object.getBoundingInfo();
  87355. if (!bInfo)
  87356. return;
  87357. var center = impostor.getObjectCenter();
  87358. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  87359. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  87360. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  87361. this._tmpPosition.copyFrom(center);
  87362. var quaternion = object.rotationQuaternion;
  87363. if (!quaternion) {
  87364. return;
  87365. }
  87366. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  87367. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  87368. //-90 DEG in X, precalculated
  87369. quaternion = quaternion.multiply(this._minus90X);
  87370. //Invert! (Precalculated, 90 deg in X)
  87371. //No need to clone. this will never change.
  87372. impostor.setDeltaRotation(this._plus90X);
  87373. }
  87374. //If it is a heightfield, if should be centered.
  87375. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  87376. var mesh = object;
  87377. var boundingInfo = mesh.getBoundingInfo();
  87378. //calculate the correct body position:
  87379. var rotationQuaternion = mesh.rotationQuaternion;
  87380. mesh.rotationQuaternion = this._tmpUnityRotation;
  87381. mesh.computeWorldMatrix(true);
  87382. //get original center with no rotation
  87383. var c = center.clone();
  87384. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  87385. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  87386. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  87387. mesh.setPreTransformMatrix(p);
  87388. mesh.computeWorldMatrix(true);
  87389. //calculate the translation
  87390. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  87391. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  87392. //add it inverted to the delta
  87393. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  87394. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  87395. //rotation is back
  87396. mesh.rotationQuaternion = rotationQuaternion;
  87397. mesh.setPreTransformMatrix(oldPivot);
  87398. mesh.computeWorldMatrix(true);
  87399. }
  87400. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  87401. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  87402. //this._tmpPosition.copyFrom(object.position);
  87403. }
  87404. impostor.setDeltaPosition(this._tmpDeltaPosition);
  87405. //Now update the impostor object
  87406. impostor.physicsBody.position.copy(this._tmpPosition);
  87407. impostor.physicsBody.quaternion.copy(quaternion);
  87408. };
  87409. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87410. impostor.object.position.copyFrom(impostor.physicsBody.position);
  87411. if (impostor.object.rotationQuaternion) {
  87412. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  87413. }
  87414. };
  87415. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87416. impostor.physicsBody.position.copy(newPosition);
  87417. impostor.physicsBody.quaternion.copy(newRotation);
  87418. };
  87419. CannonJSPlugin.prototype.isSupported = function () {
  87420. return this.BJSCANNON !== undefined;
  87421. };
  87422. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87423. impostor.physicsBody.velocity.copy(velocity);
  87424. };
  87425. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87426. impostor.physicsBody.angularVelocity.copy(velocity);
  87427. };
  87428. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87429. var v = impostor.physicsBody.velocity;
  87430. if (!v) {
  87431. return null;
  87432. }
  87433. return new BABYLON.Vector3(v.x, v.y, v.z);
  87434. };
  87435. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87436. var v = impostor.physicsBody.angularVelocity;
  87437. if (!v) {
  87438. return null;
  87439. }
  87440. return new BABYLON.Vector3(v.x, v.y, v.z);
  87441. };
  87442. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87443. impostor.physicsBody.mass = mass;
  87444. impostor.physicsBody.updateMassProperties();
  87445. };
  87446. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  87447. return impostor.physicsBody.mass;
  87448. };
  87449. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  87450. return impostor.physicsBody.material.friction;
  87451. };
  87452. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87453. impostor.physicsBody.material.friction = friction;
  87454. };
  87455. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87456. return impostor.physicsBody.material.restitution;
  87457. };
  87458. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87459. impostor.physicsBody.material.restitution = restitution;
  87460. };
  87461. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  87462. impostor.physicsBody.sleep();
  87463. };
  87464. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  87465. impostor.physicsBody.wakeUp();
  87466. };
  87467. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87468. joint.physicsJoint.distance = maxDistance;
  87469. };
  87470. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  87471. // if (!motorIndex) {
  87472. // joint.physicsJoint.enableMotor();
  87473. // }
  87474. // }
  87475. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  87476. // if (!motorIndex) {
  87477. // joint.physicsJoint.disableMotor();
  87478. // }
  87479. // }
  87480. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87481. if (!motorIndex) {
  87482. joint.physicsJoint.enableMotor();
  87483. joint.physicsJoint.setMotorSpeed(speed);
  87484. if (maxForce) {
  87485. this.setLimit(joint, maxForce);
  87486. }
  87487. }
  87488. };
  87489. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  87490. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  87491. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  87492. };
  87493. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87494. var body = impostor.physicsBody;
  87495. mesh.position.x = body.position.x;
  87496. mesh.position.y = body.position.y;
  87497. mesh.position.z = body.position.z;
  87498. if (mesh.rotationQuaternion) {
  87499. mesh.rotationQuaternion.x = body.quaternion.x;
  87500. mesh.rotationQuaternion.y = body.quaternion.y;
  87501. mesh.rotationQuaternion.z = body.quaternion.z;
  87502. mesh.rotationQuaternion.w = body.quaternion.w;
  87503. }
  87504. };
  87505. CannonJSPlugin.prototype.getRadius = function (impostor) {
  87506. var shape = impostor.physicsBody.shapes[0];
  87507. return shape.boundingSphereRadius;
  87508. };
  87509. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87510. var shape = impostor.physicsBody.shapes[0];
  87511. result.x = shape.halfExtents.x * 2;
  87512. result.y = shape.halfExtents.y * 2;
  87513. result.z = shape.halfExtents.z * 2;
  87514. };
  87515. CannonJSPlugin.prototype.dispose = function () {
  87516. };
  87517. CannonJSPlugin.prototype._extendNamespace = function () {
  87518. //this will force cannon to execute at least one step when using interpolation
  87519. var step_tmp1 = new this.BJSCANNON.Vec3();
  87520. var Engine = this.BJSCANNON;
  87521. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  87522. maxSubSteps = maxSubSteps || 10;
  87523. timeSinceLastCalled = timeSinceLastCalled || 0;
  87524. if (timeSinceLastCalled === 0) {
  87525. this.internalStep(dt);
  87526. this.time += dt;
  87527. }
  87528. else {
  87529. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  87530. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  87531. var t0 = performance.now();
  87532. for (var i = 0; i !== internalSteps; i++) {
  87533. this.internalStep(dt);
  87534. if (performance.now() - t0 > dt * 1000) {
  87535. break;
  87536. }
  87537. }
  87538. this.time += timeSinceLastCalled;
  87539. var h = this.time % dt;
  87540. var h_div_dt = h / dt;
  87541. var interpvelo = step_tmp1;
  87542. var bodies = this.bodies;
  87543. for (var j = 0; j !== bodies.length; j++) {
  87544. var b = bodies[j];
  87545. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  87546. b.position.vsub(b.previousPosition, interpvelo);
  87547. interpvelo.scale(h_div_dt, interpvelo);
  87548. b.position.vadd(interpvelo, b.interpolatedPosition);
  87549. }
  87550. else {
  87551. b.interpolatedPosition.copy(b.position);
  87552. b.interpolatedQuaternion.copy(b.quaternion);
  87553. }
  87554. }
  87555. }
  87556. };
  87557. };
  87558. return CannonJSPlugin;
  87559. }());
  87560. BABYLON.CannonJSPlugin = CannonJSPlugin;
  87561. })(BABYLON || (BABYLON = {}));
  87562. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  87563. var BABYLON;
  87564. (function (BABYLON) {
  87565. var OimoJSPlugin = /** @class */ (function () {
  87566. function OimoJSPlugin(iterations) {
  87567. this.name = "OimoJSPlugin";
  87568. this._tmpImpostorsArray = [];
  87569. this._tmpPositionVector = BABYLON.Vector3.Zero();
  87570. this.BJSOIMO = OIMO;
  87571. this.world = new this.BJSOIMO.World({
  87572. iterations: iterations
  87573. });
  87574. this.world.clear();
  87575. }
  87576. OimoJSPlugin.prototype.setGravity = function (gravity) {
  87577. this.world.gravity.copy(gravity);
  87578. };
  87579. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  87580. this.world.timeStep = timeStep;
  87581. };
  87582. OimoJSPlugin.prototype.getTimeStep = function () {
  87583. return this.world.timeStep;
  87584. };
  87585. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  87586. var _this = this;
  87587. impostors.forEach(function (impostor) {
  87588. impostor.beforeStep();
  87589. });
  87590. this.world.step();
  87591. impostors.forEach(function (impostor) {
  87592. impostor.afterStep();
  87593. //update the ordered impostors array
  87594. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  87595. });
  87596. //check for collisions
  87597. var contact = this.world.contacts;
  87598. while (contact !== null) {
  87599. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  87600. contact = contact.next;
  87601. continue;
  87602. }
  87603. //is this body colliding with any other? get the impostor
  87604. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  87605. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  87606. if (!mainImpostor || !collidingImpostor) {
  87607. contact = contact.next;
  87608. continue;
  87609. }
  87610. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  87611. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  87612. contact = contact.next;
  87613. }
  87614. };
  87615. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  87616. var mass = impostor.physicsBody.mass;
  87617. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  87618. };
  87619. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  87620. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  87621. this.applyImpulse(impostor, force, contactPoint);
  87622. };
  87623. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  87624. var _this = this;
  87625. //parent-child relationship. Does this impostor has a parent impostor?
  87626. if (impostor.parent) {
  87627. if (impostor.physicsBody) {
  87628. this.removePhysicsBody(impostor);
  87629. //TODO is that needed?
  87630. impostor.forceUpdate();
  87631. }
  87632. return;
  87633. }
  87634. if (impostor.isBodyInitRequired()) {
  87635. var bodyConfig = {
  87636. name: impostor.uniqueId,
  87637. //Oimo must have mass, also for static objects.
  87638. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  87639. size: [],
  87640. type: [],
  87641. pos: [],
  87642. posShape: [],
  87643. rot: [],
  87644. rotShape: [],
  87645. move: impostor.getParam("mass") !== 0,
  87646. density: impostor.getParam("mass"),
  87647. friction: impostor.getParam("friction"),
  87648. restitution: impostor.getParam("restitution"),
  87649. //Supporting older versions of Oimo
  87650. world: this.world
  87651. };
  87652. var impostors = [impostor];
  87653. var addToArray = function (parent) {
  87654. if (!parent.getChildMeshes)
  87655. return;
  87656. parent.getChildMeshes().forEach(function (m) {
  87657. if (m.physicsImpostor) {
  87658. impostors.push(m.physicsImpostor);
  87659. //m.physicsImpostor._init();
  87660. }
  87661. });
  87662. };
  87663. addToArray(impostor.object);
  87664. var checkWithEpsilon_1 = function (value) {
  87665. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  87666. };
  87667. var globalQuaternion_1 = new BABYLON.Quaternion();
  87668. impostors.forEach(function (i) {
  87669. if (!i.object.rotationQuaternion) {
  87670. return;
  87671. }
  87672. //get the correct bounding box
  87673. var oldQuaternion = i.object.rotationQuaternion;
  87674. globalQuaternion_1 = oldQuaternion.clone();
  87675. var rot = oldQuaternion.toEulerAngles();
  87676. var extendSize = i.getObjectExtendSize();
  87677. var radToDeg = 57.295779513082320876;
  87678. if (i === impostor) {
  87679. var center = impostor.getObjectCenter();
  87680. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  87681. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  87682. //Can also use Array.prototype.push.apply
  87683. bodyConfig.pos.push(center.x);
  87684. bodyConfig.pos.push(center.y);
  87685. bodyConfig.pos.push(center.z);
  87686. bodyConfig.posShape.push(0, 0, 0);
  87687. //tmp solution
  87688. bodyConfig.rot.push(0);
  87689. bodyConfig.rot.push(0);
  87690. bodyConfig.rot.push(0);
  87691. bodyConfig.rotShape.push(0, 0, 0);
  87692. }
  87693. else {
  87694. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  87695. bodyConfig.posShape.push(localPosition.x);
  87696. bodyConfig.posShape.push(localPosition.y);
  87697. bodyConfig.posShape.push(localPosition.z);
  87698. bodyConfig.pos.push(0, 0, 0);
  87699. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  87700. bodyConfig.rot.push(0);
  87701. bodyConfig.rot.push(0);
  87702. bodyConfig.rot.push(0);
  87703. bodyConfig.rotShape.push(rot.x * radToDeg);
  87704. bodyConfig.rotShape.push(rot.y * radToDeg);
  87705. bodyConfig.rotShape.push(rot.z * radToDeg);
  87706. }
  87707. // register mesh
  87708. switch (i.type) {
  87709. case BABYLON.PhysicsImpostor.ParticleImpostor:
  87710. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  87711. case BABYLON.PhysicsImpostor.SphereImpostor:
  87712. var radiusX = extendSize.x;
  87713. var radiusY = extendSize.y;
  87714. var radiusZ = extendSize.z;
  87715. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  87716. bodyConfig.type.push('sphere');
  87717. //due to the way oimo works with compounds, add 3 times
  87718. bodyConfig.size.push(size);
  87719. bodyConfig.size.push(size);
  87720. bodyConfig.size.push(size);
  87721. break;
  87722. case BABYLON.PhysicsImpostor.CylinderImpostor:
  87723. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  87724. var sizeY = checkWithEpsilon_1(extendSize.y);
  87725. bodyConfig.type.push('cylinder');
  87726. bodyConfig.size.push(sizeX);
  87727. bodyConfig.size.push(sizeY);
  87728. //due to the way oimo works with compounds, add one more value.
  87729. bodyConfig.size.push(sizeY);
  87730. break;
  87731. case BABYLON.PhysicsImpostor.PlaneImpostor:
  87732. case BABYLON.PhysicsImpostor.BoxImpostor:
  87733. default:
  87734. var sizeX = checkWithEpsilon_1(extendSize.x);
  87735. var sizeY = checkWithEpsilon_1(extendSize.y);
  87736. var sizeZ = checkWithEpsilon_1(extendSize.z);
  87737. bodyConfig.type.push('box');
  87738. //if (i === impostor) {
  87739. bodyConfig.size.push(sizeX);
  87740. bodyConfig.size.push(sizeY);
  87741. bodyConfig.size.push(sizeZ);
  87742. //} else {
  87743. // bodyConfig.size.push(0,0,0);
  87744. //}
  87745. break;
  87746. }
  87747. //actually not needed, but hey...
  87748. i.object.rotationQuaternion = oldQuaternion;
  87749. });
  87750. impostor.physicsBody = this.world.add(bodyConfig);
  87751. // set the quaternion, ignoring the previously defined (euler) rotation
  87752. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  87753. // update with delta 0, so the body will reveive the new rotation.
  87754. impostor.physicsBody.updatePosition(0);
  87755. }
  87756. else {
  87757. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  87758. }
  87759. impostor.setDeltaPosition(this._tmpPositionVector);
  87760. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  87761. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  87762. };
  87763. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  87764. //impostor.physicsBody.dispose();
  87765. //Same as : (older oimo versions)
  87766. this.world.removeRigidBody(impostor.physicsBody);
  87767. };
  87768. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  87769. var mainBody = impostorJoint.mainImpostor.physicsBody;
  87770. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  87771. if (!mainBody || !connectedBody) {
  87772. return;
  87773. }
  87774. var jointData = impostorJoint.joint.jointData;
  87775. var options = jointData.nativeParams || {};
  87776. var type;
  87777. var nativeJointData = {
  87778. body1: mainBody,
  87779. body2: connectedBody,
  87780. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  87781. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  87782. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  87783. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  87784. min: options.min,
  87785. max: options.max,
  87786. collision: options.collision || jointData.collision,
  87787. spring: options.spring,
  87788. //supporting older version of Oimo
  87789. world: this.world
  87790. };
  87791. switch (impostorJoint.joint.type) {
  87792. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87793. type = "jointBall";
  87794. break;
  87795. case BABYLON.PhysicsJoint.SpringJoint:
  87796. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  87797. var springData = jointData;
  87798. nativeJointData.min = springData.length || nativeJointData.min;
  87799. //Max should also be set, just make sure it is at least min
  87800. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  87801. case BABYLON.PhysicsJoint.DistanceJoint:
  87802. type = "jointDistance";
  87803. nativeJointData.max = jointData.maxDistance;
  87804. break;
  87805. case BABYLON.PhysicsJoint.PrismaticJoint:
  87806. type = "jointPrisme";
  87807. break;
  87808. case BABYLON.PhysicsJoint.SliderJoint:
  87809. type = "jointSlide";
  87810. break;
  87811. case BABYLON.PhysicsJoint.WheelJoint:
  87812. type = "jointWheel";
  87813. break;
  87814. case BABYLON.PhysicsJoint.HingeJoint:
  87815. default:
  87816. type = "jointHinge";
  87817. break;
  87818. }
  87819. nativeJointData.type = type;
  87820. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  87821. };
  87822. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87823. //Bug in Oimo prevents us from disposing a joint in the playground
  87824. //joint.joint.physicsJoint.dispose();
  87825. //So we will bruteforce it!
  87826. try {
  87827. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  87828. }
  87829. catch (e) {
  87830. BABYLON.Tools.Warn(e);
  87831. }
  87832. };
  87833. OimoJSPlugin.prototype.isSupported = function () {
  87834. return this.BJSOIMO !== undefined;
  87835. };
  87836. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87837. if (!impostor.physicsBody.sleeping) {
  87838. //TODO check that
  87839. /*if (impostor.physicsBody.shapes.next) {
  87840. var parentShape = this._getLastShape(impostor.physicsBody);
  87841. impostor.object.position.copyFrom(parentShape.position);
  87842. console.log(parentShape.position);
  87843. } else {*/
  87844. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  87845. //}
  87846. if (impostor.object.rotationQuaternion) {
  87847. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  87848. }
  87849. }
  87850. };
  87851. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87852. var body = impostor.physicsBody;
  87853. body.position.copy(newPosition);
  87854. body.orientation.copy(newRotation);
  87855. body.syncShapes();
  87856. body.awake();
  87857. };
  87858. /*private _getLastShape(body: any): any {
  87859. var lastShape = body.shapes;
  87860. while (lastShape.next) {
  87861. lastShape = lastShape.next;
  87862. }
  87863. return lastShape;
  87864. }*/
  87865. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87866. impostor.physicsBody.linearVelocity.copy(velocity);
  87867. };
  87868. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87869. impostor.physicsBody.angularVelocity.copy(velocity);
  87870. };
  87871. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87872. var v = impostor.physicsBody.linearVelocity;
  87873. if (!v) {
  87874. return null;
  87875. }
  87876. return new BABYLON.Vector3(v.x, v.y, v.z);
  87877. };
  87878. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87879. var v = impostor.physicsBody.angularVelocity;
  87880. if (!v) {
  87881. return null;
  87882. }
  87883. return new BABYLON.Vector3(v.x, v.y, v.z);
  87884. };
  87885. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87886. var staticBody = mass === 0;
  87887. //this will actually set the body's density and not its mass.
  87888. //But this is how oimo treats the mass variable.
  87889. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  87890. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  87891. };
  87892. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  87893. return impostor.physicsBody.shapes.density;
  87894. };
  87895. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  87896. return impostor.physicsBody.shapes.friction;
  87897. };
  87898. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87899. impostor.physicsBody.shapes.friction = friction;
  87900. };
  87901. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87902. return impostor.physicsBody.shapes.restitution;
  87903. };
  87904. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87905. impostor.physicsBody.shapes.restitution = restitution;
  87906. };
  87907. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  87908. impostor.physicsBody.sleep();
  87909. };
  87910. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  87911. impostor.physicsBody.awake();
  87912. };
  87913. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87914. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  87915. if (minDistance !== void 0) {
  87916. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  87917. }
  87918. };
  87919. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87920. //TODO separate rotational and transational motors.
  87921. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87922. if (motor) {
  87923. motor.setMotor(speed, maxForce);
  87924. }
  87925. };
  87926. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  87927. //TODO separate rotational and transational motors.
  87928. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87929. if (motor) {
  87930. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  87931. }
  87932. };
  87933. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87934. var body = impostor.physicsBody;
  87935. mesh.position.x = body.position.x;
  87936. mesh.position.y = body.position.y;
  87937. mesh.position.z = body.position.z;
  87938. if (mesh.rotationQuaternion) {
  87939. mesh.rotationQuaternion.x = body.orientation.x;
  87940. mesh.rotationQuaternion.y = body.orientation.y;
  87941. mesh.rotationQuaternion.z = body.orientation.z;
  87942. mesh.rotationQuaternion.w = body.orientation.s;
  87943. }
  87944. };
  87945. OimoJSPlugin.prototype.getRadius = function (impostor) {
  87946. return impostor.physicsBody.shapes.radius;
  87947. };
  87948. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87949. var shape = impostor.physicsBody.shapes;
  87950. result.x = shape.halfWidth * 2;
  87951. result.y = shape.halfHeight * 2;
  87952. result.z = shape.halfDepth * 2;
  87953. };
  87954. OimoJSPlugin.prototype.dispose = function () {
  87955. this.world.clear();
  87956. };
  87957. return OimoJSPlugin;
  87958. }());
  87959. BABYLON.OimoJSPlugin = OimoJSPlugin;
  87960. })(BABYLON || (BABYLON = {}));
  87961. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  87962. var BABYLON;
  87963. (function (BABYLON) {
  87964. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87965. // All values and structures referenced from:
  87966. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87967. var DDS_MAGIC = 0x20534444;
  87968. var
  87969. //DDSD_CAPS = 0x1,
  87970. //DDSD_HEIGHT = 0x2,
  87971. //DDSD_WIDTH = 0x4,
  87972. //DDSD_PITCH = 0x8,
  87973. //DDSD_PIXELFORMAT = 0x1000,
  87974. DDSD_MIPMAPCOUNT = 0x20000;
  87975. //DDSD_LINEARSIZE = 0x80000,
  87976. //DDSD_DEPTH = 0x800000;
  87977. // var DDSCAPS_COMPLEX = 0x8,
  87978. // DDSCAPS_MIPMAP = 0x400000,
  87979. // DDSCAPS_TEXTURE = 0x1000;
  87980. var DDSCAPS2_CUBEMAP = 0x200;
  87981. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87982. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87983. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87984. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87985. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87986. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87987. // DDSCAPS2_VOLUME = 0x200000;
  87988. var
  87989. //DDPF_ALPHAPIXELS = 0x1,
  87990. //DDPF_ALPHA = 0x2,
  87991. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87992. //DDPF_YUV = 0x200,
  87993. DDPF_LUMINANCE = 0x20000;
  87994. function FourCCToInt32(value) {
  87995. return value.charCodeAt(0) +
  87996. (value.charCodeAt(1) << 8) +
  87997. (value.charCodeAt(2) << 16) +
  87998. (value.charCodeAt(3) << 24);
  87999. }
  88000. function Int32ToFourCC(value) {
  88001. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  88002. }
  88003. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  88004. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  88005. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  88006. var FOURCC_DX10 = FourCCToInt32("DX10");
  88007. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  88008. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  88009. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  88010. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  88011. var headerLengthInt = 31; // The header length in 32 bit ints
  88012. // Offsets into the header array
  88013. var off_magic = 0;
  88014. var off_size = 1;
  88015. var off_flags = 2;
  88016. var off_height = 3;
  88017. var off_width = 4;
  88018. var off_mipmapCount = 7;
  88019. var off_pfFlags = 20;
  88020. var off_pfFourCC = 21;
  88021. var off_RGBbpp = 22;
  88022. var off_RMask = 23;
  88023. var off_GMask = 24;
  88024. var off_BMask = 25;
  88025. var off_AMask = 26;
  88026. // var off_caps1 = 27;
  88027. var off_caps2 = 28;
  88028. // var off_caps3 = 29;
  88029. // var off_caps4 = 30;
  88030. var off_dxgiFormat = 32;
  88031. ;
  88032. var DDSTools = /** @class */ (function () {
  88033. function DDSTools() {
  88034. }
  88035. DDSTools.GetDDSInfo = function (arrayBuffer) {
  88036. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  88037. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  88038. var mipmapCount = 1;
  88039. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  88040. mipmapCount = Math.max(1, header[off_mipmapCount]);
  88041. }
  88042. var fourCC = header[off_pfFourCC];
  88043. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  88044. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88045. switch (fourCC) {
  88046. case FOURCC_D3DFMT_R16G16B16A16F:
  88047. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88048. break;
  88049. case FOURCC_D3DFMT_R32G32B32A32F:
  88050. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88051. break;
  88052. case FOURCC_DX10:
  88053. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  88054. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88055. break;
  88056. }
  88057. }
  88058. return {
  88059. width: header[off_width],
  88060. height: header[off_height],
  88061. mipmapCount: mipmapCount,
  88062. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  88063. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  88064. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  88065. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  88066. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  88067. dxgiFormat: dxgiFormat,
  88068. textureType: textureType
  88069. };
  88070. };
  88071. DDSTools._ToHalfFloat = function (value) {
  88072. if (!DDSTools._FloatView) {
  88073. DDSTools._FloatView = new Float32Array(1);
  88074. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  88075. }
  88076. DDSTools._FloatView[0] = value;
  88077. var x = DDSTools._Int32View[0];
  88078. var bits = (x >> 16) & 0x8000; /* Get the sign */
  88079. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  88080. var e = (x >> 23) & 0xff; /* Using int is faster here */
  88081. /* If zero, or denormal, or exponent underflows too much for a denormal
  88082. * half, return signed zero. */
  88083. if (e < 103) {
  88084. return bits;
  88085. }
  88086. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  88087. if (e > 142) {
  88088. bits |= 0x7c00;
  88089. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  88090. * not Inf, so make sure we set one mantissa bit too. */
  88091. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  88092. return bits;
  88093. }
  88094. /* If exponent underflows but not too much, return a denormal */
  88095. if (e < 113) {
  88096. m |= 0x0800;
  88097. /* Extra rounding may overflow and set mantissa to 0 and exponent
  88098. * to 1, which is OK. */
  88099. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  88100. return bits;
  88101. }
  88102. bits |= ((e - 112) << 10) | (m >> 1);
  88103. bits += m & 1;
  88104. return bits;
  88105. };
  88106. DDSTools._FromHalfFloat = function (value) {
  88107. var s = (value & 0x8000) >> 15;
  88108. var e = (value & 0x7C00) >> 10;
  88109. var f = value & 0x03FF;
  88110. if (e === 0) {
  88111. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  88112. }
  88113. else if (e == 0x1F) {
  88114. return f ? NaN : ((s ? -1 : 1) * Infinity);
  88115. }
  88116. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  88117. };
  88118. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88119. var destArray = new Float32Array(dataLength);
  88120. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88121. var index = 0;
  88122. for (var y = 0; y < height; y++) {
  88123. for (var x = 0; x < width; x++) {
  88124. var srcPos = (x + y * width) * 4;
  88125. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  88126. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  88127. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  88128. if (DDSTools.StoreLODInAlphaChannel) {
  88129. destArray[index + 3] = lod;
  88130. }
  88131. else {
  88132. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  88133. }
  88134. index += 4;
  88135. }
  88136. }
  88137. return destArray;
  88138. };
  88139. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88140. if (DDSTools.StoreLODInAlphaChannel) {
  88141. var destArray = new Uint16Array(dataLength);
  88142. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88143. var index = 0;
  88144. for (var y = 0; y < height; y++) {
  88145. for (var x = 0; x < width; x++) {
  88146. var srcPos = (x + y * width) * 4;
  88147. destArray[index] = srcData[srcPos];
  88148. destArray[index + 1] = srcData[srcPos + 1];
  88149. destArray[index + 2] = srcData[srcPos + 2];
  88150. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  88151. index += 4;
  88152. }
  88153. }
  88154. return destArray;
  88155. }
  88156. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  88157. };
  88158. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88159. if (DDSTools.StoreLODInAlphaChannel) {
  88160. var destArray = new Float32Array(dataLength);
  88161. var srcData = new Float32Array(arrayBuffer, dataOffset);
  88162. var index = 0;
  88163. for (var y = 0; y < height; y++) {
  88164. for (var x = 0; x < width; x++) {
  88165. var srcPos = (x + y * width) * 4;
  88166. destArray[index] = srcData[srcPos];
  88167. destArray[index + 1] = srcData[srcPos + 1];
  88168. destArray[index + 2] = srcData[srcPos + 2];
  88169. destArray[index + 3] = lod;
  88170. index += 4;
  88171. }
  88172. }
  88173. return destArray;
  88174. }
  88175. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  88176. };
  88177. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88178. var destArray = new Uint8Array(dataLength);
  88179. var srcData = new Float32Array(arrayBuffer, dataOffset);
  88180. var index = 0;
  88181. for (var y = 0; y < height; y++) {
  88182. for (var x = 0; x < width; x++) {
  88183. var srcPos = (x + y * width) * 4;
  88184. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  88185. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  88186. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  88187. if (DDSTools.StoreLODInAlphaChannel) {
  88188. destArray[index + 3] = lod;
  88189. }
  88190. else {
  88191. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  88192. }
  88193. index += 4;
  88194. }
  88195. }
  88196. return destArray;
  88197. };
  88198. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88199. var destArray = new Uint8Array(dataLength);
  88200. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88201. var index = 0;
  88202. for (var y = 0; y < height; y++) {
  88203. for (var x = 0; x < width; x++) {
  88204. var srcPos = (x + y * width) * 4;
  88205. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  88206. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  88207. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  88208. if (DDSTools.StoreLODInAlphaChannel) {
  88209. destArray[index + 3] = lod;
  88210. }
  88211. else {
  88212. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  88213. }
  88214. index += 4;
  88215. }
  88216. }
  88217. return destArray;
  88218. };
  88219. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  88220. var byteArray = new Uint8Array(dataLength);
  88221. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88222. var index = 0;
  88223. for (var y = 0; y < height; y++) {
  88224. for (var x = 0; x < width; x++) {
  88225. var srcPos = (x + y * width) * 4;
  88226. byteArray[index] = srcData[srcPos + rOffset];
  88227. byteArray[index + 1] = srcData[srcPos + gOffset];
  88228. byteArray[index + 2] = srcData[srcPos + bOffset];
  88229. byteArray[index + 3] = srcData[srcPos + aOffset];
  88230. index += 4;
  88231. }
  88232. }
  88233. return byteArray;
  88234. };
  88235. DDSTools._ExtractLongWordOrder = function (value) {
  88236. if (value === 0 || value === 255 || value === -16777216) {
  88237. return 0;
  88238. }
  88239. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  88240. };
  88241. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  88242. var byteArray = new Uint8Array(dataLength);
  88243. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88244. var index = 0;
  88245. for (var y = 0; y < height; y++) {
  88246. for (var x = 0; x < width; x++) {
  88247. var srcPos = (x + y * width) * 3;
  88248. byteArray[index] = srcData[srcPos + rOffset];
  88249. byteArray[index + 1] = srcData[srcPos + gOffset];
  88250. byteArray[index + 2] = srcData[srcPos + bOffset];
  88251. index += 3;
  88252. }
  88253. }
  88254. return byteArray;
  88255. };
  88256. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  88257. var byteArray = new Uint8Array(dataLength);
  88258. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88259. var index = 0;
  88260. for (var y = 0; y < height; y++) {
  88261. for (var x = 0; x < width; x++) {
  88262. var srcPos = (x + y * width);
  88263. byteArray[index] = srcData[srcPos];
  88264. index++;
  88265. }
  88266. }
  88267. return byteArray;
  88268. };
  88269. /**
  88270. * Uploads DDS Levels to a Babylon Texture
  88271. * @hidden
  88272. */
  88273. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  88274. if (lodIndex === void 0) { lodIndex = -1; }
  88275. var sphericalPolynomialFaces = null;
  88276. if (info.sphericalPolynomial) {
  88277. sphericalPolynomialFaces = new Array();
  88278. }
  88279. var ext = engine.getCaps().s3tc;
  88280. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  88281. var fourCC, width, height, dataLength = 0, dataOffset;
  88282. var byteArray, mipmapCount, mip;
  88283. var internalCompressedFormat = 0;
  88284. var blockBytes = 1;
  88285. if (header[off_magic] !== DDS_MAGIC) {
  88286. BABYLON.Tools.Error("Invalid magic number in DDS header");
  88287. return;
  88288. }
  88289. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  88290. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  88291. return;
  88292. }
  88293. if (info.isCompressed && !ext) {
  88294. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  88295. return;
  88296. }
  88297. var bpp = header[off_RGBbpp];
  88298. dataOffset = header[off_size] + 4;
  88299. var computeFormats = false;
  88300. if (info.isFourCC) {
  88301. fourCC = header[off_pfFourCC];
  88302. switch (fourCC) {
  88303. case FOURCC_DXT1:
  88304. blockBytes = 8;
  88305. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  88306. break;
  88307. case FOURCC_DXT3:
  88308. blockBytes = 16;
  88309. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  88310. break;
  88311. case FOURCC_DXT5:
  88312. blockBytes = 16;
  88313. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  88314. break;
  88315. case FOURCC_D3DFMT_R16G16B16A16F:
  88316. computeFormats = true;
  88317. break;
  88318. case FOURCC_D3DFMT_R32G32B32A32F:
  88319. computeFormats = true;
  88320. break;
  88321. case FOURCC_DX10:
  88322. // There is an additionnal header so dataOffset need to be changed
  88323. dataOffset += 5 * 4; // 5 uints
  88324. var supported = false;
  88325. switch (info.dxgiFormat) {
  88326. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  88327. computeFormats = true;
  88328. supported = true;
  88329. break;
  88330. case DXGI_FORMAT_B8G8R8X8_UNORM:
  88331. info.isRGB = true;
  88332. info.isFourCC = false;
  88333. bpp = 32;
  88334. supported = true;
  88335. break;
  88336. }
  88337. if (supported) {
  88338. break;
  88339. }
  88340. default:
  88341. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  88342. return;
  88343. }
  88344. }
  88345. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  88346. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  88347. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  88348. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  88349. if (computeFormats) {
  88350. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  88351. }
  88352. mipmapCount = 1;
  88353. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  88354. mipmapCount = Math.max(1, header[off_mipmapCount]);
  88355. }
  88356. for (var face = 0; face < faces; face++) {
  88357. width = header[off_width];
  88358. height = header[off_height];
  88359. for (mip = 0; mip < mipmapCount; ++mip) {
  88360. if (lodIndex === -1 || lodIndex === mip) {
  88361. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  88362. var i = (lodIndex === -1) ? mip : 0;
  88363. if (!info.isCompressed && info.isFourCC) {
  88364. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88365. dataLength = width * height * 4;
  88366. var floatArray = null;
  88367. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  88368. if (bpp === 128) {
  88369. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88370. if (sphericalPolynomialFaces && i == 0) {
  88371. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88372. }
  88373. }
  88374. else if (bpp === 64) {
  88375. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88376. if (sphericalPolynomialFaces && i == 0) {
  88377. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88378. }
  88379. }
  88380. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88381. }
  88382. else {
  88383. if (bpp === 128) {
  88384. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88385. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88386. if (sphericalPolynomialFaces && i == 0) {
  88387. sphericalPolynomialFaces.push(floatArray);
  88388. }
  88389. }
  88390. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  88391. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88392. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88393. if (sphericalPolynomialFaces && i == 0) {
  88394. sphericalPolynomialFaces.push(floatArray);
  88395. }
  88396. }
  88397. else { // 64
  88398. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88399. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88400. if (sphericalPolynomialFaces && i == 0) {
  88401. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88402. }
  88403. }
  88404. }
  88405. if (floatArray) {
  88406. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  88407. }
  88408. }
  88409. else if (info.isRGB) {
  88410. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88411. if (bpp === 24) {
  88412. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  88413. dataLength = width * height * 3;
  88414. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  88415. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88416. }
  88417. else { // 32
  88418. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88419. dataLength = width * height * 4;
  88420. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  88421. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88422. }
  88423. }
  88424. else if (info.isLuminance) {
  88425. var unpackAlignment = engine._getUnpackAlignement();
  88426. var unpaddedRowSize = width;
  88427. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  88428. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  88429. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  88430. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  88431. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88432. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88433. }
  88434. else {
  88435. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  88436. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  88437. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88438. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  88439. }
  88440. }
  88441. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  88442. width *= 0.5;
  88443. height *= 0.5;
  88444. width = Math.max(1.0, width);
  88445. height = Math.max(1.0, height);
  88446. }
  88447. if (currentFace !== undefined) {
  88448. // Loading a single face
  88449. break;
  88450. }
  88451. }
  88452. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  88453. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  88454. size: header[off_width],
  88455. right: sphericalPolynomialFaces[0],
  88456. left: sphericalPolynomialFaces[1],
  88457. up: sphericalPolynomialFaces[2],
  88458. down: sphericalPolynomialFaces[3],
  88459. front: sphericalPolynomialFaces[4],
  88460. back: sphericalPolynomialFaces[5],
  88461. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  88462. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  88463. gammaSpace: false,
  88464. });
  88465. }
  88466. else {
  88467. info.sphericalPolynomial = undefined;
  88468. }
  88469. };
  88470. DDSTools.StoreLODInAlphaChannel = false;
  88471. return DDSTools;
  88472. }());
  88473. BABYLON.DDSTools = DDSTools;
  88474. })(BABYLON || (BABYLON = {}));
  88475. //# sourceMappingURL=babylon.dds.js.map
  88476. var BABYLON;
  88477. (function (BABYLON) {
  88478. /**
  88479. * Implementation of the DDS Texture Loader.
  88480. */
  88481. var DDSTextureLoader = /** @class */ (function () {
  88482. function DDSTextureLoader() {
  88483. /**
  88484. * Defines wether the loader supports cascade loading the different faces.
  88485. */
  88486. this.supportCascades = true;
  88487. }
  88488. /**
  88489. * This returns if the loader support the current file information.
  88490. * @param extension defines the file extension of the file being loaded
  88491. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88492. * @param fallback defines the fallback internal texture if any
  88493. * @param isBase64 defines whether the texture is encoded as a base64
  88494. * @param isBuffer defines whether the texture data are stored as a buffer
  88495. * @returns true if the loader can load the specified file
  88496. */
  88497. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88498. return extension.indexOf(".dds") === 0;
  88499. };
  88500. /**
  88501. * Transform the url before loading if required.
  88502. * @param rootUrl the url of the texture
  88503. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88504. * @returns the transformed texture
  88505. */
  88506. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88507. return rootUrl;
  88508. };
  88509. /**
  88510. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88511. * @param rootUrl the url of the texture
  88512. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88513. * @returns the fallback texture
  88514. */
  88515. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88516. return null;
  88517. };
  88518. /**
  88519. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88520. * @param data contains the texture data
  88521. * @param texture defines the BabylonJS internal texture
  88522. * @param createPolynomials will be true if polynomials have been requested
  88523. * @param onLoad defines the callback to trigger once the texture is ready
  88524. * @param onError defines the callback to trigger in case of error
  88525. */
  88526. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  88527. var engine = texture.getEngine();
  88528. var info;
  88529. var loadMipmap = false;
  88530. if (Array.isArray(imgs)) {
  88531. for (var index = 0; index < imgs.length; index++) {
  88532. var data_1 = imgs[index];
  88533. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  88534. texture.width = info.width;
  88535. texture.height = info.height;
  88536. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  88537. engine._unpackFlipY(info.isCompressed);
  88538. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  88539. if (!info.isFourCC && info.mipmapCount === 1) {
  88540. engine.generateMipMapsForCubemap(texture);
  88541. }
  88542. }
  88543. }
  88544. else {
  88545. var data = imgs;
  88546. info = BABYLON.DDSTools.GetDDSInfo(data);
  88547. texture.width = info.width;
  88548. texture.height = info.height;
  88549. if (createPolynomials) {
  88550. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  88551. }
  88552. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  88553. engine._unpackFlipY(info.isCompressed);
  88554. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  88555. if (!info.isFourCC && info.mipmapCount === 1) {
  88556. engine.generateMipMapsForCubemap(texture);
  88557. }
  88558. }
  88559. engine._setCubeMapTextureParams(loadMipmap);
  88560. texture.isReady = true;
  88561. if (onLoad) {
  88562. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  88563. }
  88564. };
  88565. /**
  88566. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88567. * @param data contains the texture data
  88568. * @param texture defines the BabylonJS internal texture
  88569. * @param callback defines the method to call once ready to upload
  88570. */
  88571. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  88572. var info = BABYLON.DDSTools.GetDDSInfo(data);
  88573. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  88574. callback(info.width, info.height, !loadMipmap, info.isFourCC, function () {
  88575. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  88576. });
  88577. };
  88578. return DDSTextureLoader;
  88579. }());
  88580. // Register the loader.
  88581. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  88582. })(BABYLON || (BABYLON = {}));
  88583. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  88584. var BABYLON;
  88585. (function (BABYLON) {
  88586. /*
  88587. * Based on jsTGALoader - Javascript loader for TGA file
  88588. * By Vincent Thibault
  88589. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  88590. */
  88591. var TGATools = /** @class */ (function () {
  88592. function TGATools() {
  88593. }
  88594. TGATools.GetTGAHeader = function (data) {
  88595. var offset = 0;
  88596. var header = {
  88597. id_length: data[offset++],
  88598. colormap_type: data[offset++],
  88599. image_type: data[offset++],
  88600. colormap_index: data[offset++] | data[offset++] << 8,
  88601. colormap_length: data[offset++] | data[offset++] << 8,
  88602. colormap_size: data[offset++],
  88603. origin: [
  88604. data[offset++] | data[offset++] << 8,
  88605. data[offset++] | data[offset++] << 8
  88606. ],
  88607. width: data[offset++] | data[offset++] << 8,
  88608. height: data[offset++] | data[offset++] << 8,
  88609. pixel_size: data[offset++],
  88610. flags: data[offset++]
  88611. };
  88612. return header;
  88613. };
  88614. /**
  88615. * Uploads TGA content to a Babylon Texture
  88616. * @hidden
  88617. */
  88618. TGATools.UploadContent = function (texture, data) {
  88619. // Not enough data to contain header ?
  88620. if (data.length < 19) {
  88621. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  88622. return;
  88623. }
  88624. // Read Header
  88625. var offset = 18;
  88626. var header = TGATools.GetTGAHeader(data);
  88627. // Assume it's a valid Targa file.
  88628. if (header.id_length + offset > data.length) {
  88629. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  88630. return;
  88631. }
  88632. // Skip not needed data
  88633. offset += header.id_length;
  88634. var use_rle = false;
  88635. var use_pal = false;
  88636. var use_grey = false;
  88637. // Get some informations.
  88638. switch (header.image_type) {
  88639. case TGATools._TYPE_RLE_INDEXED:
  88640. use_rle = true;
  88641. case TGATools._TYPE_INDEXED:
  88642. use_pal = true;
  88643. break;
  88644. case TGATools._TYPE_RLE_RGB:
  88645. use_rle = true;
  88646. case TGATools._TYPE_RGB:
  88647. // use_rgb = true;
  88648. break;
  88649. case TGATools._TYPE_RLE_GREY:
  88650. use_rle = true;
  88651. case TGATools._TYPE_GREY:
  88652. use_grey = true;
  88653. break;
  88654. }
  88655. var pixel_data;
  88656. // var numAlphaBits = header.flags & 0xf;
  88657. var pixel_size = header.pixel_size >> 3;
  88658. var pixel_total = header.width * header.height * pixel_size;
  88659. // Read palettes
  88660. var palettes;
  88661. if (use_pal) {
  88662. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  88663. }
  88664. // Read LRE
  88665. if (use_rle) {
  88666. pixel_data = new Uint8Array(pixel_total);
  88667. var c, count, i;
  88668. var localOffset = 0;
  88669. var pixels = new Uint8Array(pixel_size);
  88670. while (offset < pixel_total && localOffset < pixel_total) {
  88671. c = data[offset++];
  88672. count = (c & 0x7f) + 1;
  88673. // RLE pixels
  88674. if (c & 0x80) {
  88675. // Bind pixel tmp array
  88676. for (i = 0; i < pixel_size; ++i) {
  88677. pixels[i] = data[offset++];
  88678. }
  88679. // Copy pixel array
  88680. for (i = 0; i < count; ++i) {
  88681. pixel_data.set(pixels, localOffset + i * pixel_size);
  88682. }
  88683. localOffset += pixel_size * count;
  88684. }
  88685. // Raw pixels
  88686. else {
  88687. count *= pixel_size;
  88688. for (i = 0; i < count; ++i) {
  88689. pixel_data[localOffset + i] = data[offset++];
  88690. }
  88691. localOffset += count;
  88692. }
  88693. }
  88694. }
  88695. // RAW Pixels
  88696. else {
  88697. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  88698. }
  88699. // Load to texture
  88700. var x_start, y_start, x_step, y_step, y_end, x_end;
  88701. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  88702. default:
  88703. case TGATools._ORIGIN_UL:
  88704. x_start = 0;
  88705. x_step = 1;
  88706. x_end = header.width;
  88707. y_start = 0;
  88708. y_step = 1;
  88709. y_end = header.height;
  88710. break;
  88711. case TGATools._ORIGIN_BL:
  88712. x_start = 0;
  88713. x_step = 1;
  88714. x_end = header.width;
  88715. y_start = header.height - 1;
  88716. y_step = -1;
  88717. y_end = -1;
  88718. break;
  88719. case TGATools._ORIGIN_UR:
  88720. x_start = header.width - 1;
  88721. x_step = -1;
  88722. x_end = -1;
  88723. y_start = 0;
  88724. y_step = 1;
  88725. y_end = header.height;
  88726. break;
  88727. case TGATools._ORIGIN_BR:
  88728. x_start = header.width - 1;
  88729. x_step = -1;
  88730. x_end = -1;
  88731. y_start = header.height - 1;
  88732. y_step = -1;
  88733. y_end = -1;
  88734. break;
  88735. }
  88736. // Load the specify method
  88737. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  88738. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  88739. var engine = texture.getEngine();
  88740. engine._uploadDataToTextureDirectly(texture, imageData);
  88741. };
  88742. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88743. var image = pixel_data, colormap = palettes;
  88744. var width = header.width, height = header.height;
  88745. var color, i = 0, x, y;
  88746. var imageData = new Uint8Array(width * height * 4);
  88747. for (y = y_start; y !== y_end; y += y_step) {
  88748. for (x = x_start; x !== x_end; x += x_step, i++) {
  88749. color = image[i];
  88750. imageData[(x + width * y) * 4 + 3] = 255;
  88751. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  88752. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  88753. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  88754. }
  88755. }
  88756. return imageData;
  88757. };
  88758. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88759. var image = pixel_data;
  88760. var width = header.width, height = header.height;
  88761. var color, i = 0, x, y;
  88762. var imageData = new Uint8Array(width * height * 4);
  88763. for (y = y_start; y !== y_end; y += y_step) {
  88764. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88765. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  88766. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  88767. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  88768. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  88769. imageData[(x + width * y) * 4 + 0] = r;
  88770. imageData[(x + width * y) * 4 + 1] = g;
  88771. imageData[(x + width * y) * 4 + 2] = b;
  88772. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  88773. }
  88774. }
  88775. return imageData;
  88776. };
  88777. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88778. var image = pixel_data;
  88779. var width = header.width, height = header.height;
  88780. var i = 0, x, y;
  88781. var imageData = new Uint8Array(width * height * 4);
  88782. for (y = y_start; y !== y_end; y += y_step) {
  88783. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  88784. imageData[(x + width * y) * 4 + 3] = 255;
  88785. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88786. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88787. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88788. }
  88789. }
  88790. return imageData;
  88791. };
  88792. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88793. var image = pixel_data;
  88794. var width = header.width, height = header.height;
  88795. var i = 0, x, y;
  88796. var imageData = new Uint8Array(width * height * 4);
  88797. for (y = y_start; y !== y_end; y += y_step) {
  88798. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  88799. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88800. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88801. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88802. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  88803. }
  88804. }
  88805. return imageData;
  88806. };
  88807. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88808. var image = pixel_data;
  88809. var width = header.width, height = header.height;
  88810. var color, i = 0, x, y;
  88811. var imageData = new Uint8Array(width * height * 4);
  88812. for (y = y_start; y !== y_end; y += y_step) {
  88813. for (x = x_start; x !== x_end; x += x_step, i++) {
  88814. color = image[i];
  88815. imageData[(x + width * y) * 4 + 0] = color;
  88816. imageData[(x + width * y) * 4 + 1] = color;
  88817. imageData[(x + width * y) * 4 + 2] = color;
  88818. imageData[(x + width * y) * 4 + 3] = 255;
  88819. }
  88820. }
  88821. return imageData;
  88822. };
  88823. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88824. var image = pixel_data;
  88825. var width = header.width, height = header.height;
  88826. var i = 0, x, y;
  88827. var imageData = new Uint8Array(width * height * 4);
  88828. for (y = y_start; y !== y_end; y += y_step) {
  88829. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88830. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  88831. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  88832. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88833. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  88834. }
  88835. }
  88836. return imageData;
  88837. };
  88838. //private static _TYPE_NO_DATA = 0;
  88839. TGATools._TYPE_INDEXED = 1;
  88840. TGATools._TYPE_RGB = 2;
  88841. TGATools._TYPE_GREY = 3;
  88842. TGATools._TYPE_RLE_INDEXED = 9;
  88843. TGATools._TYPE_RLE_RGB = 10;
  88844. TGATools._TYPE_RLE_GREY = 11;
  88845. TGATools._ORIGIN_MASK = 0x30;
  88846. TGATools._ORIGIN_SHIFT = 0x04;
  88847. TGATools._ORIGIN_BL = 0x00;
  88848. TGATools._ORIGIN_BR = 0x01;
  88849. TGATools._ORIGIN_UL = 0x02;
  88850. TGATools._ORIGIN_UR = 0x03;
  88851. return TGATools;
  88852. }());
  88853. BABYLON.TGATools = TGATools;
  88854. })(BABYLON || (BABYLON = {}));
  88855. //# sourceMappingURL=babylon.tga.js.map
  88856. var BABYLON;
  88857. (function (BABYLON) {
  88858. /**
  88859. * Implementation of the TGA Texture Loader.
  88860. */
  88861. var TGATextureLoader = /** @class */ (function () {
  88862. function TGATextureLoader() {
  88863. /**
  88864. * Defines wether the loader supports cascade loading the different faces.
  88865. */
  88866. this.supportCascades = false;
  88867. }
  88868. /**
  88869. * This returns if the loader support the current file information.
  88870. * @param extension defines the file extension of the file being loaded
  88871. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88872. * @param fallback defines the fallback internal texture if any
  88873. * @param isBase64 defines whether the texture is encoded as a base64
  88874. * @param isBuffer defines whether the texture data are stored as a buffer
  88875. * @returns true if the loader can load the specified file
  88876. */
  88877. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88878. return extension.indexOf(".tga") === 0;
  88879. };
  88880. /**
  88881. * Transform the url before loading if required.
  88882. * @param rootUrl the url of the texture
  88883. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88884. * @returns the transformed texture
  88885. */
  88886. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88887. return rootUrl;
  88888. };
  88889. /**
  88890. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88891. * @param rootUrl the url of the texture
  88892. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88893. * @returns the fallback texture
  88894. */
  88895. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88896. return null;
  88897. };
  88898. /**
  88899. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88900. * @param data contains the texture data
  88901. * @param texture defines the BabylonJS internal texture
  88902. * @param createPolynomials will be true if polynomials have been requested
  88903. * @param onLoad defines the callback to trigger once the texture is ready
  88904. * @param onError defines the callback to trigger in case of error
  88905. */
  88906. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88907. throw ".env not supported in Cube.";
  88908. };
  88909. /**
  88910. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88911. * @param data contains the texture data
  88912. * @param texture defines the BabylonJS internal texture
  88913. * @param callback defines the method to call once ready to upload
  88914. */
  88915. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  88916. var uintData = new Uint8Array(data);
  88917. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  88918. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  88919. BABYLON.TGATools.UploadContent(texture, uintData);
  88920. });
  88921. };
  88922. return TGATextureLoader;
  88923. }());
  88924. // Register the loader.
  88925. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  88926. })(BABYLON || (BABYLON = {}));
  88927. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  88928. var BABYLON;
  88929. (function (BABYLON) {
  88930. /**
  88931. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  88932. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  88933. */
  88934. var KhronosTextureContainer = /** @class */ (function () {
  88935. /**
  88936. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  88937. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  88938. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  88939. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  88940. */
  88941. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  88942. this.arrayBuffer = arrayBuffer;
  88943. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  88944. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  88945. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  88946. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  88947. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  88948. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  88949. BABYLON.Tools.Error("texture missing KTX identifier");
  88950. return;
  88951. }
  88952. // load the reset of the header in native 32 bit int
  88953. var header = new Int32Array(this.arrayBuffer, 12, 13);
  88954. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  88955. var oppositeEndianess = header[0] === 0x01020304;
  88956. // read all the header elements in order they exist in the file, without modification (sans endainness)
  88957. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  88958. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  88959. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  88960. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  88961. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  88962. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  88963. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  88964. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  88965. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  88966. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  88967. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  88968. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  88969. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  88970. if (this.glType !== 0) {
  88971. BABYLON.Tools.Error("only compressed formats currently supported");
  88972. return;
  88973. }
  88974. else {
  88975. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  88976. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  88977. }
  88978. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  88979. BABYLON.Tools.Error("only 2D textures currently supported");
  88980. return;
  88981. }
  88982. if (this.numberOfArrayElements !== 0) {
  88983. BABYLON.Tools.Error("texture arrays not currently supported");
  88984. return;
  88985. }
  88986. if (this.numberOfFaces !== facesExpected) {
  88987. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  88988. return;
  88989. }
  88990. // we now have a completely validated file, so could use existence of loadType as success
  88991. // would need to make this more elaborate & adjust checks above to support more than one load type
  88992. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  88993. }
  88994. // not as fast hardware based, but will probably never need to use
  88995. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  88996. return ((val & 0xFF) << 24)
  88997. | ((val & 0xFF00) << 8)
  88998. | ((val >> 8) & 0xFF00)
  88999. | ((val >> 24) & 0xFF);
  89000. };
  89001. /**
  89002. * Uploads KTX content to a Babylon Texture.
  89003. * It is assumed that the texture has already been created & is currently bound
  89004. * @hidden
  89005. */
  89006. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  89007. switch (this.loadType) {
  89008. case KhronosTextureContainer.COMPRESSED_2D:
  89009. this._upload2DCompressedLevels(texture, loadMipmaps);
  89010. break;
  89011. case KhronosTextureContainer.TEX_2D:
  89012. case KhronosTextureContainer.COMPRESSED_3D:
  89013. case KhronosTextureContainer.TEX_3D:
  89014. }
  89015. };
  89016. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  89017. // initialize width & height for level 1
  89018. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  89019. var width = this.pixelWidth;
  89020. var height = this.pixelHeight;
  89021. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  89022. for (var level = 0; level < mipmapCount; level++) {
  89023. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  89024. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  89025. for (var face = 0; face < this.numberOfFaces; face++) {
  89026. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  89027. var engine = texture.getEngine();
  89028. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  89029. dataOffset += imageSize; // add size of the image for the next face/mipmap
  89030. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  89031. }
  89032. width = Math.max(1.0, width * 0.5);
  89033. height = Math.max(1.0, height * 0.5);
  89034. }
  89035. };
  89036. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  89037. // load types
  89038. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  89039. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  89040. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  89041. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  89042. return KhronosTextureContainer;
  89043. }());
  89044. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  89045. })(BABYLON || (BABYLON = {}));
  89046. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  89047. var BABYLON;
  89048. (function (BABYLON) {
  89049. /**
  89050. * Implementation of the KTX Texture Loader.
  89051. */
  89052. var KTXTextureLoader = /** @class */ (function () {
  89053. function KTXTextureLoader() {
  89054. /**
  89055. * Defines wether the loader supports cascade loading the different faces.
  89056. */
  89057. this.supportCascades = false;
  89058. }
  89059. /**
  89060. * This returns if the loader support the current file information.
  89061. * @param extension defines the file extension of the file being loaded
  89062. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89063. * @param fallback defines the fallback internal texture if any
  89064. * @param isBase64 defines whether the texture is encoded as a base64
  89065. * @param isBuffer defines whether the texture data are stored as a buffer
  89066. * @returns true if the loader can load the specified file
  89067. */
  89068. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89069. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  89070. return true;
  89071. }
  89072. return false;
  89073. };
  89074. /**
  89075. * Transform the url before loading if required.
  89076. * @param rootUrl the url of the texture
  89077. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89078. * @returns the transformed texture
  89079. */
  89080. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89081. var lastDot = rootUrl.lastIndexOf('.');
  89082. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  89083. };
  89084. /**
  89085. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89086. * @param rootUrl the url of the texture
  89087. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89088. * @returns the fallback texture
  89089. */
  89090. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89091. // remove the format appended to the rootUrl in the original createCubeTexture call.
  89092. var exp = new RegExp("" + textureFormatInUse + "$");
  89093. return rootUrl.replace(exp, "");
  89094. };
  89095. /**
  89096. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89097. * @param data contains the texture data
  89098. * @param texture defines the BabylonJS internal texture
  89099. * @param createPolynomials will be true if polynomials have been requested
  89100. * @param onLoad defines the callback to trigger once the texture is ready
  89101. * @param onError defines the callback to trigger in case of error
  89102. */
  89103. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  89104. if (Array.isArray(data)) {
  89105. return;
  89106. }
  89107. var engine = texture.getEngine();
  89108. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  89109. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  89110. engine._unpackFlipY(true);
  89111. ktx.uploadLevels(texture, texture.generateMipMaps);
  89112. texture.width = ktx.pixelWidth;
  89113. texture.height = ktx.pixelHeight;
  89114. engine._setCubeMapTextureParams(loadMipmap);
  89115. texture.isReady = true;
  89116. };
  89117. /**
  89118. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89119. * @param data contains the texture data
  89120. * @param texture defines the BabylonJS internal texture
  89121. * @param callback defines the method to call once ready to upload
  89122. */
  89123. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  89124. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  89125. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  89126. ktx.uploadLevels(texture, texture.generateMipMaps);
  89127. });
  89128. };
  89129. return KTXTextureLoader;
  89130. }());
  89131. // Register the loader.
  89132. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  89133. })(BABYLON || (BABYLON = {}));
  89134. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  89135. var BABYLON;
  89136. (function (BABYLON) {
  89137. /**
  89138. * Sets of helpers addressing the serialization and deserialization of environment texture
  89139. * stored in a BabylonJS env file.
  89140. * Those files are usually stored as .env files.
  89141. */
  89142. var EnvironmentTextureTools = /** @class */ (function () {
  89143. function EnvironmentTextureTools() {
  89144. }
  89145. /**
  89146. * Gets the environment info from an env file.
  89147. * @param data The array buffer containing the .env bytes.
  89148. * @returns the environment file info (the json header) if successfully parsed.
  89149. */
  89150. EnvironmentTextureTools.GetEnvInfo = function (data) {
  89151. var dataView = new DataView(data);
  89152. var pos = 0;
  89153. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  89154. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  89155. BABYLON.Tools.Error('Not a babylon environment map');
  89156. return null;
  89157. }
  89158. }
  89159. // Read json manifest - collect characters up to null terminator
  89160. var manifestString = '';
  89161. var charCode = 0x00;
  89162. while ((charCode = dataView.getUint8(pos++))) {
  89163. manifestString += String.fromCharCode(charCode);
  89164. }
  89165. var manifest = JSON.parse(manifestString);
  89166. if (manifest.specular) {
  89167. // Extend the header with the position of the payload.
  89168. manifest.specular.specularDataPosition = pos;
  89169. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  89170. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  89171. }
  89172. return manifest;
  89173. };
  89174. /**
  89175. * Creates an environment texture from a loaded cube texture.
  89176. * @param texture defines the cube texture to convert in env file
  89177. * @return a promise containing the environment data if succesfull.
  89178. */
  89179. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  89180. var _this = this;
  89181. var internalTexture = texture.getInternalTexture();
  89182. if (!internalTexture) {
  89183. return Promise.reject("The cube texture is invalid.");
  89184. }
  89185. if (!texture._prefiltered) {
  89186. return Promise.reject("The cube texture is invalid (not prefiltered).");
  89187. }
  89188. var engine = internalTexture.getEngine();
  89189. if (engine && engine.premultipliedAlpha) {
  89190. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  89191. }
  89192. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  89193. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  89194. }
  89195. var canvas = engine.getRenderingCanvas();
  89196. if (!canvas) {
  89197. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  89198. }
  89199. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89200. if (!engine.getCaps().textureFloatRender) {
  89201. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89202. if (!engine.getCaps().textureHalfFloatRender) {
  89203. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  89204. }
  89205. }
  89206. var cubeWidth = internalTexture.width;
  89207. var hostingScene = new BABYLON.Scene(engine);
  89208. var specularTextures = {};
  89209. var promises = [];
  89210. // Read and collect all mipmaps data from the cube.
  89211. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  89212. mipmapsCount = Math.round(mipmapsCount);
  89213. var _loop_1 = function (i) {
  89214. var faceWidth = Math.pow(2, mipmapsCount - i);
  89215. var _loop_2 = function (face) {
  89216. var data = texture.readPixels(face, i);
  89217. // Creates a temp texture with the face data.
  89218. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  89219. // And rgbdEncode them.
  89220. var promise = new Promise(function (resolve, reject) {
  89221. 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);
  89222. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  89223. rgbdPostProcess.onApply = function (effect) {
  89224. effect._bindTexture("textureSampler", tempTexture);
  89225. };
  89226. // As the process needs to happen on the main canvas, keep track of the current size
  89227. var currentW = engine.getRenderWidth();
  89228. var currentH = engine.getRenderHeight();
  89229. // Set the desired size for the texture
  89230. engine.setSize(faceWidth, faceWidth);
  89231. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  89232. // Reading datas from WebGL
  89233. BABYLON.Tools.ToBlob(canvas, function (blob) {
  89234. var fileReader = new FileReader();
  89235. fileReader.onload = function (event) {
  89236. var arrayBuffer = event.target.result;
  89237. specularTextures[i * 6 + face] = arrayBuffer;
  89238. resolve();
  89239. };
  89240. fileReader.readAsArrayBuffer(blob);
  89241. });
  89242. // Reapply the previous canvas size
  89243. engine.setSize(currentW, currentH);
  89244. });
  89245. });
  89246. promises.push(promise);
  89247. };
  89248. // All faces of the cube.
  89249. for (var face = 0; face < 6; face++) {
  89250. _loop_2(face);
  89251. }
  89252. };
  89253. for (var i = 0; i <= mipmapsCount; i++) {
  89254. _loop_1(i);
  89255. }
  89256. // Once all the textures haves been collected as RGBD stored in PNGs
  89257. return Promise.all(promises).then(function () {
  89258. // We can delete the hosting scene keeping track of all the creation objects
  89259. hostingScene.dispose();
  89260. // Creates the json header for the env texture
  89261. var info = {
  89262. version: 1,
  89263. width: cubeWidth,
  89264. irradiance: _this._CreateEnvTextureIrradiance(texture),
  89265. specular: {
  89266. mipmaps: [],
  89267. lodGenerationScale: texture.lodGenerationScale
  89268. }
  89269. };
  89270. // Sets the specular image data information
  89271. var position = 0;
  89272. for (var i = 0; i <= mipmapsCount; i++) {
  89273. for (var face = 0; face < 6; face++) {
  89274. var byteLength = specularTextures[i * 6 + face].byteLength;
  89275. info.specular.mipmaps.push({
  89276. length: byteLength,
  89277. position: position
  89278. });
  89279. position += byteLength;
  89280. }
  89281. }
  89282. // Encode the JSON as an array buffer
  89283. var infoString = JSON.stringify(info);
  89284. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  89285. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  89286. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  89287. infoView[i] = infoString.charCodeAt(i);
  89288. }
  89289. // Ends up with a null terminator for easier parsing
  89290. infoView[infoString.length] = 0x00;
  89291. // Computes the final required size and creates the storage
  89292. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  89293. var finalBuffer = new ArrayBuffer(totalSize);
  89294. var finalBufferView = new Uint8Array(finalBuffer);
  89295. var dataView = new DataView(finalBuffer);
  89296. // Copy the magic bytes identifying the file in
  89297. var pos = 0;
  89298. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  89299. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  89300. }
  89301. // Add the json info
  89302. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  89303. pos += infoBuffer.byteLength;
  89304. // Finally inserts the texture data
  89305. for (var i = 0; i <= mipmapsCount; i++) {
  89306. for (var face = 0; face < 6; face++) {
  89307. var dataBuffer = specularTextures[i * 6 + face];
  89308. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  89309. pos += dataBuffer.byteLength;
  89310. }
  89311. }
  89312. // Voila
  89313. return finalBuffer;
  89314. });
  89315. };
  89316. /**
  89317. * Creates a JSON representation of the spherical data.
  89318. * @param texture defines the texture containing the polynomials
  89319. * @return the JSON representation of the spherical info
  89320. */
  89321. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  89322. var polynmials = texture.sphericalPolynomial;
  89323. if (polynmials == null) {
  89324. return null;
  89325. }
  89326. return {
  89327. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  89328. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  89329. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  89330. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  89331. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  89332. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  89333. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  89334. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  89335. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  89336. };
  89337. };
  89338. /**
  89339. * Uploads the texture info contained in the env file to the GPU.
  89340. * @param texture defines the internal texture to upload to
  89341. * @param arrayBuffer defines the buffer cotaining the data to load
  89342. * @param info defines the texture info retrieved through the GetEnvInfo method
  89343. * @returns a promise
  89344. */
  89345. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  89346. if (info.version !== 1) {
  89347. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  89348. }
  89349. var specularInfo = info.specular;
  89350. if (!specularInfo) {
  89351. // Nothing else parsed so far
  89352. return Promise.resolve();
  89353. }
  89354. // Double checks the enclosed info
  89355. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  89356. mipmapsCount = Math.round(mipmapsCount) + 1;
  89357. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  89358. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  89359. }
  89360. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  89361. var imageData = new Array(mipmapsCount);
  89362. for (var i = 0; i < mipmapsCount; i++) {
  89363. imageData[i] = new Array(6);
  89364. for (var face = 0; face < 6; face++) {
  89365. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  89366. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  89367. }
  89368. }
  89369. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  89370. };
  89371. /**
  89372. * Uploads the levels of image data to the GPU.
  89373. * @param texture defines the internal texture to upload to
  89374. * @param imageData defines the array buffer views of image data [mipmap][face]
  89375. * @returns a promise
  89376. */
  89377. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  89378. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  89379. throw new Error("Texture size must be a power of two");
  89380. }
  89381. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  89382. // Gets everything ready.
  89383. var engine = texture.getEngine();
  89384. var expandTexture = false;
  89385. var generateNonLODTextures = false;
  89386. var rgbdPostProcess = null;
  89387. var cubeRtt = null;
  89388. var lodTextures = null;
  89389. var caps = engine.getCaps();
  89390. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89391. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89392. texture.generateMipMaps = true;
  89393. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  89394. // Add extra process if texture lod is not supported
  89395. if (!caps.textureLOD) {
  89396. expandTexture = false;
  89397. generateNonLODTextures = true;
  89398. lodTextures = {};
  89399. }
  89400. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  89401. else if (engine.webGLVersion < 2) {
  89402. expandTexture = false;
  89403. }
  89404. // If half float available we can uncompress the texture
  89405. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  89406. expandTexture = true;
  89407. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89408. }
  89409. // If full float available we can uncompress the texture
  89410. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  89411. expandTexture = true;
  89412. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89413. }
  89414. // Expand the texture if possible
  89415. if (expandTexture) {
  89416. // Simply run through the decode PP
  89417. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  89418. texture._isRGBD = false;
  89419. texture.invertY = false;
  89420. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  89421. generateDepthBuffer: false,
  89422. generateMipMaps: true,
  89423. generateStencilBuffer: false,
  89424. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  89425. type: texture.type,
  89426. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  89427. });
  89428. }
  89429. else {
  89430. texture._isRGBD = true;
  89431. texture.invertY = true;
  89432. // In case of missing support, applies the same patch than DDS files.
  89433. if (generateNonLODTextures) {
  89434. var mipSlices = 3;
  89435. var scale = texture._lodGenerationScale;
  89436. var offset = texture._lodGenerationOffset;
  89437. for (var i = 0; i < mipSlices; i++) {
  89438. //compute LOD from even spacing in smoothness (matching shader calculation)
  89439. var smoothness = i / (mipSlices - 1);
  89440. var roughness = 1 - smoothness;
  89441. var minLODIndex = offset; // roughness = 0
  89442. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  89443. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  89444. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  89445. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  89446. glTextureFromLod.isCube = true;
  89447. glTextureFromLod.invertY = true;
  89448. glTextureFromLod.generateMipMaps = false;
  89449. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  89450. // Wrap in a base texture for easy binding.
  89451. var lodTexture = new BABYLON.BaseTexture(null);
  89452. lodTexture.isCube = true;
  89453. lodTexture._texture = glTextureFromLod;
  89454. lodTextures[mipmapIndex] = lodTexture;
  89455. switch (i) {
  89456. case 0:
  89457. texture._lodTextureLow = lodTexture;
  89458. break;
  89459. case 1:
  89460. texture._lodTextureMid = lodTexture;
  89461. break;
  89462. case 2:
  89463. texture._lodTextureHigh = lodTexture;
  89464. break;
  89465. }
  89466. }
  89467. }
  89468. }
  89469. var promises = [];
  89470. var _loop_3 = function (i) {
  89471. var _loop_4 = function (face) {
  89472. // Constructs an image element from image data
  89473. var bytes = imageData[i][face];
  89474. var blob = new Blob([bytes], { type: 'image/png' });
  89475. var url = URL.createObjectURL(blob);
  89476. var image = new Image();
  89477. image.src = url;
  89478. // Enqueue promise to upload to the texture.
  89479. var promise = new Promise(function (resolve, reject) {
  89480. image.onload = function () {
  89481. if (expandTexture) {
  89482. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  89483. reject(message);
  89484. }, image);
  89485. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  89486. // Uncompress the data to a RTT
  89487. rgbdPostProcess.onApply = function (effect) {
  89488. effect._bindTexture("textureSampler", tempTexture_1);
  89489. effect.setFloat2("scale", 1, 1);
  89490. };
  89491. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  89492. // Cleanup
  89493. engine.restoreDefaultFramebuffer();
  89494. tempTexture_1.dispose();
  89495. window.URL.revokeObjectURL(url);
  89496. resolve();
  89497. });
  89498. }
  89499. else {
  89500. engine._uploadImageToTexture(texture, image, face, i);
  89501. // Upload the face to the non lod texture support
  89502. if (generateNonLODTextures) {
  89503. var lodTexture = lodTextures[i];
  89504. if (lodTexture) {
  89505. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  89506. }
  89507. }
  89508. resolve();
  89509. }
  89510. };
  89511. image.onerror = function (error) {
  89512. reject(error);
  89513. };
  89514. });
  89515. promises.push(promise);
  89516. };
  89517. // All faces
  89518. for (var face = 0; face < 6; face++) {
  89519. _loop_4(face);
  89520. }
  89521. };
  89522. // All mipmaps up to provided number of images
  89523. for (var i = 0; i < imageData.length; i++) {
  89524. _loop_3(i);
  89525. }
  89526. // Fill remaining mipmaps with black textures.
  89527. if (imageData.length < mipmapsCount) {
  89528. var data = void 0;
  89529. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  89530. var dataLength = size * size * 4;
  89531. switch (texture.type) {
  89532. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  89533. data = new Uint8Array(dataLength);
  89534. break;
  89535. }
  89536. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  89537. data = new Uint16Array(dataLength);
  89538. break;
  89539. }
  89540. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  89541. data = new Float32Array(dataLength);
  89542. break;
  89543. }
  89544. }
  89545. for (var i = imageData.length; i < mipmapsCount; i++) {
  89546. for (var face = 0; face < 6; face++) {
  89547. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  89548. }
  89549. }
  89550. }
  89551. // Once all done, finishes the cleanup and return
  89552. return Promise.all(promises).then(function () {
  89553. // Release temp RTT.
  89554. if (cubeRtt) {
  89555. engine._releaseFramebufferObjects(cubeRtt);
  89556. cubeRtt._swapAndDie(texture);
  89557. }
  89558. // Release temp Post Process.
  89559. if (rgbdPostProcess) {
  89560. rgbdPostProcess.dispose();
  89561. }
  89562. // Flag internal texture as ready in case they are in use.
  89563. if (generateNonLODTextures) {
  89564. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  89565. texture._lodTextureHigh._texture.isReady = true;
  89566. }
  89567. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  89568. texture._lodTextureMid._texture.isReady = true;
  89569. }
  89570. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  89571. texture._lodTextureLow._texture.isReady = true;
  89572. }
  89573. }
  89574. });
  89575. };
  89576. /**
  89577. * Uploads spherical polynomials information to the texture.
  89578. * @param texture defines the texture we are trying to upload the information to
  89579. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  89580. */
  89581. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  89582. if (info.version !== 1) {
  89583. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  89584. }
  89585. var irradianceInfo = info.irradiance;
  89586. if (!irradianceInfo) {
  89587. return;
  89588. }
  89589. var sp = new BABYLON.SphericalPolynomial();
  89590. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  89591. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  89592. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  89593. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  89594. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  89595. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  89596. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  89597. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  89598. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  89599. texture._sphericalPolynomial = sp;
  89600. };
  89601. /**
  89602. * Magic number identifying the env file.
  89603. */
  89604. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  89605. return EnvironmentTextureTools;
  89606. }());
  89607. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  89608. })(BABYLON || (BABYLON = {}));
  89609. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  89610. var BABYLON;
  89611. (function (BABYLON) {
  89612. /**
  89613. * Implementation of the ENV Texture Loader.
  89614. */
  89615. var ENVTextureLoader = /** @class */ (function () {
  89616. function ENVTextureLoader() {
  89617. /**
  89618. * Defines wether the loader supports cascade loading the different faces.
  89619. */
  89620. this.supportCascades = false;
  89621. }
  89622. /**
  89623. * This returns if the loader support the current file information.
  89624. * @param extension defines the file extension of the file being loaded
  89625. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89626. * @param fallback defines the fallback internal texture if any
  89627. * @param isBase64 defines whether the texture is encoded as a base64
  89628. * @param isBuffer defines whether the texture data are stored as a buffer
  89629. * @returns true if the loader can load the specified file
  89630. */
  89631. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89632. return extension.indexOf(".env") === 0;
  89633. };
  89634. /**
  89635. * Transform the url before loading if required.
  89636. * @param rootUrl the url of the texture
  89637. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89638. * @returns the transformed texture
  89639. */
  89640. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89641. return rootUrl;
  89642. };
  89643. /**
  89644. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89645. * @param rootUrl the url of the texture
  89646. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89647. * @returns the fallback texture
  89648. */
  89649. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89650. return null;
  89651. };
  89652. /**
  89653. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89654. * @param data contains the texture data
  89655. * @param texture defines the BabylonJS internal texture
  89656. * @param createPolynomials will be true if polynomials have been requested
  89657. * @param onLoad defines the callback to trigger once the texture is ready
  89658. * @param onError defines the callback to trigger in case of error
  89659. */
  89660. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  89661. if (Array.isArray(data)) {
  89662. return;
  89663. }
  89664. data = data;
  89665. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  89666. if (info) {
  89667. texture.width = info.width;
  89668. texture.height = info.width;
  89669. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  89670. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  89671. texture.isReady = true;
  89672. if (onLoad) {
  89673. onLoad();
  89674. }
  89675. });
  89676. }
  89677. else if (onError) {
  89678. onError("Can not parse the environment file", null);
  89679. }
  89680. };
  89681. /**
  89682. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89683. * @param data contains the texture data
  89684. * @param texture defines the BabylonJS internal texture
  89685. * @param callback defines the method to call once ready to upload
  89686. */
  89687. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  89688. throw ".env not supported in 2d.";
  89689. };
  89690. return ENVTextureLoader;
  89691. }());
  89692. // Register the loader.
  89693. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  89694. })(BABYLON || (BABYLON = {}));
  89695. //# sourceMappingURL=babylon.envTextureLoader.js.map
  89696. var BABYLON;
  89697. (function (BABYLON) {
  89698. /**
  89699. * Renders a layer on top of an existing scene
  89700. */
  89701. var UtilityLayerRenderer = /** @class */ (function () {
  89702. /**
  89703. * Instantiates a UtilityLayerRenderer
  89704. * @param originalScene the original scene that will be rendered on top of
  89705. */
  89706. function UtilityLayerRenderer(
  89707. /** the original scene that will be rendered on top of */
  89708. originalScene) {
  89709. var _this = this;
  89710. this.originalScene = originalScene;
  89711. this._pointerCaptures = {};
  89712. this._lastPointerEvents = {};
  89713. /**
  89714. * If the utility layer should automatically be rendered on top of existing scene
  89715. */
  89716. this.shouldRender = true;
  89717. /**
  89718. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  89719. */
  89720. this.onlyCheckPointerDownEvents = true;
  89721. /**
  89722. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  89723. */
  89724. this.processAllEvents = false;
  89725. /**
  89726. * Observable raised when the pointer move from the utility layer scene to the main scene
  89727. */
  89728. this.onPointerOutObservable = new BABYLON.Observable();
  89729. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  89730. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  89731. this.utilityLayerScene._allowPostProcessClear = false;
  89732. originalScene.getEngine().scenes.pop();
  89733. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  89734. this.utilityLayerScene.detachControl();
  89735. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  89736. if (!_this.processAllEvents) {
  89737. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  89738. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  89739. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  89740. return;
  89741. }
  89742. }
  89743. var pointerEvent = (prePointerInfo.event);
  89744. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  89745. _this._pointerCaptures[pointerEvent.pointerId] = false;
  89746. return;
  89747. }
  89748. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  89749. if (!prePointerInfo.ray && utilityScenePick) {
  89750. prePointerInfo.ray = utilityScenePick.ray;
  89751. }
  89752. // always fire the prepointer oversvable
  89753. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  89754. // allow every non pointer down event to flow to the utility layer
  89755. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  89756. if (!prePointerInfo.skipOnPointerObservable) {
  89757. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  89758. }
  89759. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  89760. _this._pointerCaptures[pointerEvent.pointerId] = false;
  89761. }
  89762. return;
  89763. }
  89764. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  89765. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  89766. if (utilityScenePick && utilityScenePick.hit) {
  89767. if (!prePointerInfo.skipOnPointerObservable) {
  89768. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  89769. }
  89770. prePointerInfo.skipOnPointerObservable = true;
  89771. }
  89772. }
  89773. else {
  89774. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  89775. var pointerEvent_1 = (prePointerInfo.event);
  89776. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  89777. if (originalScenePick && utilityScenePick) {
  89778. // No pick in utility scene
  89779. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  89780. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89781. // We touched an utility mesh present in the main scene
  89782. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89783. prePointerInfo.skipOnPointerObservable = true;
  89784. }
  89785. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89786. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  89787. }
  89788. }
  89789. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  89790. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  89791. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  89792. // If a previous utility layer set this, do not unset this
  89793. if (!prePointerInfo.skipOnPointerObservable) {
  89794. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  89795. }
  89796. }
  89797. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  89798. // We have a pick in both scenes but main is closer than utility
  89799. // We touched an utility mesh present in the main scene
  89800. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89801. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89802. prePointerInfo.skipOnPointerObservable = true;
  89803. }
  89804. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  89805. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  89806. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  89807. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  89808. }
  89809. }
  89810. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  89811. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  89812. }
  89813. }
  89814. }
  89815. });
  89816. // Render directly on top of existing scene without clearing
  89817. this.utilityLayerScene.autoClear = false;
  89818. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  89819. if (_this.shouldRender) {
  89820. _this.render();
  89821. }
  89822. });
  89823. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  89824. _this.dispose();
  89825. });
  89826. this._updateCamera();
  89827. }
  89828. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  89829. /**
  89830. * 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)
  89831. */
  89832. get: function () {
  89833. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  89834. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89835. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89836. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89837. });
  89838. }
  89839. return UtilityLayerRenderer._DefaultUtilityLayer;
  89840. },
  89841. enumerable: true,
  89842. configurable: true
  89843. });
  89844. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  89845. /**
  89846. * 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)
  89847. */
  89848. get: function () {
  89849. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  89850. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89851. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  89852. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89853. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89854. });
  89855. }
  89856. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  89857. },
  89858. enumerable: true,
  89859. configurable: true
  89860. });
  89861. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  89862. if (!prePointerInfo.skipOnPointerObservable) {
  89863. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  89864. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  89865. }
  89866. };
  89867. /**
  89868. * Renders the utility layers scene on top of the original scene
  89869. */
  89870. UtilityLayerRenderer.prototype.render = function () {
  89871. this._updateCamera();
  89872. if (this.utilityLayerScene.activeCamera) {
  89873. // Set the camera's scene to utility layers scene
  89874. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  89875. var camera = this.utilityLayerScene.activeCamera;
  89876. camera._scene = this.utilityLayerScene;
  89877. if (camera.leftCamera) {
  89878. camera.leftCamera._scene = this.utilityLayerScene;
  89879. }
  89880. if (camera.rightCamera) {
  89881. camera.rightCamera._scene = this.utilityLayerScene;
  89882. }
  89883. this.utilityLayerScene.render(false);
  89884. // Reset camera's scene back to original
  89885. camera._scene = oldScene;
  89886. if (camera.leftCamera) {
  89887. camera.leftCamera._scene = oldScene;
  89888. }
  89889. if (camera.rightCamera) {
  89890. camera.rightCamera._scene = oldScene;
  89891. }
  89892. }
  89893. };
  89894. /**
  89895. * Disposes of the renderer
  89896. */
  89897. UtilityLayerRenderer.prototype.dispose = function () {
  89898. this.onPointerOutObservable.clear();
  89899. if (this._afterRenderObserver) {
  89900. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  89901. }
  89902. if (this._sceneDisposeObserver) {
  89903. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89904. }
  89905. if (this._originalPointerObserver) {
  89906. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  89907. }
  89908. this.utilityLayerScene.dispose();
  89909. };
  89910. UtilityLayerRenderer.prototype._updateCamera = function () {
  89911. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  89912. };
  89913. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89914. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89915. return UtilityLayerRenderer;
  89916. }());
  89917. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  89918. })(BABYLON || (BABYLON = {}));
  89919. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  89920. //# sourceMappingURL=babylon.behavior.js.map
  89921. var BABYLON;
  89922. (function (BABYLON) {
  89923. /**
  89924. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  89925. */
  89926. var PointerDragBehavior = /** @class */ (function () {
  89927. /**
  89928. * Creates a pointer drag behavior that can be attached to a mesh
  89929. * @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)
  89930. */
  89931. function PointerDragBehavior(options) {
  89932. /**
  89933. * 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)
  89934. */
  89935. this.maxDragAngle = 0;
  89936. /**
  89937. * @hidden
  89938. */
  89939. this._useAlternatePickedPointAboveMaxDragAngle = false;
  89940. /**
  89941. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89942. */
  89943. this.currentDraggingPointerID = -1;
  89944. /**
  89945. * If the behavior is currently in a dragging state
  89946. */
  89947. this.dragging = false;
  89948. /**
  89949. * 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)
  89950. */
  89951. this.dragDeltaRatio = 0.2;
  89952. /**
  89953. * If the drag plane orientation should be updated during the dragging (Default: true)
  89954. */
  89955. this.updateDragPlane = true;
  89956. // Debug mode will display drag planes to help visualize behavior
  89957. this._debugMode = false;
  89958. this._moving = false;
  89959. /**
  89960. * Fires each time the attached mesh is dragged with the pointer
  89961. * * delta between last drag position and current drag position in world space
  89962. * * dragDistance along the drag axis
  89963. * * dragPlaneNormal normal of the current drag plane used during the drag
  89964. * * dragPlanePoint in world space where the drag intersects the drag plane
  89965. */
  89966. this.onDragObservable = new BABYLON.Observable();
  89967. /**
  89968. * Fires each time a drag begins (eg. mouse down on mesh)
  89969. */
  89970. this.onDragStartObservable = new BABYLON.Observable();
  89971. /**
  89972. * Fires each time a drag ends (eg. mouse release after drag)
  89973. */
  89974. this.onDragEndObservable = new BABYLON.Observable();
  89975. /**
  89976. * If the attached mesh should be moved when dragged
  89977. */
  89978. this.moveAttached = true;
  89979. /**
  89980. * If the drag behavior will react to drag events (Default: true)
  89981. */
  89982. this.enabled = true;
  89983. /**
  89984. * If camera controls should be detached during the drag
  89985. */
  89986. this.detachCameraControls = true;
  89987. /**
  89988. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  89989. */
  89990. this.useObjectOrienationForDragging = true;
  89991. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89992. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  89993. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  89994. // Variables to avoid instantiation in the below method
  89995. this._pointA = new BABYLON.Vector3(0, 0, 0);
  89996. this._pointB = new BABYLON.Vector3(0, 0, 0);
  89997. this._pointC = new BABYLON.Vector3(0, 0, 0);
  89998. this._lineA = new BABYLON.Vector3(0, 0, 0);
  89999. this._lineB = new BABYLON.Vector3(0, 0, 0);
  90000. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  90001. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  90002. this._options = options ? options : {};
  90003. var optionCount = 0;
  90004. if (this._options.dragAxis) {
  90005. optionCount++;
  90006. }
  90007. if (this._options.dragPlaneNormal) {
  90008. optionCount++;
  90009. }
  90010. if (optionCount > 1) {
  90011. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  90012. }
  90013. }
  90014. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  90015. /**
  90016. * The name of the behavior
  90017. */
  90018. get: function () {
  90019. return "PointerDrag";
  90020. },
  90021. enumerable: true,
  90022. configurable: true
  90023. });
  90024. /**
  90025. * Initializes the behavior
  90026. */
  90027. PointerDragBehavior.prototype.init = function () { };
  90028. /**
  90029. * Attaches the drag behavior the passed in mesh
  90030. * @param ownerNode The mesh that will be dragged around once attached
  90031. */
  90032. PointerDragBehavior.prototype.attach = function (ownerNode) {
  90033. var _this = this;
  90034. this._scene = ownerNode.getScene();
  90035. this._attachedNode = ownerNode;
  90036. // Initialize drag plane to not interfere with existing scene
  90037. if (!PointerDragBehavior._planeScene) {
  90038. if (this._debugMode) {
  90039. PointerDragBehavior._planeScene = this._scene;
  90040. }
  90041. else {
  90042. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  90043. PointerDragBehavior._planeScene.detachControl();
  90044. this._scene.getEngine().scenes.pop();
  90045. this._scene.onDisposeObservable.addOnce(function () {
  90046. PointerDragBehavior._planeScene.dispose();
  90047. PointerDragBehavior._planeScene = null;
  90048. });
  90049. }
  90050. }
  90051. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  90052. // State of the drag
  90053. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  90054. var delta = new BABYLON.Vector3(0, 0, 0);
  90055. var dragLength = 0;
  90056. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  90057. var pickPredicate = function (m) {
  90058. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  90059. };
  90060. var attachedElement = null;
  90061. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  90062. if (!_this.enabled) {
  90063. return;
  90064. }
  90065. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90066. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  90067. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  90068. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  90069. if (pickedPoint) {
  90070. _this.dragging = true;
  90071. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  90072. _this.lastDragPosition.copyFrom(pickedPoint);
  90073. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  90074. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  90075. // Detatch camera controls
  90076. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90077. if (_this._scene.activeCamera.inputs.attachedElement) {
  90078. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  90079. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  90080. }
  90081. else {
  90082. attachedElement = null;
  90083. }
  90084. }
  90085. }
  90086. }
  90087. }
  90088. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  90089. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  90090. _this.releaseDrag();
  90091. // Reattach camera controls
  90092. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90093. _this._scene.activeCamera.attachControl(attachedElement, true);
  90094. }
  90095. }
  90096. }
  90097. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  90098. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  90099. _this._moving = true;
  90100. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  90101. if (pickedPoint) {
  90102. if (_this.updateDragPlane) {
  90103. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  90104. }
  90105. // depending on the drag mode option drag accordingly
  90106. if (_this._options.dragAxis) {
  90107. // Convert local drag axis to world
  90108. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  90109. // Project delta drag from the drag plane onto the drag axis
  90110. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  90111. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  90112. _this._worldDragAxis.scaleToRef(dragLength, delta);
  90113. }
  90114. else {
  90115. dragLength = delta.length();
  90116. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  90117. }
  90118. targetPosition.addInPlace(delta);
  90119. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  90120. _this.lastDragPosition.copyFrom(pickedPoint);
  90121. }
  90122. }
  90123. }
  90124. });
  90125. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  90126. if (_this._moving && _this.moveAttached) {
  90127. // Slowly move mesh to avoid jitter
  90128. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  90129. _this._tmpVector.scaleInPlace(0.2);
  90130. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  90131. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  90132. }
  90133. });
  90134. };
  90135. PointerDragBehavior.prototype.releaseDrag = function () {
  90136. this.dragging = false;
  90137. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  90138. this.currentDraggingPointerID = -1;
  90139. this._moving = false;
  90140. };
  90141. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  90142. var _this = this;
  90143. if (!ray) {
  90144. return null;
  90145. }
  90146. // Calculate angle between plane normal and ray
  90147. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  90148. // Correct if ray is casted from oposite side
  90149. if (angle > Math.PI / 2) {
  90150. angle = Math.PI - angle;
  90151. }
  90152. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  90153. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  90154. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  90155. // Invert ray direction along the towards object axis
  90156. this._tmpVector.copyFrom(ray.direction);
  90157. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  90158. this._alternatePickedPoint.normalize();
  90159. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  90160. this._tmpVector.addInPlace(this._alternatePickedPoint);
  90161. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  90162. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  90163. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  90164. this._alternatePickedPoint.addInPlace(this._tmpVector);
  90165. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  90166. return this._alternatePickedPoint;
  90167. }
  90168. else {
  90169. return null;
  90170. }
  90171. }
  90172. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  90173. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  90174. return pickResult.pickedPoint;
  90175. }
  90176. else {
  90177. return null;
  90178. }
  90179. };
  90180. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  90181. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  90182. this._pointA.copyFrom(dragPlanePosition);
  90183. if (this._options.dragAxis) {
  90184. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  90185. // Calculate plane normal in direction of camera but perpendicular to drag axis
  90186. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  90187. ray.origin.subtractToRef(this._pointA, this._pointC);
  90188. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  90189. // Get perpendicular line from direction to camera and drag axis
  90190. this._pointB.subtractToRef(this._pointA, this._lineA);
  90191. this._pointC.subtractToRef(this._pointA, this._lineB);
  90192. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  90193. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  90194. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  90195. this._lookAt.normalize();
  90196. this._dragPlane.position.copyFrom(this._pointA);
  90197. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  90198. this._dragPlane.lookAt(this._lookAt);
  90199. }
  90200. else if (this._options.dragPlaneNormal) {
  90201. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  90202. this._dragPlane.position.copyFrom(this._pointA);
  90203. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  90204. this._dragPlane.lookAt(this._lookAt);
  90205. }
  90206. else {
  90207. this._dragPlane.position.copyFrom(this._pointA);
  90208. this._dragPlane.lookAt(ray.origin);
  90209. }
  90210. this._dragPlane.computeWorldMatrix(true);
  90211. };
  90212. /**
  90213. * Detaches the behavior from the mesh
  90214. */
  90215. PointerDragBehavior.prototype.detach = function () {
  90216. if (this._pointerObserver) {
  90217. this._scene.onPointerObservable.remove(this._pointerObserver);
  90218. }
  90219. if (this._beforeRenderObserver) {
  90220. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  90221. }
  90222. };
  90223. return PointerDragBehavior;
  90224. }());
  90225. BABYLON.PointerDragBehavior = PointerDragBehavior;
  90226. })(BABYLON || (BABYLON = {}));
  90227. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  90228. var BABYLON;
  90229. (function (BABYLON) {
  90230. /**
  90231. * A behavior that when attached to a mesh will allow the mesh to be scaled
  90232. */
  90233. var MultiPointerScaleBehavior = /** @class */ (function () {
  90234. function MultiPointerScaleBehavior() {
  90235. this._startDistance = 0;
  90236. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  90237. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  90238. this._sceneRenderObserver = null;
  90239. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  90240. this._dragBehaviorA.moveAttached = false;
  90241. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  90242. this._dragBehaviorB.moveAttached = false;
  90243. }
  90244. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  90245. /**
  90246. * The name of the behavior
  90247. */
  90248. get: function () {
  90249. return "MultiPointerScale";
  90250. },
  90251. enumerable: true,
  90252. configurable: true
  90253. });
  90254. /**
  90255. * Initializes the behavior
  90256. */
  90257. MultiPointerScaleBehavior.prototype.init = function () { };
  90258. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  90259. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  90260. };
  90261. /**
  90262. * Attaches the scale behavior the passed in mesh
  90263. * @param ownerNode The mesh that will be scaled around once attached
  90264. */
  90265. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  90266. var _this = this;
  90267. this._ownerNode = ownerNode;
  90268. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  90269. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  90270. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90271. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  90272. _this._dragBehaviorA.releaseDrag();
  90273. }
  90274. else {
  90275. _this._initialScale.copyFrom(ownerNode.scaling);
  90276. _this._startDistance = _this._getCurrentDistance();
  90277. }
  90278. }
  90279. });
  90280. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  90281. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90282. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  90283. _this._dragBehaviorB.releaseDrag();
  90284. }
  90285. else {
  90286. _this._initialScale.copyFrom(ownerNode.scaling);
  90287. _this._startDistance = _this._getCurrentDistance();
  90288. }
  90289. }
  90290. });
  90291. // Once both drag behaviors are active scale based on the distance between the two pointers
  90292. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  90293. behavior.onDragObservable.add(function () {
  90294. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90295. var ratio = _this._getCurrentDistance() / _this._startDistance;
  90296. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  90297. }
  90298. });
  90299. });
  90300. ownerNode.addBehavior(this._dragBehaviorA);
  90301. ownerNode.addBehavior(this._dragBehaviorB);
  90302. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  90303. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  90304. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90305. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  90306. if (change.length() > 0.01) {
  90307. ownerNode.scaling.addInPlace(change);
  90308. }
  90309. }
  90310. });
  90311. };
  90312. /**
  90313. * Detaches the behavior from the mesh
  90314. */
  90315. MultiPointerScaleBehavior.prototype.detach = function () {
  90316. var _this = this;
  90317. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  90318. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  90319. behavior.onDragStartObservable.clear();
  90320. behavior.onDragObservable.clear();
  90321. _this._ownerNode.removeBehavior(behavior);
  90322. });
  90323. };
  90324. return MultiPointerScaleBehavior;
  90325. }());
  90326. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  90327. })(BABYLON || (BABYLON = {}));
  90328. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  90329. var BABYLON;
  90330. (function (BABYLON) {
  90331. /**
  90332. * 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
  90333. */
  90334. var SixDofDragBehavior = /** @class */ (function () {
  90335. function SixDofDragBehavior() {
  90336. this._sceneRenderObserver = null;
  90337. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  90338. this._moving = false;
  90339. this._startingOrientation = new BABYLON.Quaternion();
  90340. /**
  90341. * 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)
  90342. */
  90343. this.zDragFactor = 3;
  90344. /**
  90345. * If the behavior is currently in a dragging state
  90346. */
  90347. this.dragging = false;
  90348. /**
  90349. * 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)
  90350. */
  90351. this.dragDeltaRatio = 0.2;
  90352. /**
  90353. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  90354. */
  90355. this.currentDraggingPointerID = -1;
  90356. /**
  90357. * If camera controls should be detached during the drag
  90358. */
  90359. this.detachCameraControls = true;
  90360. }
  90361. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  90362. /**
  90363. * The name of the behavior
  90364. */
  90365. get: function () {
  90366. return "SixDofDrag";
  90367. },
  90368. enumerable: true,
  90369. configurable: true
  90370. });
  90371. /**
  90372. * Initializes the behavior
  90373. */
  90374. SixDofDragBehavior.prototype.init = function () { };
  90375. /**
  90376. * Attaches the scale behavior the passed in mesh
  90377. * @param ownerNode The mesh that will be scaled around once attached
  90378. */
  90379. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  90380. var _this = this;
  90381. this._ownerNode = ownerNode;
  90382. this._scene = this._ownerNode.getScene();
  90383. if (!SixDofDragBehavior._virtualScene) {
  90384. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  90385. this._scene.getEngine().scenes.pop();
  90386. }
  90387. var pickedMesh = null;
  90388. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  90389. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  90390. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  90391. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  90392. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  90393. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  90394. var pickPredicate = function (m) {
  90395. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  90396. };
  90397. var attachedElement = null;
  90398. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  90399. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90400. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  90401. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  90402. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  90403. }
  90404. pickedMesh = _this._ownerNode;
  90405. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  90406. // Set position and orientation of the controller
  90407. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  90408. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  90409. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  90410. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  90411. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  90412. if (!pickedMesh.rotationQuaternion) {
  90413. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  90414. }
  90415. var oldParent = pickedMesh.parent;
  90416. pickedMesh.setParent(null);
  90417. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  90418. pickedMesh.setParent(oldParent);
  90419. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  90420. // Update state
  90421. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  90422. _this.dragging = true;
  90423. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  90424. // Detatch camera controls
  90425. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90426. if (_this._scene.activeCamera.inputs.attachedElement) {
  90427. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  90428. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  90429. }
  90430. else {
  90431. attachedElement = null;
  90432. }
  90433. }
  90434. }
  90435. }
  90436. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  90437. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  90438. _this.dragging = false;
  90439. _this._moving = false;
  90440. _this.currentDraggingPointerID = -1;
  90441. pickedMesh = null;
  90442. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  90443. // Reattach camera controls
  90444. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90445. _this._scene.activeCamera.attachControl(attachedElement, true);
  90446. }
  90447. }
  90448. }
  90449. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  90450. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  90451. var zDragFactor = _this.zDragFactor;
  90452. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  90453. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  90454. zDragFactor = 0;
  90455. }
  90456. // Calculate controller drag distance in controller space
  90457. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  90458. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  90459. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  90460. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  90461. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  90462. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  90463. if (_this._virtualDragMesh.position.z < 0) {
  90464. _this._virtualDragMesh.position.z = 0;
  90465. }
  90466. // Update the controller position
  90467. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  90468. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  90469. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  90470. // Move the virtualObjectsPosition into the picked mesh's space if needed
  90471. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  90472. if (pickedMesh.parent) {
  90473. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  90474. }
  90475. if (!_this._moving) {
  90476. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  90477. }
  90478. _this._moving = true;
  90479. }
  90480. }
  90481. });
  90482. var tmpQuaternion = new BABYLON.Quaternion();
  90483. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  90484. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  90485. if (_this.dragging && _this._moving && pickedMesh) {
  90486. // Slowly move mesh to avoid jitter
  90487. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  90488. // Get change in rotation
  90489. tmpQuaternion.copyFrom(_this._startingOrientation);
  90490. tmpQuaternion.x = -tmpQuaternion.x;
  90491. tmpQuaternion.y = -tmpQuaternion.y;
  90492. tmpQuaternion.z = -tmpQuaternion.z;
  90493. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  90494. // Convert change in rotation to only y axis rotation
  90495. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  90496. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  90497. // Slowly move mesh to avoid jitter
  90498. var oldParent = pickedMesh.parent;
  90499. pickedMesh.setParent(null);
  90500. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  90501. pickedMesh.setParent(oldParent);
  90502. }
  90503. });
  90504. };
  90505. /**
  90506. * Detaches the behavior from the mesh
  90507. */
  90508. SixDofDragBehavior.prototype.detach = function () {
  90509. if (this._scene) {
  90510. this._scene.onPointerObservable.remove(this._pointerObserver);
  90511. }
  90512. if (this._ownerNode) {
  90513. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  90514. }
  90515. if (this._virtualOriginMesh) {
  90516. this._virtualOriginMesh.dispose();
  90517. }
  90518. if (this._virtualDragMesh) {
  90519. this._virtualDragMesh.dispose();
  90520. }
  90521. };
  90522. return SixDofDragBehavior;
  90523. }());
  90524. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  90525. })(BABYLON || (BABYLON = {}));
  90526. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  90527. var BABYLON;
  90528. (function (BABYLON) {
  90529. /**
  90530. * @hidden
  90531. */
  90532. var FaceDirectionInfo = /** @class */ (function () {
  90533. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  90534. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  90535. if (diff === void 0) { diff = 0; }
  90536. if (ignore === void 0) { ignore = false; }
  90537. this.direction = direction;
  90538. this.rotatedDirection = rotatedDirection;
  90539. this.diff = diff;
  90540. this.ignore = ignore;
  90541. }
  90542. return FaceDirectionInfo;
  90543. }());
  90544. /**
  90545. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  90546. */
  90547. var AttachToBoxBehavior = /** @class */ (function () {
  90548. /**
  90549. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  90550. * @param ui The transform node that should be attched to the mesh
  90551. */
  90552. function AttachToBoxBehavior(ui) {
  90553. this.ui = ui;
  90554. /**
  90555. * The name of the behavior
  90556. */
  90557. this.name = "AttachToBoxBehavior";
  90558. /**
  90559. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  90560. */
  90561. this.distanceAwayFromFace = 0.15;
  90562. /**
  90563. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  90564. */
  90565. this.distanceAwayFromBottomOfFace = 0.15;
  90566. 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))];
  90567. this._tmpMatrix = new BABYLON.Matrix();
  90568. this._tmpVector = new BABYLON.Vector3();
  90569. this._zeroVector = BABYLON.Vector3.Zero();
  90570. this._lookAtTmpMatrix = new BABYLON.Matrix();
  90571. /* Does nothing */
  90572. }
  90573. /**
  90574. * Initializes the behavior
  90575. */
  90576. AttachToBoxBehavior.prototype.init = function () {
  90577. /* Does nothing */
  90578. };
  90579. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  90580. var _this = this;
  90581. // Go over each face and calculate the angle between the face's normal and targetDirection
  90582. this._faceVectors.forEach(function (v) {
  90583. if (!_this._target.rotationQuaternion) {
  90584. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  90585. }
  90586. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  90587. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  90588. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  90589. });
  90590. // Return the face information of the one with the normal closeset to target direction
  90591. return this._faceVectors.reduce(function (min, p) {
  90592. if (min.ignore) {
  90593. return p;
  90594. }
  90595. else if (p.ignore) {
  90596. return min;
  90597. }
  90598. else {
  90599. return min.diff < p.diff ? min : p;
  90600. }
  90601. }, this._faceVectors[0]);
  90602. };
  90603. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  90604. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  90605. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  90606. this._lookAtTmpMatrix.invert();
  90607. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  90608. };
  90609. /**
  90610. * Attaches the AttachToBoxBehavior to the passed in mesh
  90611. * @param target The mesh that the specified node will be attached to
  90612. */
  90613. AttachToBoxBehavior.prototype.attach = function (target) {
  90614. var _this = this;
  90615. this._target = target;
  90616. this._scene = this._target.getScene();
  90617. // Every frame, update the app bars position
  90618. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  90619. if (!_this._scene.activeCamera) {
  90620. return;
  90621. }
  90622. // Find the face closest to the cameras position
  90623. var cameraPos = _this._scene.activeCamera.position;
  90624. if (_this._scene.activeCamera.devicePosition) {
  90625. cameraPos = _this._scene.activeCamera.devicePosition;
  90626. }
  90627. var facing = _this._closestFace(cameraPos.subtract(target.position));
  90628. if (_this._scene.activeCamera.leftCamera) {
  90629. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  90630. }
  90631. else {
  90632. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  90633. }
  90634. // Get camera up direction
  90635. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  90636. // Ignore faces to not select a parrelel face for the up vector of the UI
  90637. _this._faceVectors.forEach(function (v) {
  90638. if (facing.direction.x && v.direction.x) {
  90639. v.ignore = true;
  90640. }
  90641. if (facing.direction.y && v.direction.y) {
  90642. v.ignore = true;
  90643. }
  90644. if (facing.direction.z && v.direction.z) {
  90645. v.ignore = true;
  90646. }
  90647. });
  90648. var facingUp = _this._closestFace(_this._tmpVector);
  90649. // Unignore faces
  90650. _this._faceVectors.forEach(function (v) {
  90651. v.ignore = false;
  90652. });
  90653. // Position the app bar on that face
  90654. _this.ui.position.copyFrom(target.position);
  90655. if (facing.direction.x) {
  90656. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90657. _this.ui.position.addInPlace(_this._tmpVector);
  90658. }
  90659. if (facing.direction.y) {
  90660. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90661. _this.ui.position.addInPlace(_this._tmpVector);
  90662. }
  90663. if (facing.direction.z) {
  90664. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90665. _this.ui.position.addInPlace(_this._tmpVector);
  90666. }
  90667. // Rotate to be oriented properly to the camera
  90668. if (!_this.ui.rotationQuaternion) {
  90669. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  90670. }
  90671. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  90672. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  90673. // Place ui the correct distance from the bottom of the mesh
  90674. if (facingUp.direction.x) {
  90675. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  90676. }
  90677. if (facingUp.direction.y) {
  90678. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  90679. }
  90680. if (facingUp.direction.z) {
  90681. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  90682. }
  90683. _this.ui.position.addInPlace(_this._tmpVector);
  90684. });
  90685. };
  90686. /**
  90687. * Detaches the behavior from the mesh
  90688. */
  90689. AttachToBoxBehavior.prototype.detach = function () {
  90690. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  90691. };
  90692. return AttachToBoxBehavior;
  90693. }());
  90694. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  90695. })(BABYLON || (BABYLON = {}));
  90696. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  90697. var BABYLON;
  90698. (function (BABYLON) {
  90699. /**
  90700. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  90701. */
  90702. var Gizmo = /** @class */ (function () {
  90703. /**
  90704. * Creates a gizmo
  90705. * @param gizmoLayer The utility layer the gizmo will be added to
  90706. */
  90707. function Gizmo(
  90708. /** The utility layer the gizmo will be added to */
  90709. gizmoLayer) {
  90710. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90711. var _this = this;
  90712. this.gizmoLayer = gizmoLayer;
  90713. this._scaleFactor = 3;
  90714. this._tmpMatrix = new BABYLON.Matrix();
  90715. /**
  90716. * If a custom mesh has been set (Default: false)
  90717. */
  90718. this._customMeshSet = false;
  90719. /**
  90720. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  90721. */
  90722. this.updateGizmoRotationToMatchAttachedMesh = true;
  90723. /**
  90724. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  90725. */
  90726. this.updateGizmoPositionToMatchAttachedMesh = true;
  90727. /**
  90728. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  90729. */
  90730. this._updateScale = true;
  90731. this._interactionsEnabled = true;
  90732. this._tempVector = new BABYLON.Vector3();
  90733. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  90734. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  90735. _this._update();
  90736. });
  90737. this.attachedMesh = null;
  90738. }
  90739. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  90740. /**
  90741. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  90742. * * When set, interactions will be enabled
  90743. */
  90744. get: function () {
  90745. return this._attachedMesh;
  90746. },
  90747. set: function (value) {
  90748. this._attachedMesh = value;
  90749. this._rootMesh.setEnabled(value ? true : false);
  90750. this._attachedMeshChanged(value);
  90751. },
  90752. enumerable: true,
  90753. configurable: true
  90754. });
  90755. /**
  90756. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  90757. * @param mesh The mesh to replace the default mesh of the gizmo
  90758. */
  90759. Gizmo.prototype.setCustomMesh = function (mesh) {
  90760. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  90761. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  90762. }
  90763. this._rootMesh.getChildMeshes().forEach(function (c) {
  90764. c.dispose();
  90765. });
  90766. mesh.parent = this._rootMesh;
  90767. this._customMeshSet = true;
  90768. };
  90769. Gizmo.prototype._attachedMeshChanged = function (value) {
  90770. };
  90771. /**
  90772. * @hidden
  90773. * Updates the gizmo to match the attached mesh's position/rotation
  90774. */
  90775. Gizmo.prototype._update = function () {
  90776. if (this.attachedMesh) {
  90777. if (this.updateGizmoRotationToMatchAttachedMesh) {
  90778. if (!this._rootMesh.rotationQuaternion) {
  90779. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  90780. }
  90781. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  90782. this._tempVector.copyFrom(this.attachedMesh.scaling);
  90783. if (this.attachedMesh.scaling.x < 0) {
  90784. this.attachedMesh.scaling.x *= -1;
  90785. }
  90786. if (this.attachedMesh.scaling.y < 0) {
  90787. this.attachedMesh.scaling.y *= -1;
  90788. }
  90789. if (this.attachedMesh.scaling.z < 0) {
  90790. this.attachedMesh.scaling.z *= -1;
  90791. }
  90792. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  90793. this.attachedMesh.scaling.copyFrom(this._tempVector);
  90794. this.attachedMesh.computeWorldMatrix();
  90795. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  90796. }
  90797. if (this.updateGizmoPositionToMatchAttachedMesh) {
  90798. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  90799. }
  90800. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  90801. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  90802. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  90803. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  90804. }
  90805. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  90806. var dist = this._tempVector.length() / this._scaleFactor;
  90807. this._rootMesh.scaling.set(dist, dist, dist);
  90808. }
  90809. }
  90810. };
  90811. /**
  90812. * Disposes of the gizmo
  90813. */
  90814. Gizmo.prototype.dispose = function () {
  90815. this._rootMesh.dispose();
  90816. if (this._beforeRenderObserver) {
  90817. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  90818. }
  90819. };
  90820. return Gizmo;
  90821. }());
  90822. BABYLON.Gizmo = Gizmo;
  90823. })(BABYLON || (BABYLON = {}));
  90824. //# sourceMappingURL=babylon.gizmo.js.map
  90825. var BABYLON;
  90826. (function (BABYLON) {
  90827. /**
  90828. * Single axis drag gizmo
  90829. */
  90830. var AxisDragGizmo = /** @class */ (function (_super) {
  90831. __extends(AxisDragGizmo, _super);
  90832. /**
  90833. * Creates an AxisDragGizmo
  90834. * @param gizmoLayer The utility layer the gizmo will be added to
  90835. * @param dragAxis The axis which the gizmo will be able to drag on
  90836. * @param color The color of the gizmo
  90837. */
  90838. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  90839. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90840. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90841. var _this = _super.call(this, gizmoLayer) || this;
  90842. _this._pointerObserver = null;
  90843. /**
  90844. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90845. */
  90846. _this.snapDistance = 0;
  90847. /**
  90848. * Event that fires each time the gizmo snaps to a new location.
  90849. * * snapDistance is the the change in distance
  90850. */
  90851. _this.onSnapObservable = new BABYLON.Observable();
  90852. // Create Material
  90853. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90854. coloredMaterial.disableLighting = true;
  90855. coloredMaterial.emissiveColor = color;
  90856. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90857. hoverMaterial.disableLighting = true;
  90858. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90859. // Build mesh on root node
  90860. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90861. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90862. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);
  90863. arrowTail.color = coloredMaterial.emissiveColor;
  90864. arrow.addChild(arrowMesh);
  90865. arrow.addChild(arrowTail);
  90866. // Position arrow pointing in its drag axis
  90867. arrowMesh.scaling.scaleInPlace(0.05);
  90868. arrowMesh.material = coloredMaterial;
  90869. arrowMesh.rotation.x = Math.PI / 2;
  90870. arrowMesh.position.z += 0.3;
  90871. arrowTail.scaling.scaleInPlace(0.2);
  90872. arrowTail.rotation.x = Math.PI / 2;
  90873. arrowTail.material = coloredMaterial;
  90874. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90875. _this._rootMesh.addChild(arrow);
  90876. var currentSnapDragDistance = 0;
  90877. var tmpVector = new BABYLON.Vector3();
  90878. var tmpSnapEvent = { snapDistance: 0 };
  90879. // Add drag behavior to handle events when the gizmo is dragged
  90880. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90881. _this.dragBehavior.moveAttached = false;
  90882. _this._rootMesh.addBehavior(_this.dragBehavior);
  90883. _this.dragBehavior.onDragObservable.add(function (event) {
  90884. if (_this.attachedMesh) {
  90885. // Snapping logic
  90886. if (_this.snapDistance == 0) {
  90887. _this.attachedMesh.position.addInPlace(event.delta);
  90888. }
  90889. else {
  90890. currentSnapDragDistance += event.dragDistance;
  90891. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90892. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  90893. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90894. event.delta.normalizeToRef(tmpVector);
  90895. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  90896. _this.attachedMesh.position.addInPlace(tmpVector);
  90897. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90898. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90899. }
  90900. }
  90901. }
  90902. });
  90903. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90904. if (_this._customMeshSet) {
  90905. return;
  90906. }
  90907. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  90908. var material = isHovered ? hoverMaterial : coloredMaterial;
  90909. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90910. m.material = material;
  90911. if (m.color) {
  90912. m.color = material.emissiveColor;
  90913. }
  90914. });
  90915. });
  90916. return _this;
  90917. }
  90918. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  90919. if (this.dragBehavior) {
  90920. this.dragBehavior.enabled = value ? true : false;
  90921. }
  90922. };
  90923. /**
  90924. * Disposes of the gizmo
  90925. */
  90926. AxisDragGizmo.prototype.dispose = function () {
  90927. this.onSnapObservable.clear();
  90928. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90929. this.dragBehavior.detach();
  90930. _super.prototype.dispose.call(this);
  90931. };
  90932. return AxisDragGizmo;
  90933. }(BABYLON.Gizmo));
  90934. BABYLON.AxisDragGizmo = AxisDragGizmo;
  90935. })(BABYLON || (BABYLON = {}));
  90936. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  90937. var BABYLON;
  90938. (function (BABYLON) {
  90939. /**
  90940. * Single axis scale gizmo
  90941. */
  90942. var AxisScaleGizmo = /** @class */ (function (_super) {
  90943. __extends(AxisScaleGizmo, _super);
  90944. /**
  90945. * Creates an AxisScaleGizmo
  90946. * @param gizmoLayer The utility layer the gizmo will be added to
  90947. * @param dragAxis The axis which the gizmo will be able to scale on
  90948. * @param color The color of the gizmo
  90949. */
  90950. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  90951. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90952. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90953. var _this = _super.call(this, gizmoLayer) || this;
  90954. _this._pointerObserver = null;
  90955. /**
  90956. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90957. */
  90958. _this.snapDistance = 0;
  90959. /**
  90960. * Event that fires each time the gizmo snaps to a new location.
  90961. * * snapDistance is the the change in distance
  90962. */
  90963. _this.onSnapObservable = new BABYLON.Observable();
  90964. // Create Material
  90965. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90966. coloredMaterial.disableLighting = true;
  90967. coloredMaterial.emissiveColor = color;
  90968. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90969. hoverMaterial.disableLighting = true;
  90970. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90971. // Build mesh on root node
  90972. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90973. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  90974. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);
  90975. arrowTail.color = coloredMaterial.emissiveColor;
  90976. arrow.addChild(arrowMesh);
  90977. arrow.addChild(arrowTail);
  90978. // Position arrow pointing in its drag axis
  90979. arrowMesh.scaling.scaleInPlace(0.1);
  90980. arrowMesh.material = coloredMaterial;
  90981. arrowMesh.rotation.x = Math.PI / 2;
  90982. arrowMesh.position.z += 0.3;
  90983. arrowTail.scaling.scaleInPlace(0.2);
  90984. arrowTail.rotation.x = Math.PI / 2;
  90985. arrowTail.material = coloredMaterial;
  90986. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90987. _this._rootMesh.addChild(arrow);
  90988. // Add drag behavior to handle events when the gizmo is dragged
  90989. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90990. _this.dragBehavior.moveAttached = false;
  90991. _this._rootMesh.addBehavior(_this.dragBehavior);
  90992. var currentSnapDragDistance = 0;
  90993. var tmpVector = new BABYLON.Vector3();
  90994. var tmpSnapEvent = { snapDistance: 0 };
  90995. _this.dragBehavior.onDragObservable.add(function (event) {
  90996. if (_this.attachedMesh) {
  90997. // Snapping logic
  90998. var snapped = false;
  90999. var dragSteps = 0;
  91000. if (_this.snapDistance == 0) {
  91001. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  91002. }
  91003. else {
  91004. currentSnapDragDistance += event.dragDistance;
  91005. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  91006. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  91007. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  91008. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  91009. snapped = true;
  91010. }
  91011. else {
  91012. tmpVector.scaleInPlace(0);
  91013. }
  91014. }
  91015. _this.attachedMesh.scaling.addInPlace(tmpVector);
  91016. if (snapped) {
  91017. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  91018. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  91019. }
  91020. }
  91021. });
  91022. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  91023. if (_this._customMeshSet) {
  91024. return;
  91025. }
  91026. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  91027. var material = isHovered ? hoverMaterial : coloredMaterial;
  91028. _this._rootMesh.getChildMeshes().forEach(function (m) {
  91029. m.material = material;
  91030. if (m.color) {
  91031. m.color = material.emissiveColor;
  91032. }
  91033. });
  91034. });
  91035. return _this;
  91036. }
  91037. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  91038. if (this.dragBehavior) {
  91039. this.dragBehavior.enabled = value ? true : false;
  91040. }
  91041. };
  91042. /**
  91043. * Disposes of the gizmo
  91044. */
  91045. AxisScaleGizmo.prototype.dispose = function () {
  91046. this.onSnapObservable.clear();
  91047. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91048. this.dragBehavior.detach();
  91049. _super.prototype.dispose.call(this);
  91050. };
  91051. return AxisScaleGizmo;
  91052. }(BABYLON.Gizmo));
  91053. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  91054. })(BABYLON || (BABYLON = {}));
  91055. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  91056. var BABYLON;
  91057. (function (BABYLON) {
  91058. /**
  91059. * Single plane rotation gizmo
  91060. */
  91061. var PlaneRotationGizmo = /** @class */ (function (_super) {
  91062. __extends(PlaneRotationGizmo, _super);
  91063. /**
  91064. * Creates a PlaneRotationGizmo
  91065. * @param gizmoLayer The utility layer the gizmo will be added to
  91066. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  91067. * @param color The color of the gizmo
  91068. */
  91069. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  91070. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  91071. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91072. var _this = _super.call(this, gizmoLayer) || this;
  91073. _this._pointerObserver = null;
  91074. /**
  91075. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  91076. */
  91077. _this.snapDistance = 0;
  91078. /**
  91079. * Event that fires each time the gizmo snaps to a new location.
  91080. * * snapDistance is the the change in distance
  91081. */
  91082. _this.onSnapObservable = new BABYLON.Observable();
  91083. // Create Material
  91084. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91085. coloredMaterial.disableLighting = true;
  91086. coloredMaterial.emissiveColor = color;
  91087. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91088. hoverMaterial.disableLighting = true;
  91089. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  91090. // Build mesh on root node
  91091. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91092. // Create circle out of lines
  91093. var tessellation = 20;
  91094. var radius = 2;
  91095. var points = new Array();
  91096. for (var i = 0; i < tessellation; i++) {
  91097. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  91098. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  91099. }
  91100. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  91101. rotationMesh.color = coloredMaterial.emissiveColor;
  91102. // Position arrow pointing in its drag axis
  91103. rotationMesh.scaling.scaleInPlace(0.1);
  91104. rotationMesh.material = coloredMaterial;
  91105. rotationMesh.rotation.x = Math.PI / 2;
  91106. parentMesh.addChild(rotationMesh);
  91107. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  91108. _this._rootMesh.addChild(parentMesh);
  91109. // Add drag behavior to handle events when the gizmo is dragged
  91110. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  91111. _this.dragBehavior.moveAttached = false;
  91112. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  91113. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  91114. _this._rootMesh.addBehavior(_this.dragBehavior);
  91115. var lastDragPosition = new BABYLON.Vector3();
  91116. _this.dragBehavior.onDragStartObservable.add(function (e) {
  91117. if (_this.attachedMesh) {
  91118. lastDragPosition.copyFrom(e.dragPlanePoint);
  91119. }
  91120. });
  91121. var rotationMatrix = new BABYLON.Matrix();
  91122. var planeNormalTowardsCamera = new BABYLON.Vector3();
  91123. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  91124. var tmpSnapEvent = { snapDistance: 0 };
  91125. var currentSnapDragDistance = 0;
  91126. _this.dragBehavior.onDragObservable.add(function (event) {
  91127. if (_this.attachedMesh) {
  91128. if (!_this.attachedMesh.rotationQuaternion) {
  91129. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  91130. }
  91131. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  91132. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  91133. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  91134. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  91135. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  91136. var angle = Math.atan2(cross.length(), dot);
  91137. planeNormalTowardsCamera.copyFrom(planeNormal);
  91138. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  91139. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  91140. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  91141. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  91142. }
  91143. // Flip up vector depending on which side the camera is on
  91144. if (gizmoLayer.utilityLayerScene.activeCamera) {
  91145. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  91146. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  91147. planeNormalTowardsCamera.scaleInPlace(-1);
  91148. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  91149. }
  91150. }
  91151. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  91152. if (halfCircleSide)
  91153. angle = -angle;
  91154. // Snapping logic
  91155. var snapped = false;
  91156. if (_this.snapDistance != 0) {
  91157. currentSnapDragDistance += angle;
  91158. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  91159. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  91160. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  91161. angle = _this.snapDistance * dragSteps;
  91162. snapped = true;
  91163. }
  91164. else {
  91165. angle = 0;
  91166. }
  91167. }
  91168. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  91169. var quaternionCoefficient = Math.sin(angle / 2);
  91170. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  91171. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  91172. // Rotate selected mesh quaternion over fixed axis
  91173. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  91174. }
  91175. else {
  91176. // Rotate selected mesh quaternion over rotated axis
  91177. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  91178. }
  91179. lastDragPosition.copyFrom(event.dragPlanePoint);
  91180. if (snapped) {
  91181. tmpSnapEvent.snapDistance = angle;
  91182. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  91183. }
  91184. }
  91185. });
  91186. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  91187. if (_this._customMeshSet) {
  91188. return;
  91189. }
  91190. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  91191. var material = isHovered ? hoverMaterial : coloredMaterial;
  91192. _this._rootMesh.getChildMeshes().forEach(function (m) {
  91193. m.material = material;
  91194. if (m.color) {
  91195. m.color = material.emissiveColor;
  91196. }
  91197. });
  91198. });
  91199. return _this;
  91200. }
  91201. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  91202. if (this.dragBehavior) {
  91203. this.dragBehavior.enabled = value ? true : false;
  91204. }
  91205. };
  91206. /**
  91207. * Disposes of the gizmo
  91208. */
  91209. PlaneRotationGizmo.prototype.dispose = function () {
  91210. this.onSnapObservable.clear();
  91211. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91212. this.dragBehavior.detach();
  91213. _super.prototype.dispose.call(this);
  91214. };
  91215. return PlaneRotationGizmo;
  91216. }(BABYLON.Gizmo));
  91217. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  91218. })(BABYLON || (BABYLON = {}));
  91219. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  91220. var BABYLON;
  91221. (function (BABYLON) {
  91222. /**
  91223. * Gizmo that enables dragging a mesh along 3 axis
  91224. */
  91225. var PositionGizmo = /** @class */ (function (_super) {
  91226. __extends(PositionGizmo, _super);
  91227. /**
  91228. * Creates a PositionGizmo
  91229. * @param gizmoLayer The utility layer the gizmo will be added to
  91230. */
  91231. function PositionGizmo(gizmoLayer) {
  91232. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91233. var _this = _super.call(this, gizmoLayer) || this;
  91234. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  91235. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  91236. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  91237. _this.attachedMesh = null;
  91238. return _this;
  91239. }
  91240. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  91241. set: function (mesh) {
  91242. if (this.xGizmo) {
  91243. this.xGizmo.attachedMesh = mesh;
  91244. this.yGizmo.attachedMesh = mesh;
  91245. this.zGizmo.attachedMesh = mesh;
  91246. }
  91247. },
  91248. enumerable: true,
  91249. configurable: true
  91250. });
  91251. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  91252. get: function () {
  91253. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  91254. },
  91255. set: function (value) {
  91256. if (this.xGizmo) {
  91257. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91258. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91259. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91260. }
  91261. },
  91262. enumerable: true,
  91263. configurable: true
  91264. });
  91265. /**
  91266. * Disposes of the gizmo
  91267. */
  91268. PositionGizmo.prototype.dispose = function () {
  91269. this.xGizmo.dispose();
  91270. this.yGizmo.dispose();
  91271. this.zGizmo.dispose();
  91272. };
  91273. /**
  91274. * CustomMeshes are not supported by this gizmo
  91275. * @param mesh The mesh to replace the default mesh of the gizmo
  91276. */
  91277. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  91278. 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)");
  91279. };
  91280. return PositionGizmo;
  91281. }(BABYLON.Gizmo));
  91282. BABYLON.PositionGizmo = PositionGizmo;
  91283. })(BABYLON || (BABYLON = {}));
  91284. //# sourceMappingURL=babylon.positionGizmo.js.map
  91285. var BABYLON;
  91286. (function (BABYLON) {
  91287. /**
  91288. * Gizmo that enables rotating a mesh along 3 axis
  91289. */
  91290. var RotationGizmo = /** @class */ (function (_super) {
  91291. __extends(RotationGizmo, _super);
  91292. /**
  91293. * Creates a RotationGizmo
  91294. * @param gizmoLayer The utility layer the gizmo will be added to
  91295. */
  91296. function RotationGizmo(gizmoLayer) {
  91297. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91298. var _this = _super.call(this, gizmoLayer) || this;
  91299. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  91300. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  91301. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  91302. _this.attachedMesh = null;
  91303. return _this;
  91304. }
  91305. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  91306. set: function (mesh) {
  91307. if (this.xGizmo) {
  91308. this.xGizmo.attachedMesh = mesh;
  91309. this.yGizmo.attachedMesh = mesh;
  91310. this.zGizmo.attachedMesh = mesh;
  91311. }
  91312. },
  91313. enumerable: true,
  91314. configurable: true
  91315. });
  91316. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  91317. get: function () {
  91318. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  91319. },
  91320. set: function (value) {
  91321. if (this.xGizmo) {
  91322. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91323. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91324. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91325. }
  91326. },
  91327. enumerable: true,
  91328. configurable: true
  91329. });
  91330. /**
  91331. * Disposes of the gizmo
  91332. */
  91333. RotationGizmo.prototype.dispose = function () {
  91334. this.xGizmo.dispose();
  91335. this.yGizmo.dispose();
  91336. this.zGizmo.dispose();
  91337. };
  91338. /**
  91339. * CustomMeshes are not supported by this gizmo
  91340. * @param mesh The mesh to replace the default mesh of the gizmo
  91341. */
  91342. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  91343. 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)");
  91344. };
  91345. return RotationGizmo;
  91346. }(BABYLON.Gizmo));
  91347. BABYLON.RotationGizmo = RotationGizmo;
  91348. })(BABYLON || (BABYLON = {}));
  91349. //# sourceMappingURL=babylon.rotationGizmo.js.map
  91350. var BABYLON;
  91351. (function (BABYLON) {
  91352. /**
  91353. * Gizmo that enables scaling a mesh along 3 axis
  91354. */
  91355. var ScaleGizmo = /** @class */ (function (_super) {
  91356. __extends(ScaleGizmo, _super);
  91357. /**
  91358. * Creates a ScaleGizmo
  91359. * @param gizmoLayer The utility layer the gizmo will be added to
  91360. */
  91361. function ScaleGizmo(gizmoLayer) {
  91362. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91363. var _this = _super.call(this, gizmoLayer) || this;
  91364. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  91365. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  91366. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  91367. _this.attachedMesh = null;
  91368. return _this;
  91369. }
  91370. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  91371. set: function (mesh) {
  91372. if (this.xGizmo) {
  91373. this.xGizmo.attachedMesh = mesh;
  91374. this.yGizmo.attachedMesh = mesh;
  91375. this.zGizmo.attachedMesh = mesh;
  91376. }
  91377. },
  91378. enumerable: true,
  91379. configurable: true
  91380. });
  91381. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  91382. get: function () {
  91383. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  91384. },
  91385. set: function (value) {
  91386. if (this.xGizmo) {
  91387. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91388. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91389. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91390. }
  91391. },
  91392. enumerable: true,
  91393. configurable: true
  91394. });
  91395. /**
  91396. * Disposes of the gizmo
  91397. */
  91398. ScaleGizmo.prototype.dispose = function () {
  91399. this.xGizmo.dispose();
  91400. this.yGizmo.dispose();
  91401. this.zGizmo.dispose();
  91402. };
  91403. return ScaleGizmo;
  91404. }(BABYLON.Gizmo));
  91405. BABYLON.ScaleGizmo = ScaleGizmo;
  91406. })(BABYLON || (BABYLON = {}));
  91407. //# sourceMappingURL=babylon.scaleGizmo.js.map
  91408. var BABYLON;
  91409. (function (BABYLON) {
  91410. /**
  91411. * Bounding box gizmo
  91412. */
  91413. var BoundingBoxGizmo = /** @class */ (function (_super) {
  91414. __extends(BoundingBoxGizmo, _super);
  91415. /**
  91416. * Creates an BoundingBoxGizmo
  91417. * @param gizmoLayer The utility layer the gizmo will be added to
  91418. * @param color The color of the gizmo
  91419. */
  91420. function BoundingBoxGizmo(color, gizmoLayer) {
  91421. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  91422. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  91423. var _this = _super.call(this, gizmoLayer) || this;
  91424. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  91425. _this._renderObserver = null;
  91426. _this._pointerObserver = null;
  91427. _this._scaleDragSpeed = 0.2;
  91428. _this._tmpQuaternion = new BABYLON.Quaternion();
  91429. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  91430. /**
  91431. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  91432. */
  91433. _this.rotationSphereSize = 0.1;
  91434. /**
  91435. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  91436. */
  91437. _this.scaleBoxSize = 0.1;
  91438. /**
  91439. * 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)
  91440. */
  91441. _this.fixedDragMeshScreenSize = false;
  91442. /**
  91443. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  91444. */
  91445. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  91446. /**
  91447. * Fired when a rotation sphere or scale box is dragged
  91448. */
  91449. _this.onDragStartObservable = new BABYLON.Observable();
  91450. /**
  91451. * Fired when a rotation sphere or scale box drag is started
  91452. */
  91453. _this.onDragObservable = new BABYLON.Observable();
  91454. /**
  91455. * Fired when a rotation sphere or scale box drag is needed
  91456. */
  91457. _this.onDragEndObservable = new BABYLON.Observable();
  91458. _this._existingMeshScale = new BABYLON.Vector3();
  91459. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  91460. _this._updateScale = false;
  91461. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  91462. // Create Materials
  91463. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91464. coloredMaterial.disableLighting = true;
  91465. coloredMaterial.emissiveColor = color;
  91466. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91467. hoverColoredMaterial.disableLighting = true;
  91468. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  91469. // Build bounding box out of lines
  91470. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91471. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  91472. var lines = [];
  91473. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  91474. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  91475. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  91476. 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));
  91477. 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));
  91478. 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));
  91479. 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));
  91480. 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));
  91481. 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));
  91482. 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));
  91483. 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));
  91484. 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));
  91485. lines.forEach(function (l) {
  91486. l.color = color;
  91487. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  91488. l.isPickable = false;
  91489. _this._lineBoundingBox.addChild(l);
  91490. });
  91491. _this._rootMesh.addChild(_this._lineBoundingBox);
  91492. // Create rotation spheres
  91493. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91494. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  91495. var _loop_1 = function (i_1) {
  91496. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  91497. sphere.rotationQuaternion = new BABYLON.Quaternion();
  91498. sphere.material = coloredMaterial;
  91499. // Drag behavior
  91500. _dragBehavior = new BABYLON.PointerDragBehavior({});
  91501. _dragBehavior.moveAttached = false;
  91502. _dragBehavior.updateDragPlane = false;
  91503. sphere.addBehavior(_dragBehavior);
  91504. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  91505. var totalTurnAmountOfDrag = 0;
  91506. _dragBehavior.onDragStartObservable.add(function (event) {
  91507. startingTurnDirection.copyFrom(sphere.forward);
  91508. totalTurnAmountOfDrag = 0;
  91509. });
  91510. _dragBehavior.onDragObservable.add(function (event) {
  91511. _this.onDragObservable.notifyObservers({});
  91512. if (_this.attachedMesh) {
  91513. var worldDragDirection = startingTurnDirection;
  91514. // Project the world right on to the drag plane
  91515. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  91516. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  91517. // project drag delta on to the resulting drag axis and rotate based on that
  91518. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  91519. // Make rotation relative to size of mesh.
  91520. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  91521. // Rotate based on axis
  91522. if (!_this.attachedMesh.rotationQuaternion) {
  91523. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  91524. }
  91525. if (!_this._anchorMesh.rotationQuaternion) {
  91526. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  91527. }
  91528. // Do not allow the object to turn more than a full circle
  91529. totalTurnAmountOfDrag += projectDist;
  91530. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  91531. if (i_1 >= 8) {
  91532. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  91533. }
  91534. else if (i_1 >= 4) {
  91535. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  91536. }
  91537. else {
  91538. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  91539. }
  91540. // Rotate around center of bounding box
  91541. _this._anchorMesh.addChild(_this.attachedMesh);
  91542. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  91543. _this._anchorMesh.removeChild(_this.attachedMesh);
  91544. }
  91545. _this.updateBoundingBox();
  91546. }
  91547. });
  91548. // Selection/deselection
  91549. _dragBehavior.onDragStartObservable.add(function () {
  91550. _this.onDragStartObservable.notifyObservers({});
  91551. _this._selectNode(sphere);
  91552. });
  91553. _dragBehavior.onDragEndObservable.add(function () {
  91554. _this.onDragEndObservable.notifyObservers({});
  91555. _this._selectNode(null);
  91556. });
  91557. this_1._rotateSpheresParent.addChild(sphere);
  91558. };
  91559. var this_1 = this, _dragBehavior;
  91560. for (var i_1 = 0; i_1 < 12; i_1++) {
  91561. _loop_1(i_1);
  91562. }
  91563. _this._rootMesh.addChild(_this._rotateSpheresParent);
  91564. // Create scale cubes
  91565. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91566. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  91567. for (var i = 0; i < 2; i++) {
  91568. for (var j = 0; j < 2; j++) {
  91569. var _loop_2 = function () {
  91570. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  91571. box.material = coloredMaterial;
  91572. // Dragging logic
  91573. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  91574. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  91575. _dragBehavior.moveAttached = false;
  91576. box.addBehavior(_dragBehavior);
  91577. _dragBehavior.onDragObservable.add(function (event) {
  91578. _this.onDragObservable.notifyObservers({});
  91579. if (_this.attachedMesh) {
  91580. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  91581. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  91582. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  91583. _this.updateBoundingBox();
  91584. // Scale from the position of the opposite corner
  91585. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  91586. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  91587. _this._anchorMesh.addChild(_this.attachedMesh);
  91588. _this._anchorMesh.scaling.addInPlace(deltaScale);
  91589. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  91590. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  91591. }
  91592. _this._anchorMesh.removeChild(_this.attachedMesh);
  91593. }
  91594. });
  91595. // Selection/deselection
  91596. _dragBehavior.onDragStartObservable.add(function () {
  91597. _this.onDragStartObservable.notifyObservers({});
  91598. _this._selectNode(box);
  91599. });
  91600. _dragBehavior.onDragEndObservable.add(function () {
  91601. _this.onDragEndObservable.notifyObservers({});
  91602. _this._selectNode(null);
  91603. });
  91604. this_2._scaleBoxesParent.addChild(box);
  91605. };
  91606. var this_2 = this, _dragBehavior;
  91607. for (var k = 0; k < 2; k++) {
  91608. _loop_2();
  91609. }
  91610. }
  91611. }
  91612. _this._rootMesh.addChild(_this._scaleBoxesParent);
  91613. // Hover color change
  91614. var pointerIds = new Array();
  91615. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  91616. if (!pointerIds[pointerInfo.event.pointerId]) {
  91617. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  91618. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  91619. pointerIds[pointerInfo.event.pointerId] = mesh;
  91620. mesh.material = hoverColoredMaterial;
  91621. }
  91622. });
  91623. }
  91624. else {
  91625. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  91626. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  91627. delete pointerIds[pointerInfo.event.pointerId];
  91628. }
  91629. }
  91630. });
  91631. // Update bounding box positions
  91632. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  91633. // Only update the bouding box if scaling has changed
  91634. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  91635. _this.updateBoundingBox();
  91636. }
  91637. });
  91638. _this.updateBoundingBox();
  91639. return _this;
  91640. }
  91641. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  91642. if (value) {
  91643. // Reset anchor mesh to match attached mesh's scale
  91644. // This is needed to avoid invalid box/sphere position on first drag
  91645. this._anchorMesh.addChild(value);
  91646. this._anchorMesh.removeChild(value);
  91647. this.updateBoundingBox();
  91648. }
  91649. };
  91650. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  91651. this._rotateSpheresParent.getChildMeshes()
  91652. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  91653. m.isVisible = (!selectedMesh || m == selectedMesh);
  91654. });
  91655. };
  91656. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  91657. var _this = this;
  91658. mesh.computeWorldMatrix(true);
  91659. mesh.getChildMeshes().forEach(function (m) {
  91660. _this._recurseComputeWorld(m);
  91661. });
  91662. };
  91663. /**
  91664. * Updates the bounding box information for the Gizmo
  91665. */
  91666. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  91667. this._update();
  91668. if (this.attachedMesh) {
  91669. // Rotate based on axis
  91670. if (!this.attachedMesh.rotationQuaternion) {
  91671. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  91672. }
  91673. if (!this._anchorMesh.rotationQuaternion) {
  91674. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  91675. }
  91676. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  91677. // Store original position and reset mesh to origin before computing the bounding box
  91678. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  91679. this._tmpVector.copyFrom(this.attachedMesh.position);
  91680. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  91681. this.attachedMesh.position.set(0, 0, 0);
  91682. // Update bounding dimensions/positions
  91683. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();
  91684. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  91685. // Update gizmo to match bounding box scaling and rotation
  91686. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  91687. 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);
  91688. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  91689. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  91690. this._lineBoundingBox.computeWorldMatrix();
  91691. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  91692. // restore position/rotation values
  91693. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  91694. this.attachedMesh.position.copyFrom(this._tmpVector);
  91695. this._recurseComputeWorld(this.attachedMesh);
  91696. }
  91697. // Update rotation sphere locations
  91698. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  91699. for (var i = 0; i < 3; i++) {
  91700. for (var j = 0; j < 2; j++) {
  91701. for (var k = 0; k < 2; k++) {
  91702. var index = ((i * 4) + (j * 2)) + k;
  91703. if (i == 0) {
  91704. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  91705. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91706. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  91707. }
  91708. if (i == 1) {
  91709. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  91710. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91711. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  91712. }
  91713. if (i == 2) {
  91714. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  91715. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91716. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  91717. }
  91718. if (this.fixedDragMeshScreenSize) {
  91719. this._rootMesh.computeWorldMatrix();
  91720. this._rotateSpheresParent.computeWorldMatrix();
  91721. rotateSpheres[index].computeWorldMatrix();
  91722. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  91723. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  91724. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  91725. }
  91726. else {
  91727. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  91728. }
  91729. }
  91730. }
  91731. }
  91732. // Update scale box locations
  91733. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  91734. for (var i = 0; i < 2; i++) {
  91735. for (var j = 0; j < 2; j++) {
  91736. for (var k = 0; k < 2; k++) {
  91737. var index = ((i * 4) + (j * 2)) + k;
  91738. if (scaleBoxes[index]) {
  91739. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  91740. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91741. if (this.fixedDragMeshScreenSize) {
  91742. this._rootMesh.computeWorldMatrix();
  91743. this._scaleBoxesParent.computeWorldMatrix();
  91744. scaleBoxes[index].computeWorldMatrix();
  91745. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  91746. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  91747. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  91748. }
  91749. else {
  91750. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  91751. }
  91752. }
  91753. }
  91754. }
  91755. }
  91756. if (this.attachedMesh) {
  91757. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  91758. }
  91759. };
  91760. /**
  91761. * Enables rotation on the specified axis and disables rotation on the others
  91762. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  91763. */
  91764. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  91765. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  91766. if (i < 4) {
  91767. m.setEnabled(axis.indexOf("x") != -1);
  91768. }
  91769. else if (i < 8) {
  91770. m.setEnabled(axis.indexOf("y") != -1);
  91771. }
  91772. else {
  91773. m.setEnabled(axis.indexOf("z") != -1);
  91774. }
  91775. });
  91776. };
  91777. /**
  91778. * Disposes of the gizmo
  91779. */
  91780. BoundingBoxGizmo.prototype.dispose = function () {
  91781. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91782. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  91783. this._lineBoundingBox.dispose();
  91784. this._rotateSpheresParent.dispose();
  91785. this._scaleBoxesParent.dispose();
  91786. _super.prototype.dispose.call(this);
  91787. };
  91788. /**
  91789. * 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)
  91790. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  91791. * @returns the bounding box mesh with the passed in mesh as a child
  91792. */
  91793. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  91794. var makeNotPickable = function (root) {
  91795. root.isPickable = false;
  91796. root.getChildMeshes().forEach(function (c) {
  91797. makeNotPickable(c);
  91798. });
  91799. };
  91800. makeNotPickable(mesh);
  91801. // Reset position to get boudning box from origin with no rotation
  91802. if (!mesh.rotationQuaternion) {
  91803. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  91804. }
  91805. var oldPos = mesh.position.clone();
  91806. var oldRot = mesh.rotationQuaternion.clone();
  91807. mesh.rotationQuaternion.set(0, 0, 0, 1);
  91808. mesh.position.set(0, 0, 0);
  91809. // Update bounding dimensions/positions
  91810. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  91811. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  91812. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  91813. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  91814. // Restore original positions
  91815. mesh.addChild(box);
  91816. mesh.rotationQuaternion.copyFrom(oldRot);
  91817. mesh.position.copyFrom(oldPos);
  91818. // Reverse parenting
  91819. mesh.removeChild(box);
  91820. box.addChild(mesh);
  91821. box.visibility = 0;
  91822. return box;
  91823. };
  91824. /**
  91825. * CustomMeshes are not supported by this gizmo
  91826. * @param mesh The mesh to replace the default mesh of the gizmo
  91827. */
  91828. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  91829. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  91830. };
  91831. return BoundingBoxGizmo;
  91832. }(BABYLON.Gizmo));
  91833. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  91834. })(BABYLON || (BABYLON = {}));
  91835. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  91836. var BABYLON;
  91837. (function (BABYLON) {
  91838. /**
  91839. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  91840. */
  91841. var GizmoManager = /** @class */ (function () {
  91842. /**
  91843. * Instatiates a gizmo manager
  91844. * @param scene the scene to overlay the gizmos on top of
  91845. */
  91846. function GizmoManager(scene) {
  91847. var _this = this;
  91848. this.scene = scene;
  91849. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  91850. this._pointerObserver = null;
  91851. this._attachedMesh = null;
  91852. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  91853. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  91854. /**
  91855. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  91856. */
  91857. this.attachableMeshes = null;
  91858. /**
  91859. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  91860. */
  91861. this.usePointerToAttachGizmos = true;
  91862. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  91863. // Instatiate/dispose gizmos based on pointer actions
  91864. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  91865. if (!_this.usePointerToAttachGizmos) {
  91866. return;
  91867. }
  91868. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91869. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  91870. var node = pointerInfo.pickInfo.pickedMesh;
  91871. if (_this.attachableMeshes == null) {
  91872. // Attach to the most parent node
  91873. while (node && node.parent != null) {
  91874. node = node.parent;
  91875. }
  91876. }
  91877. else {
  91878. // Attach to the parent node that is an attachableMesh
  91879. var found = false;
  91880. _this.attachableMeshes.forEach(function (mesh) {
  91881. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  91882. node = mesh;
  91883. found = true;
  91884. }
  91885. });
  91886. if (!found) {
  91887. node = null;
  91888. }
  91889. }
  91890. if (node instanceof BABYLON.AbstractMesh) {
  91891. _this.attachToMesh(node);
  91892. }
  91893. }
  91894. else {
  91895. _this.attachToMesh(null);
  91896. }
  91897. }
  91898. });
  91899. }
  91900. /**
  91901. * Attaches a set of gizmos to the specified mesh
  91902. * @param mesh The mesh the gizmo's should be attached to
  91903. */
  91904. GizmoManager.prototype.attachToMesh = function (mesh) {
  91905. if (this._attachedMesh) {
  91906. this._attachedMesh.removeBehavior(this._dragBehavior);
  91907. }
  91908. this._attachedMesh = mesh;
  91909. for (var key in this.gizmos) {
  91910. var gizmo = (this.gizmos[key]);
  91911. if (gizmo && this._gizmosEnabled[key]) {
  91912. gizmo.attachedMesh = mesh;
  91913. }
  91914. }
  91915. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  91916. this._attachedMesh.addBehavior(this._dragBehavior);
  91917. }
  91918. };
  91919. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  91920. get: function () {
  91921. return this._gizmosEnabled.positionGizmo;
  91922. },
  91923. /**
  91924. * If the position gizmo is enabled
  91925. */
  91926. set: function (value) {
  91927. if (value) {
  91928. this.gizmos.positionGizmo = this.gizmos.positionGizmo || new BABYLON.PositionGizmo();
  91929. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91930. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  91931. }
  91932. else if (this.gizmos.positionGizmo) {
  91933. this.gizmos.positionGizmo.attachedMesh = null;
  91934. }
  91935. this._gizmosEnabled.positionGizmo = value;
  91936. },
  91937. enumerable: true,
  91938. configurable: true
  91939. });
  91940. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  91941. get: function () {
  91942. return this._gizmosEnabled.rotationGizmo;
  91943. },
  91944. /**
  91945. * If the rotation gizmo is enabled
  91946. */
  91947. set: function (value) {
  91948. if (value) {
  91949. this.gizmos.rotationGizmo = this.gizmos.rotationGizmo || new BABYLON.RotationGizmo();
  91950. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91951. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  91952. }
  91953. else if (this.gizmos.rotationGizmo) {
  91954. this.gizmos.rotationGizmo.attachedMesh = null;
  91955. }
  91956. this._gizmosEnabled.rotationGizmo = value;
  91957. },
  91958. enumerable: true,
  91959. configurable: true
  91960. });
  91961. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  91962. get: function () {
  91963. return this._gizmosEnabled.scaleGizmo;
  91964. },
  91965. /**
  91966. * If the scale gizmo is enabled
  91967. */
  91968. set: function (value) {
  91969. if (value) {
  91970. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  91971. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  91972. }
  91973. else if (this.gizmos.scaleGizmo) {
  91974. this.gizmos.scaleGizmo.attachedMesh = null;
  91975. }
  91976. this._gizmosEnabled.scaleGizmo = value;
  91977. },
  91978. enumerable: true,
  91979. configurable: true
  91980. });
  91981. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  91982. get: function () {
  91983. return this._gizmosEnabled.boundingBoxGizmo;
  91984. },
  91985. /**
  91986. * If the boundingBox gizmo is enabled
  91987. */
  91988. set: function (value) {
  91989. if (value) {
  91990. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  91991. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  91992. if (this._attachedMesh) {
  91993. this._attachedMesh.removeBehavior(this._dragBehavior);
  91994. this._attachedMesh.addBehavior(this._dragBehavior);
  91995. }
  91996. }
  91997. else if (this.gizmos.boundingBoxGizmo) {
  91998. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  91999. }
  92000. this._gizmosEnabled.boundingBoxGizmo = value;
  92001. },
  92002. enumerable: true,
  92003. configurable: true
  92004. });
  92005. /**
  92006. * Disposes of the gizmo manager
  92007. */
  92008. GizmoManager.prototype.dispose = function () {
  92009. this.scene.onPointerObservable.remove(this._pointerObserver);
  92010. for (var key in this.gizmos) {
  92011. var gizmo = (this.gizmos[key]);
  92012. if (gizmo) {
  92013. gizmo.dispose();
  92014. }
  92015. }
  92016. this._dragBehavior.detach();
  92017. this._gizmoLayer.dispose();
  92018. };
  92019. return GizmoManager;
  92020. }());
  92021. BABYLON.GizmoManager = GizmoManager;
  92022. })(BABYLON || (BABYLON = {}));
  92023. //# sourceMappingURL=babylon.gizmoManager.js.map
  92024. var BABYLON;
  92025. (function (BABYLON) {
  92026. /**
  92027. * Defines a target to use with MorphTargetManager
  92028. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  92029. */
  92030. var MorphTarget = /** @class */ (function () {
  92031. /**
  92032. * Creates a new MorphTarget
  92033. * @param name defines the name of the target
  92034. * @param influence defines the influence to use
  92035. */
  92036. function MorphTarget(
  92037. /** defines the name of the target */
  92038. name, influence, scene) {
  92039. if (influence === void 0) { influence = 0; }
  92040. if (scene === void 0) { scene = null; }
  92041. this.name = name;
  92042. /**
  92043. * Gets or sets the list of animations
  92044. */
  92045. this.animations = new Array();
  92046. this._positions = null;
  92047. this._normals = null;
  92048. this._tangents = null;
  92049. /**
  92050. * Observable raised when the influence changes
  92051. */
  92052. this.onInfluenceChanged = new BABYLON.Observable();
  92053. this._animationPropertiesOverride = null;
  92054. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92055. this.influence = influence;
  92056. }
  92057. Object.defineProperty(MorphTarget.prototype, "influence", {
  92058. /**
  92059. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  92060. */
  92061. get: function () {
  92062. return this._influence;
  92063. },
  92064. set: function (influence) {
  92065. if (this._influence === influence) {
  92066. return;
  92067. }
  92068. var previous = this._influence;
  92069. this._influence = influence;
  92070. if (this.onInfluenceChanged.hasObservers) {
  92071. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  92072. }
  92073. },
  92074. enumerable: true,
  92075. configurable: true
  92076. });
  92077. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  92078. /**
  92079. * Gets or sets the animation properties override
  92080. */
  92081. get: function () {
  92082. if (!this._animationPropertiesOverride && this._scene) {
  92083. return this._scene.animationPropertiesOverride;
  92084. }
  92085. return this._animationPropertiesOverride;
  92086. },
  92087. set: function (value) {
  92088. this._animationPropertiesOverride = value;
  92089. },
  92090. enumerable: true,
  92091. configurable: true
  92092. });
  92093. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  92094. /**
  92095. * Gets a boolean defining if the target contains position data
  92096. */
  92097. get: function () {
  92098. return !!this._positions;
  92099. },
  92100. enumerable: true,
  92101. configurable: true
  92102. });
  92103. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  92104. /**
  92105. * Gets a boolean defining if the target contains normal data
  92106. */
  92107. get: function () {
  92108. return !!this._normals;
  92109. },
  92110. enumerable: true,
  92111. configurable: true
  92112. });
  92113. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  92114. /**
  92115. * Gets a boolean defining if the target contains tangent data
  92116. */
  92117. get: function () {
  92118. return !!this._tangents;
  92119. },
  92120. enumerable: true,
  92121. configurable: true
  92122. });
  92123. /**
  92124. * Affects position data to this target
  92125. * @param data defines the position data to use
  92126. */
  92127. MorphTarget.prototype.setPositions = function (data) {
  92128. this._positions = data;
  92129. };
  92130. /**
  92131. * Gets the position data stored in this target
  92132. * @returns a FloatArray containing the position data (or null if not present)
  92133. */
  92134. MorphTarget.prototype.getPositions = function () {
  92135. return this._positions;
  92136. };
  92137. /**
  92138. * Affects normal data to this target
  92139. * @param data defines the normal data to use
  92140. */
  92141. MorphTarget.prototype.setNormals = function (data) {
  92142. this._normals = data;
  92143. };
  92144. /**
  92145. * Gets the normal data stored in this target
  92146. * @returns a FloatArray containing the normal data (or null if not present)
  92147. */
  92148. MorphTarget.prototype.getNormals = function () {
  92149. return this._normals;
  92150. };
  92151. /**
  92152. * Affects tangent data to this target
  92153. * @param data defines the tangent data to use
  92154. */
  92155. MorphTarget.prototype.setTangents = function (data) {
  92156. this._tangents = data;
  92157. };
  92158. /**
  92159. * Gets the tangent data stored in this target
  92160. * @returns a FloatArray containing the tangent data (or null if not present)
  92161. */
  92162. MorphTarget.prototype.getTangents = function () {
  92163. return this._tangents;
  92164. };
  92165. /**
  92166. * Serializes the current target into a Serialization object
  92167. * @returns the serialized object
  92168. */
  92169. MorphTarget.prototype.serialize = function () {
  92170. var serializationObject = {};
  92171. serializationObject.name = this.name;
  92172. serializationObject.influence = this.influence;
  92173. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  92174. if (this.hasNormals) {
  92175. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  92176. }
  92177. if (this.hasTangents) {
  92178. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  92179. }
  92180. // Animations
  92181. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  92182. return serializationObject;
  92183. };
  92184. // Statics
  92185. /**
  92186. * Creates a new target from serialized data
  92187. * @param serializationObject defines the serialized data to use
  92188. * @returns a new MorphTarget
  92189. */
  92190. MorphTarget.Parse = function (serializationObject) {
  92191. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  92192. result.setPositions(serializationObject.positions);
  92193. if (serializationObject.normals) {
  92194. result.setNormals(serializationObject.normals);
  92195. }
  92196. if (serializationObject.tangents) {
  92197. result.setTangents(serializationObject.tangents);
  92198. }
  92199. // Animations
  92200. if (serializationObject.animations) {
  92201. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  92202. var parsedAnimation = serializationObject.animations[animationIndex];
  92203. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  92204. }
  92205. }
  92206. return result;
  92207. };
  92208. /**
  92209. * Creates a MorphTarget from mesh data
  92210. * @param mesh defines the source mesh
  92211. * @param name defines the name to use for the new target
  92212. * @param influence defines the influence to attach to the target
  92213. * @returns a new MorphTarget
  92214. */
  92215. MorphTarget.FromMesh = function (mesh, name, influence) {
  92216. if (!name) {
  92217. name = mesh.name;
  92218. }
  92219. var result = new MorphTarget(name, influence, mesh.getScene());
  92220. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  92221. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  92222. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  92223. }
  92224. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  92225. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  92226. }
  92227. return result;
  92228. };
  92229. return MorphTarget;
  92230. }());
  92231. BABYLON.MorphTarget = MorphTarget;
  92232. })(BABYLON || (BABYLON = {}));
  92233. //# sourceMappingURL=babylon.morphTarget.js.map
  92234. var BABYLON;
  92235. (function (BABYLON) {
  92236. /**
  92237. * This class is used to deform meshes using morphing between different targets
  92238. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  92239. */
  92240. var MorphTargetManager = /** @class */ (function () {
  92241. /**
  92242. * Creates a new MorphTargetManager
  92243. * @param scene defines the current scene
  92244. */
  92245. function MorphTargetManager(scene) {
  92246. if (scene === void 0) { scene = null; }
  92247. this._targets = new Array();
  92248. this._targetObservable = new Array();
  92249. this._activeTargets = new BABYLON.SmartArray(16);
  92250. this._supportsNormals = false;
  92251. this._supportsTangents = false;
  92252. this._vertexCount = 0;
  92253. this._uniqueId = 0;
  92254. this._tempInfluences = new Array();
  92255. if (!scene) {
  92256. scene = BABYLON.Engine.LastCreatedScene;
  92257. }
  92258. this._scene = scene;
  92259. if (this._scene) {
  92260. this._scene.morphTargetManagers.push(this);
  92261. this._uniqueId = this._scene.getUniqueId();
  92262. }
  92263. }
  92264. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  92265. /**
  92266. * Gets the unique ID of this manager
  92267. */
  92268. get: function () {
  92269. return this._uniqueId;
  92270. },
  92271. enumerable: true,
  92272. configurable: true
  92273. });
  92274. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  92275. /**
  92276. * Gets the number of vertices handled by this manager
  92277. */
  92278. get: function () {
  92279. return this._vertexCount;
  92280. },
  92281. enumerable: true,
  92282. configurable: true
  92283. });
  92284. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  92285. /**
  92286. * Gets a boolean indicating if this manager supports morphing of normals
  92287. */
  92288. get: function () {
  92289. return this._supportsNormals;
  92290. },
  92291. enumerable: true,
  92292. configurable: true
  92293. });
  92294. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  92295. /**
  92296. * Gets a boolean indicating if this manager supports morphing of tangents
  92297. */
  92298. get: function () {
  92299. return this._supportsTangents;
  92300. },
  92301. enumerable: true,
  92302. configurable: true
  92303. });
  92304. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  92305. /**
  92306. * Gets the number of targets stored in this manager
  92307. */
  92308. get: function () {
  92309. return this._targets.length;
  92310. },
  92311. enumerable: true,
  92312. configurable: true
  92313. });
  92314. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  92315. /**
  92316. * Gets the number of influencers (ie. the number of targets with influences > 0)
  92317. */
  92318. get: function () {
  92319. return this._activeTargets.length;
  92320. },
  92321. enumerable: true,
  92322. configurable: true
  92323. });
  92324. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  92325. /**
  92326. * Gets the list of influences (one per target)
  92327. */
  92328. get: function () {
  92329. return this._influences;
  92330. },
  92331. enumerable: true,
  92332. configurable: true
  92333. });
  92334. /**
  92335. * Gets the active target at specified index. An active target is a target with an influence > 0
  92336. * @param index defines the index to check
  92337. * @returns the requested target
  92338. */
  92339. MorphTargetManager.prototype.getActiveTarget = function (index) {
  92340. return this._activeTargets.data[index];
  92341. };
  92342. /**
  92343. * Gets the target at specified index
  92344. * @param index defines the index to check
  92345. * @returns the requested target
  92346. */
  92347. MorphTargetManager.prototype.getTarget = function (index) {
  92348. return this._targets[index];
  92349. };
  92350. /**
  92351. * Add a new target to this manager
  92352. * @param target defines the target to add
  92353. */
  92354. MorphTargetManager.prototype.addTarget = function (target) {
  92355. var _this = this;
  92356. this._targets.push(target);
  92357. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  92358. _this._syncActiveTargets(needUpdate);
  92359. }));
  92360. this._syncActiveTargets(true);
  92361. };
  92362. /**
  92363. * Removes a target from the manager
  92364. * @param target defines the target to remove
  92365. */
  92366. MorphTargetManager.prototype.removeTarget = function (target) {
  92367. var index = this._targets.indexOf(target);
  92368. if (index >= 0) {
  92369. this._targets.splice(index, 1);
  92370. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  92371. this._syncActiveTargets(true);
  92372. }
  92373. };
  92374. /**
  92375. * Serializes the current manager into a Serialization object
  92376. * @returns the serialized object
  92377. */
  92378. MorphTargetManager.prototype.serialize = function () {
  92379. var serializationObject = {};
  92380. serializationObject.id = this.uniqueId;
  92381. serializationObject.targets = [];
  92382. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  92383. var target = _a[_i];
  92384. serializationObject.targets.push(target.serialize());
  92385. }
  92386. return serializationObject;
  92387. };
  92388. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  92389. var influenceCount = 0;
  92390. this._activeTargets.reset();
  92391. this._supportsNormals = true;
  92392. this._supportsTangents = true;
  92393. this._vertexCount = 0;
  92394. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  92395. var target = _a[_i];
  92396. this._activeTargets.push(target);
  92397. this._tempInfluences[influenceCount++] = target.influence;
  92398. var positions = target.getPositions();
  92399. if (positions) {
  92400. this._supportsNormals = this._supportsNormals && target.hasNormals;
  92401. this._supportsTangents = this._supportsTangents && target.hasTangents;
  92402. var vertexCount = positions.length / 3;
  92403. if (this._vertexCount === 0) {
  92404. this._vertexCount = vertexCount;
  92405. }
  92406. else if (this._vertexCount !== vertexCount) {
  92407. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  92408. return;
  92409. }
  92410. }
  92411. }
  92412. if (!this._influences || this._influences.length !== influenceCount) {
  92413. this._influences = new Float32Array(influenceCount);
  92414. }
  92415. for (var index = 0; index < influenceCount; index++) {
  92416. this._influences[index] = this._tempInfluences[index];
  92417. }
  92418. if (needUpdate) {
  92419. this.synchronize();
  92420. }
  92421. };
  92422. /**
  92423. * Syncrhonize the targets with all the meshes using this morph target manager
  92424. */
  92425. MorphTargetManager.prototype.synchronize = function () {
  92426. if (!this._scene) {
  92427. return;
  92428. }
  92429. // Flag meshes as dirty to resync with the active targets
  92430. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  92431. var mesh = _a[_i];
  92432. if (mesh.morphTargetManager === this) {
  92433. mesh._syncGeometryWithMorphTargetManager();
  92434. }
  92435. }
  92436. };
  92437. // Statics
  92438. /**
  92439. * Creates a new MorphTargetManager from serialized data
  92440. * @param serializationObject defines the serialized data
  92441. * @param scene defines the hosting scene
  92442. * @returns the new MorphTargetManager
  92443. */
  92444. MorphTargetManager.Parse = function (serializationObject, scene) {
  92445. var result = new MorphTargetManager(scene);
  92446. result._uniqueId = serializationObject.id;
  92447. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  92448. var targetData = _a[_i];
  92449. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  92450. }
  92451. return result;
  92452. };
  92453. return MorphTargetManager;
  92454. }());
  92455. BABYLON.MorphTargetManager = MorphTargetManager;
  92456. })(BABYLON || (BABYLON = {}));
  92457. //# sourceMappingURL=babylon.morphTargetManager.js.map
  92458. var BABYLON;
  92459. (function (BABYLON) {
  92460. var Octree = /** @class */ (function () {
  92461. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  92462. if (maxDepth === void 0) { maxDepth = 2; }
  92463. this.maxDepth = maxDepth;
  92464. this.dynamicContent = new Array();
  92465. this._maxBlockCapacity = maxBlockCapacity || 64;
  92466. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  92467. this._creationFunc = creationFunc;
  92468. }
  92469. // Methods
  92470. Octree.prototype.update = function (worldMin, worldMax, entries) {
  92471. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  92472. };
  92473. Octree.prototype.addMesh = function (entry) {
  92474. for (var index = 0; index < this.blocks.length; index++) {
  92475. var block = this.blocks[index];
  92476. block.addEntry(entry);
  92477. }
  92478. };
  92479. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  92480. this._selectionContent.reset();
  92481. for (var index = 0; index < this.blocks.length; index++) {
  92482. var block = this.blocks[index];
  92483. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  92484. }
  92485. if (allowDuplicate) {
  92486. this._selectionContent.concat(this.dynamicContent);
  92487. }
  92488. else {
  92489. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  92490. }
  92491. return this._selectionContent;
  92492. };
  92493. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  92494. this._selectionContent.reset();
  92495. for (var index = 0; index < this.blocks.length; index++) {
  92496. var block = this.blocks[index];
  92497. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  92498. }
  92499. if (allowDuplicate) {
  92500. this._selectionContent.concat(this.dynamicContent);
  92501. }
  92502. else {
  92503. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  92504. }
  92505. return this._selectionContent;
  92506. };
  92507. Octree.prototype.intersectsRay = function (ray) {
  92508. this._selectionContent.reset();
  92509. for (var index = 0; index < this.blocks.length; index++) {
  92510. var block = this.blocks[index];
  92511. block.intersectsRay(ray, this._selectionContent);
  92512. }
  92513. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  92514. return this._selectionContent;
  92515. };
  92516. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  92517. target.blocks = new Array();
  92518. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  92519. // Segmenting space
  92520. for (var x = 0; x < 2; x++) {
  92521. for (var y = 0; y < 2; y++) {
  92522. for (var z = 0; z < 2; z++) {
  92523. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  92524. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  92525. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  92526. block.addEntries(entries);
  92527. target.blocks.push(block);
  92528. }
  92529. }
  92530. }
  92531. };
  92532. Octree.CreationFuncForMeshes = function (entry, block) {
  92533. var boundingInfo = entry.getBoundingInfo();
  92534. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  92535. block.entries.push(entry);
  92536. }
  92537. };
  92538. Octree.CreationFuncForSubMeshes = function (entry, block) {
  92539. var boundingInfo = entry.getBoundingInfo();
  92540. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  92541. block.entries.push(entry);
  92542. }
  92543. };
  92544. return Octree;
  92545. }());
  92546. BABYLON.Octree = Octree;
  92547. })(BABYLON || (BABYLON = {}));
  92548. //# sourceMappingURL=babylon.octree.js.map
  92549. var BABYLON;
  92550. (function (BABYLON) {
  92551. var OctreeBlock = /** @class */ (function () {
  92552. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  92553. this.entries = new Array();
  92554. this._boundingVectors = new Array();
  92555. this._capacity = capacity;
  92556. this._depth = depth;
  92557. this._maxDepth = maxDepth;
  92558. this._creationFunc = creationFunc;
  92559. this._minPoint = minPoint;
  92560. this._maxPoint = maxPoint;
  92561. this._boundingVectors.push(minPoint.clone());
  92562. this._boundingVectors.push(maxPoint.clone());
  92563. this._boundingVectors.push(minPoint.clone());
  92564. this._boundingVectors[2].x = maxPoint.x;
  92565. this._boundingVectors.push(minPoint.clone());
  92566. this._boundingVectors[3].y = maxPoint.y;
  92567. this._boundingVectors.push(minPoint.clone());
  92568. this._boundingVectors[4].z = maxPoint.z;
  92569. this._boundingVectors.push(maxPoint.clone());
  92570. this._boundingVectors[5].z = minPoint.z;
  92571. this._boundingVectors.push(maxPoint.clone());
  92572. this._boundingVectors[6].x = minPoint.x;
  92573. this._boundingVectors.push(maxPoint.clone());
  92574. this._boundingVectors[7].y = minPoint.y;
  92575. }
  92576. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  92577. // Property
  92578. get: function () {
  92579. return this._capacity;
  92580. },
  92581. enumerable: true,
  92582. configurable: true
  92583. });
  92584. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  92585. get: function () {
  92586. return this._minPoint;
  92587. },
  92588. enumerable: true,
  92589. configurable: true
  92590. });
  92591. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  92592. get: function () {
  92593. return this._maxPoint;
  92594. },
  92595. enumerable: true,
  92596. configurable: true
  92597. });
  92598. // Methods
  92599. OctreeBlock.prototype.addEntry = function (entry) {
  92600. if (this.blocks) {
  92601. for (var index = 0; index < this.blocks.length; index++) {
  92602. var block = this.blocks[index];
  92603. block.addEntry(entry);
  92604. }
  92605. return;
  92606. }
  92607. this._creationFunc(entry, this);
  92608. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  92609. this.createInnerBlocks();
  92610. }
  92611. };
  92612. OctreeBlock.prototype.addEntries = function (entries) {
  92613. for (var index = 0; index < entries.length; index++) {
  92614. var mesh = entries[index];
  92615. this.addEntry(mesh);
  92616. }
  92617. };
  92618. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  92619. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  92620. if (this.blocks) {
  92621. for (var index = 0; index < this.blocks.length; index++) {
  92622. var block = this.blocks[index];
  92623. block.select(frustumPlanes, selection, allowDuplicate);
  92624. }
  92625. return;
  92626. }
  92627. if (allowDuplicate) {
  92628. selection.concat(this.entries);
  92629. }
  92630. else {
  92631. selection.concatWithNoDuplicate(this.entries);
  92632. }
  92633. }
  92634. };
  92635. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  92636. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  92637. if (this.blocks) {
  92638. for (var index = 0; index < this.blocks.length; index++) {
  92639. var block = this.blocks[index];
  92640. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  92641. }
  92642. return;
  92643. }
  92644. if (allowDuplicate) {
  92645. selection.concat(this.entries);
  92646. }
  92647. else {
  92648. selection.concatWithNoDuplicate(this.entries);
  92649. }
  92650. }
  92651. };
  92652. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  92653. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  92654. if (this.blocks) {
  92655. for (var index = 0; index < this.blocks.length; index++) {
  92656. var block = this.blocks[index];
  92657. block.intersectsRay(ray, selection);
  92658. }
  92659. return;
  92660. }
  92661. selection.concatWithNoDuplicate(this.entries);
  92662. }
  92663. };
  92664. OctreeBlock.prototype.createInnerBlocks = function () {
  92665. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  92666. };
  92667. return OctreeBlock;
  92668. }());
  92669. BABYLON.OctreeBlock = OctreeBlock;
  92670. })(BABYLON || (BABYLON = {}));
  92671. //# sourceMappingURL=babylon.octreeBlock.js.map
  92672. var BABYLON;
  92673. (function (BABYLON) {
  92674. /**
  92675. * Postprocess used to generate anaglyphic rendering
  92676. */
  92677. var AnaglyphPostProcess = /** @class */ (function (_super) {
  92678. __extends(AnaglyphPostProcess, _super);
  92679. /**
  92680. * Creates a new AnaglyphPostProcess
  92681. * @param name defines postprocess name
  92682. * @param options defines creation options or target ratio scale
  92683. * @param rigCameras defines cameras using this postprocess
  92684. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  92685. * @param engine defines hosting engine
  92686. * @param reusable defines if the postprocess will be reused multiple times per frame
  92687. */
  92688. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  92689. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  92690. _this._passedProcess = rigCameras[0]._rigPostProcess;
  92691. _this.onApplyObservable.add(function (effect) {
  92692. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  92693. });
  92694. return _this;
  92695. }
  92696. return AnaglyphPostProcess;
  92697. }(BABYLON.PostProcess));
  92698. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  92699. })(BABYLON || (BABYLON = {}));
  92700. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  92701. var BABYLON;
  92702. (function (BABYLON) {
  92703. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  92704. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92705. });
  92706. /**
  92707. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  92708. */
  92709. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  92710. __extends(AnaglyphArcRotateCamera, _super);
  92711. /**
  92712. * Creates a new AnaglyphArcRotateCamera
  92713. * @param name defines camera name
  92714. * @param alpha defines alpha angle (in radians)
  92715. * @param beta defines beta angle (in radians)
  92716. * @param radius defines radius
  92717. * @param target defines camera target
  92718. * @param interaxialDistance defines distance between each color axis
  92719. * @param scene defines the hosting scene
  92720. */
  92721. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  92722. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92723. _this.interaxialDistance = interaxialDistance;
  92724. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92725. return _this;
  92726. }
  92727. /**
  92728. * Gets camera class name
  92729. * @returns AnaglyphArcRotateCamera
  92730. */
  92731. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  92732. return "AnaglyphArcRotateCamera";
  92733. };
  92734. return AnaglyphArcRotateCamera;
  92735. }(BABYLON.ArcRotateCamera));
  92736. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  92737. })(BABYLON || (BABYLON = {}));
  92738. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  92739. var BABYLON;
  92740. (function (BABYLON) {
  92741. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  92742. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92743. });
  92744. /**
  92745. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  92746. */
  92747. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  92748. __extends(AnaglyphFreeCamera, _super);
  92749. /**
  92750. * Creates a new AnaglyphFreeCamera
  92751. * @param name defines camera name
  92752. * @param position defines initial position
  92753. * @param interaxialDistance defines distance between each color axis
  92754. * @param scene defines the hosting scene
  92755. */
  92756. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  92757. var _this = _super.call(this, name, position, scene) || this;
  92758. _this.interaxialDistance = interaxialDistance;
  92759. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92760. return _this;
  92761. }
  92762. /**
  92763. * Gets camera class name
  92764. * @returns AnaglyphFreeCamera
  92765. */
  92766. AnaglyphFreeCamera.prototype.getClassName = function () {
  92767. return "AnaglyphFreeCamera";
  92768. };
  92769. return AnaglyphFreeCamera;
  92770. }(BABYLON.FreeCamera));
  92771. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  92772. })(BABYLON || (BABYLON = {}));
  92773. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  92774. var BABYLON;
  92775. (function (BABYLON) {
  92776. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  92777. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92778. });
  92779. /**
  92780. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  92781. */
  92782. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  92783. __extends(AnaglyphGamepadCamera, _super);
  92784. /**
  92785. * Creates a new AnaglyphGamepadCamera
  92786. * @param name defines camera name
  92787. * @param position defines initial position
  92788. * @param interaxialDistance defines distance between each color axis
  92789. * @param scene defines the hosting scene
  92790. */
  92791. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  92792. var _this = _super.call(this, name, position, scene) || this;
  92793. _this.interaxialDistance = interaxialDistance;
  92794. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92795. return _this;
  92796. }
  92797. /**
  92798. * Gets camera class name
  92799. * @returns AnaglyphGamepadCamera
  92800. */
  92801. AnaglyphGamepadCamera.prototype.getClassName = function () {
  92802. return "AnaglyphGamepadCamera";
  92803. };
  92804. return AnaglyphGamepadCamera;
  92805. }(BABYLON.GamepadCamera));
  92806. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  92807. })(BABYLON || (BABYLON = {}));
  92808. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  92809. var BABYLON;
  92810. (function (BABYLON) {
  92811. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  92812. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92813. });
  92814. /**
  92815. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  92816. */
  92817. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  92818. __extends(AnaglyphUniversalCamera, _super);
  92819. /**
  92820. * Creates a new AnaglyphUniversalCamera
  92821. * @param name defines camera name
  92822. * @param position defines initial position
  92823. * @param interaxialDistance defines distance between each color axis
  92824. * @param scene defines the hosting scene
  92825. */
  92826. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  92827. var _this = _super.call(this, name, position, scene) || this;
  92828. _this.interaxialDistance = interaxialDistance;
  92829. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92830. return _this;
  92831. }
  92832. /**
  92833. * Gets camera class name
  92834. * @returns AnaglyphUniversalCamera
  92835. */
  92836. AnaglyphUniversalCamera.prototype.getClassName = function () {
  92837. return "AnaglyphUniversalCamera";
  92838. };
  92839. return AnaglyphUniversalCamera;
  92840. }(BABYLON.UniversalCamera));
  92841. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  92842. })(BABYLON || (BABYLON = {}));
  92843. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  92844. var BABYLON;
  92845. (function (BABYLON) {
  92846. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  92847. __extends(StereoscopicInterlacePostProcess, _super);
  92848. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  92849. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  92850. _this._passedProcess = rigCameras[0]._rigPostProcess;
  92851. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92852. _this.onSizeChangedObservable.add(function () {
  92853. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92854. });
  92855. _this.onApplyObservable.add(function (effect) {
  92856. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  92857. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  92858. });
  92859. return _this;
  92860. }
  92861. return StereoscopicInterlacePostProcess;
  92862. }(BABYLON.PostProcess));
  92863. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  92864. })(BABYLON || (BABYLON = {}));
  92865. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  92866. var BABYLON;
  92867. (function (BABYLON) {
  92868. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  92869. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92870. });
  92871. /**
  92872. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  92873. */
  92874. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  92875. __extends(StereoscopicArcRotateCamera, _super);
  92876. /**
  92877. * Creates a new StereoscopicArcRotateCamera
  92878. * @param name defines camera name
  92879. * @param alpha defines alpha angle (in radians)
  92880. * @param beta defines beta angle (in radians)
  92881. * @param radius defines radius
  92882. * @param target defines camera target
  92883. * @param interaxialDistance defines distance between each color axis
  92884. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92885. * @param scene defines the hosting scene
  92886. */
  92887. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  92888. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92889. _this.interaxialDistance = interaxialDistance;
  92890. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92891. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92892. return _this;
  92893. }
  92894. /**
  92895. * Gets camera class name
  92896. * @returns StereoscopicArcRotateCamera
  92897. */
  92898. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  92899. return "StereoscopicArcRotateCamera";
  92900. };
  92901. return StereoscopicArcRotateCamera;
  92902. }(BABYLON.ArcRotateCamera));
  92903. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  92904. })(BABYLON || (BABYLON = {}));
  92905. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  92906. var BABYLON;
  92907. (function (BABYLON) {
  92908. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92909. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92910. });
  92911. /**
  92912. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  92913. */
  92914. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  92915. __extends(StereoscopicFreeCamera, _super);
  92916. /**
  92917. * Creates a new StereoscopicFreeCamera
  92918. * @param name defines camera name
  92919. * @param position defines initial position
  92920. * @param interaxialDistance defines distance between each color axis
  92921. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92922. * @param scene defines the hosting scene
  92923. */
  92924. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92925. var _this = _super.call(this, name, position, scene) || this;
  92926. _this.interaxialDistance = interaxialDistance;
  92927. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92928. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92929. return _this;
  92930. }
  92931. /**
  92932. * Gets camera class name
  92933. * @returns StereoscopicFreeCamera
  92934. */
  92935. StereoscopicFreeCamera.prototype.getClassName = function () {
  92936. return "StereoscopicFreeCamera";
  92937. };
  92938. return StereoscopicFreeCamera;
  92939. }(BABYLON.FreeCamera));
  92940. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  92941. })(BABYLON || (BABYLON = {}));
  92942. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  92943. var BABYLON;
  92944. (function (BABYLON) {
  92945. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  92946. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92947. });
  92948. /**
  92949. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  92950. */
  92951. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  92952. __extends(StereoscopicGamepadCamera, _super);
  92953. /**
  92954. * Creates a new StereoscopicGamepadCamera
  92955. * @param name defines camera name
  92956. * @param position defines initial position
  92957. * @param interaxialDistance defines distance between each color axis
  92958. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92959. * @param scene defines the hosting scene
  92960. */
  92961. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92962. var _this = _super.call(this, name, position, scene) || this;
  92963. _this.interaxialDistance = interaxialDistance;
  92964. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92965. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92966. return _this;
  92967. }
  92968. /**
  92969. * Gets camera class name
  92970. * @returns StereoscopicGamepadCamera
  92971. */
  92972. StereoscopicGamepadCamera.prototype.getClassName = function () {
  92973. return "StereoscopicGamepadCamera";
  92974. };
  92975. return StereoscopicGamepadCamera;
  92976. }(BABYLON.GamepadCamera));
  92977. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  92978. })(BABYLON || (BABYLON = {}));
  92979. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  92980. var BABYLON;
  92981. (function (BABYLON) {
  92982. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92983. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92984. });
  92985. /**
  92986. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  92987. */
  92988. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  92989. __extends(StereoscopicUniversalCamera, _super);
  92990. /**
  92991. * Creates a new StereoscopicUniversalCamera
  92992. * @param name defines camera name
  92993. * @param position defines initial position
  92994. * @param interaxialDistance defines distance between each color axis
  92995. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92996. * @param scene defines the hosting scene
  92997. */
  92998. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92999. var _this = _super.call(this, name, position, scene) || this;
  93000. _this.interaxialDistance = interaxialDistance;
  93001. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  93002. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  93003. return _this;
  93004. }
  93005. /**
  93006. * Gets camera class name
  93007. * @returns StereoscopicUniversalCamera
  93008. */
  93009. StereoscopicUniversalCamera.prototype.getClassName = function () {
  93010. return "StereoscopicUniversalCamera";
  93011. };
  93012. return StereoscopicUniversalCamera;
  93013. }(BABYLON.UniversalCamera));
  93014. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  93015. })(BABYLON || (BABYLON = {}));
  93016. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  93017. var BABYLON;
  93018. (function (BABYLON) {
  93019. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  93020. __extends(VRDistortionCorrectionPostProcess, _super);
  93021. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  93022. var _this = _super.call(this, name, "vrDistortionCorrection", [
  93023. 'LensCenter',
  93024. 'Scale',
  93025. 'ScaleIn',
  93026. 'HmdWarpParam'
  93027. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  93028. _this._isRightEye = isRightEye;
  93029. _this._distortionFactors = vrMetrics.distortionK;
  93030. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  93031. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  93032. _this.adaptScaleToCurrentViewport = true;
  93033. _this.onSizeChangedObservable.add(function () {
  93034. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  93035. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  93036. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  93037. });
  93038. _this.onApplyObservable.add(function (effect) {
  93039. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  93040. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  93041. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  93042. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  93043. });
  93044. return _this;
  93045. }
  93046. return VRDistortionCorrectionPostProcess;
  93047. }(BABYLON.PostProcess));
  93048. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  93049. })(BABYLON || (BABYLON = {}));
  93050. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  93051. var BABYLON;
  93052. (function (BABYLON) {
  93053. /**
  93054. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  93055. * Screen rotation is taken into account.
  93056. */
  93057. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  93058. function FreeCameraDeviceOrientationInput() {
  93059. var _this = this;
  93060. this._screenOrientationAngle = 0;
  93061. this._screenQuaternion = new BABYLON.Quaternion();
  93062. this._alpha = 0;
  93063. this._beta = 0;
  93064. this._gamma = 0;
  93065. this._orientationChanged = function () {
  93066. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  93067. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  93068. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  93069. };
  93070. this._deviceOrientation = function (evt) {
  93071. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  93072. _this._beta = evt.beta !== null ? evt.beta : 0;
  93073. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  93074. };
  93075. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  93076. this._orientationChanged();
  93077. }
  93078. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  93079. get: function () {
  93080. return this._camera;
  93081. },
  93082. set: function (camera) {
  93083. this._camera = camera;
  93084. if (this._camera != null && !this._camera.rotationQuaternion) {
  93085. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  93086. }
  93087. },
  93088. enumerable: true,
  93089. configurable: true
  93090. });
  93091. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  93092. window.addEventListener("orientationchange", this._orientationChanged);
  93093. window.addEventListener("deviceorientation", this._deviceOrientation);
  93094. //In certain cases, the attach control is called AFTER orientation was changed,
  93095. //So this is needed.
  93096. this._orientationChanged();
  93097. };
  93098. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  93099. window.removeEventListener("orientationchange", this._orientationChanged);
  93100. window.removeEventListener("deviceorientation", this._deviceOrientation);
  93101. };
  93102. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  93103. //if no device orientation provided, don't update the rotation.
  93104. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  93105. if (!this._alpha)
  93106. return;
  93107. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  93108. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  93109. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  93110. //Mirror on XY Plane
  93111. this._camera.rotationQuaternion.z *= -1;
  93112. this._camera.rotationQuaternion.w *= -1;
  93113. };
  93114. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  93115. return "FreeCameraDeviceOrientationInput";
  93116. };
  93117. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  93118. return "deviceOrientation";
  93119. };
  93120. return FreeCameraDeviceOrientationInput;
  93121. }());
  93122. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  93123. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  93124. })(BABYLON || (BABYLON = {}));
  93125. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  93126. var BABYLON;
  93127. (function (BABYLON) {
  93128. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  93129. function ArcRotateCameraVRDeviceOrientationInput() {
  93130. this.alphaCorrection = 1;
  93131. this.betaCorrection = 1;
  93132. this.gammaCorrection = 1;
  93133. this._alpha = 0;
  93134. this._gamma = 0;
  93135. this._dirty = false;
  93136. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  93137. }
  93138. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  93139. this.camera.attachControl(element, noPreventDefault);
  93140. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  93141. };
  93142. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  93143. if (evt.alpha !== null) {
  93144. this._alpha = +evt.alpha | 0;
  93145. }
  93146. if (evt.gamma !== null) {
  93147. this._gamma = +evt.gamma | 0;
  93148. }
  93149. this._dirty = true;
  93150. };
  93151. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  93152. if (this._dirty) {
  93153. this._dirty = false;
  93154. if (this._gamma < 0) {
  93155. this._gamma = 180 + this._gamma;
  93156. }
  93157. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  93158. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  93159. }
  93160. };
  93161. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  93162. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  93163. };
  93164. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  93165. return "ArcRotateCameraVRDeviceOrientationInput";
  93166. };
  93167. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  93168. return "VRDeviceOrientation";
  93169. };
  93170. return ArcRotateCameraVRDeviceOrientationInput;
  93171. }());
  93172. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  93173. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  93174. })(BABYLON || (BABYLON = {}));
  93175. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  93176. var BABYLON;
  93177. (function (BABYLON) {
  93178. var VRCameraMetrics = /** @class */ (function () {
  93179. function VRCameraMetrics() {
  93180. this.compensateDistortion = true;
  93181. }
  93182. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  93183. get: function () {
  93184. return this.hResolution / (2 * this.vResolution);
  93185. },
  93186. enumerable: true,
  93187. configurable: true
  93188. });
  93189. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  93190. get: function () {
  93191. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  93192. },
  93193. enumerable: true,
  93194. configurable: true
  93195. });
  93196. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  93197. get: function () {
  93198. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  93199. var h = (4 * meters) / this.hScreenSize;
  93200. return BABYLON.Matrix.Translation(h, 0, 0);
  93201. },
  93202. enumerable: true,
  93203. configurable: true
  93204. });
  93205. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  93206. get: function () {
  93207. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  93208. var h = (4 * meters) / this.hScreenSize;
  93209. return BABYLON.Matrix.Translation(-h, 0, 0);
  93210. },
  93211. enumerable: true,
  93212. configurable: true
  93213. });
  93214. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  93215. get: function () {
  93216. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  93217. },
  93218. enumerable: true,
  93219. configurable: true
  93220. });
  93221. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  93222. get: function () {
  93223. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  93224. },
  93225. enumerable: true,
  93226. configurable: true
  93227. });
  93228. VRCameraMetrics.GetDefault = function () {
  93229. var result = new VRCameraMetrics();
  93230. result.hResolution = 1280;
  93231. result.vResolution = 800;
  93232. result.hScreenSize = 0.149759993;
  93233. result.vScreenSize = 0.0935999975;
  93234. result.vScreenCenter = 0.0467999987;
  93235. result.eyeToScreenDistance = 0.0410000011;
  93236. result.lensSeparationDistance = 0.0635000020;
  93237. result.interpupillaryDistance = 0.0640000030;
  93238. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  93239. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  93240. result.postProcessScaleFactor = 1.714605507808412;
  93241. result.lensCenterOffset = 0.151976421;
  93242. return result;
  93243. };
  93244. return VRCameraMetrics;
  93245. }());
  93246. BABYLON.VRCameraMetrics = VRCameraMetrics;
  93247. })(BABYLON || (BABYLON = {}));
  93248. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  93249. var BABYLON;
  93250. (function (BABYLON) {
  93251. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  93252. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93253. });
  93254. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  93255. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93256. });
  93257. /**
  93258. * This represents a WebVR camera.
  93259. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  93260. * @example http://doc.babylonjs.com/how_to/webvr_camera
  93261. */
  93262. var WebVRFreeCamera = /** @class */ (function (_super) {
  93263. __extends(WebVRFreeCamera, _super);
  93264. /**
  93265. * Instantiates a WebVRFreeCamera.
  93266. * @param name The name of the WebVRFreeCamera
  93267. * @param position The starting anchor position for the camera
  93268. * @param scene The scene the camera belongs to
  93269. * @param webVROptions a set of customizable options for the webVRCamera
  93270. */
  93271. function WebVRFreeCamera(name, position, scene, webVROptions) {
  93272. if (webVROptions === void 0) { webVROptions = {}; }
  93273. var _this = _super.call(this, name, position, scene) || this;
  93274. _this.webVROptions = webVROptions;
  93275. /**
  93276. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  93277. */
  93278. _this._vrDevice = null;
  93279. /**
  93280. * The rawPose of the vrDevice.
  93281. */
  93282. _this.rawPose = null;
  93283. _this._specsVersion = "1.1";
  93284. _this._attached = false;
  93285. _this._descendants = [];
  93286. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  93287. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  93288. /** @hidden */
  93289. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  93290. _this._standingMatrix = null;
  93291. /**
  93292. * Represents device position in babylon space.
  93293. */
  93294. _this.devicePosition = BABYLON.Vector3.Zero();
  93295. /**
  93296. * Represents device rotation in babylon space.
  93297. */
  93298. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  93299. /**
  93300. * The scale of the device to be used when translating from device space to babylon space.
  93301. */
  93302. _this.deviceScaleFactor = 1;
  93303. _this._deviceToWorld = BABYLON.Matrix.Identity();
  93304. _this._worldToDevice = BABYLON.Matrix.Identity();
  93305. /**
  93306. * References to the webVR controllers for the vrDevice.
  93307. */
  93308. _this.controllers = [];
  93309. /**
  93310. * Emits an event when a controller is attached.
  93311. */
  93312. _this.onControllersAttachedObservable = new BABYLON.Observable();
  93313. /**
  93314. * Emits an event when a controller's mesh has been loaded;
  93315. */
  93316. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  93317. /**
  93318. * Emits an event when the HMD's pose has been updated.
  93319. */
  93320. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  93321. _this._poseSet = false;
  93322. /**
  93323. * If the rig cameras be used as parent instead of this camera.
  93324. */
  93325. _this.rigParenting = true;
  93326. _this._defaultHeight = undefined;
  93327. _this._workingVector = BABYLON.Vector3.Zero();
  93328. _this._oneVector = BABYLON.Vector3.One();
  93329. _this._workingMatrix = BABYLON.Matrix.Identity();
  93330. _this._cache.position = BABYLON.Vector3.Zero();
  93331. if (webVROptions.defaultHeight) {
  93332. _this._defaultHeight = webVROptions.defaultHeight;
  93333. _this.position.y = _this._defaultHeight;
  93334. }
  93335. _this.minZ = 0.1;
  93336. //legacy support - the compensation boolean was removed.
  93337. if (arguments.length === 5) {
  93338. _this.webVROptions = arguments[4];
  93339. }
  93340. // default webVR options
  93341. if (_this.webVROptions.trackPosition == undefined) {
  93342. _this.webVROptions.trackPosition = true;
  93343. }
  93344. if (_this.webVROptions.controllerMeshes == undefined) {
  93345. _this.webVROptions.controllerMeshes = true;
  93346. }
  93347. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  93348. _this.webVROptions.defaultLightingOnControllers = true;
  93349. }
  93350. _this.rotationQuaternion = new BABYLON.Quaternion();
  93351. if (_this.webVROptions && _this.webVROptions.positionScale) {
  93352. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  93353. }
  93354. //enable VR
  93355. var engine = _this.getEngine();
  93356. _this._onVREnabled = function (success) { if (success) {
  93357. _this.initControllers();
  93358. } };
  93359. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  93360. engine.initWebVR().add(function (event) {
  93361. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  93362. return;
  93363. }
  93364. _this._vrDevice = event.vrDisplay;
  93365. //reset the rig parameters.
  93366. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  93367. if (_this._attached) {
  93368. _this.getEngine().enableVR();
  93369. }
  93370. });
  93371. if (typeof (VRFrameData) !== "undefined")
  93372. _this._frameData = new VRFrameData();
  93373. /**
  93374. * The idea behind the following lines:
  93375. * objects that have the camera as parent should actually have the rig cameras as a parent.
  93376. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  93377. * the second will not show it correctly.
  93378. *
  93379. * To solve this - each object that has the camera as parent will be added to a protected array.
  93380. * When the rig camera renders, it will take this array and set all of those to be its children.
  93381. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  93382. * Amazing!
  93383. */
  93384. scene.onBeforeCameraRenderObservable.add(function (camera) {
  93385. if (camera.parent === _this && _this.rigParenting) {
  93386. _this._descendants = _this.getDescendants(true, function (n) {
  93387. // don't take the cameras or the controllers!
  93388. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  93389. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  93390. return !isController && !isRigCamera;
  93391. });
  93392. _this._descendants.forEach(function (node) {
  93393. node.parent = camera;
  93394. });
  93395. }
  93396. });
  93397. scene.onAfterCameraRenderObservable.add(function (camera) {
  93398. if (camera.parent === _this && _this.rigParenting) {
  93399. _this._descendants.forEach(function (node) {
  93400. node.parent = _this;
  93401. });
  93402. }
  93403. });
  93404. return _this;
  93405. }
  93406. /**
  93407. * Gets the device distance from the ground in meters.
  93408. * @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.
  93409. */
  93410. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  93411. if (this._standingMatrix) {
  93412. // Add standing matrix offset to get real offset from ground in room
  93413. this._standingMatrix.getTranslationToRef(this._workingVector);
  93414. return this._deviceRoomPosition.y + this._workingVector.y;
  93415. }
  93416. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  93417. return this._defaultHeight || 0;
  93418. };
  93419. /**
  93420. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  93421. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  93422. */
  93423. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  93424. var _this = this;
  93425. if (callback === void 0) { callback = function (bool) { }; }
  93426. // Use standing matrix if available
  93427. this.getEngine().initWebVRAsync().then(function (result) {
  93428. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  93429. callback(false);
  93430. }
  93431. else {
  93432. _this._standingMatrix = new BABYLON.Matrix();
  93433. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  93434. if (!_this.getScene().useRightHandedSystem) {
  93435. [2, 6, 8, 9, 14].forEach(function (num) {
  93436. if (_this._standingMatrix) {
  93437. _this._standingMatrix.m[num] *= -1;
  93438. }
  93439. });
  93440. }
  93441. callback(true);
  93442. }
  93443. });
  93444. };
  93445. /**
  93446. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  93447. * @returns A promise with a boolean set to if the standing matrix is supported.
  93448. */
  93449. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  93450. var _this = this;
  93451. return new Promise(function (res, rej) {
  93452. _this.useStandingMatrix(function (supported) {
  93453. res(supported);
  93454. });
  93455. });
  93456. };
  93457. /**
  93458. * Disposes the camera
  93459. */
  93460. WebVRFreeCamera.prototype.dispose = function () {
  93461. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  93462. _super.prototype.dispose.call(this);
  93463. };
  93464. /**
  93465. * Gets a vrController by name.
  93466. * @param name The name of the controller to retreive
  93467. * @returns the controller matching the name specified or null if not found
  93468. */
  93469. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  93470. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  93471. var gp = _a[_i];
  93472. if (gp.hand === name) {
  93473. return gp;
  93474. }
  93475. }
  93476. return null;
  93477. };
  93478. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  93479. /**
  93480. * The controller corrisponding to the users left hand.
  93481. */
  93482. get: function () {
  93483. if (!this._leftController) {
  93484. this._leftController = this.getControllerByName("left");
  93485. }
  93486. return this._leftController;
  93487. },
  93488. enumerable: true,
  93489. configurable: true
  93490. });
  93491. ;
  93492. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  93493. /**
  93494. * The controller corrisponding to the users right hand.
  93495. */
  93496. get: function () {
  93497. if (!this._rightController) {
  93498. this._rightController = this.getControllerByName("right");
  93499. }
  93500. return this._rightController;
  93501. },
  93502. enumerable: true,
  93503. configurable: true
  93504. });
  93505. ;
  93506. /**
  93507. * Casts a ray forward from the vrCamera's gaze.
  93508. * @param length Length of the ray (default: 100)
  93509. * @returns the ray corrisponding to the gaze
  93510. */
  93511. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  93512. if (length === void 0) { length = 100; }
  93513. if (this.leftCamera) {
  93514. // Use left eye to avoid computation to compute center on every call
  93515. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  93516. }
  93517. else {
  93518. return _super.prototype.getForwardRay.call(this, length);
  93519. }
  93520. };
  93521. /**
  93522. * Updates the camera based on device's frame data
  93523. */
  93524. WebVRFreeCamera.prototype._checkInputs = function () {
  93525. if (this._vrDevice && this._vrDevice.isPresenting) {
  93526. this._vrDevice.getFrameData(this._frameData);
  93527. this.updateFromDevice(this._frameData.pose);
  93528. }
  93529. _super.prototype._checkInputs.call(this);
  93530. };
  93531. /**
  93532. * Updates the poseControlled values based on the input device pose.
  93533. * @param poseData Pose coming from the device
  93534. */
  93535. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  93536. if (poseData && poseData.orientation) {
  93537. this.rawPose = poseData;
  93538. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  93539. if (this.getScene().useRightHandedSystem) {
  93540. this._deviceRoomRotationQuaternion.z *= -1;
  93541. this._deviceRoomRotationQuaternion.w *= -1;
  93542. }
  93543. if (this.webVROptions.trackPosition && this.rawPose.position) {
  93544. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  93545. if (this.getScene().useRightHandedSystem) {
  93546. this._deviceRoomPosition.z *= -1;
  93547. }
  93548. }
  93549. this._poseSet = true;
  93550. }
  93551. };
  93552. /**
  93553. * WebVR's attach control will start broadcasting frames to the device.
  93554. * Note that in certain browsers (chrome for example) this function must be called
  93555. * within a user-interaction callback. Example:
  93556. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  93557. *
  93558. * @param element html element to attach the vrDevice to
  93559. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  93560. */
  93561. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  93562. _super.prototype.attachControl.call(this, element, noPreventDefault);
  93563. this._attached = true;
  93564. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  93565. if (this._vrDevice) {
  93566. this.getEngine().enableVR();
  93567. }
  93568. };
  93569. /**
  93570. * Detaches the camera from the html element and disables VR
  93571. *
  93572. * @param element html element to detach from
  93573. */
  93574. WebVRFreeCamera.prototype.detachControl = function (element) {
  93575. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  93576. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  93577. _super.prototype.detachControl.call(this, element);
  93578. this._attached = false;
  93579. this.getEngine().disableVR();
  93580. };
  93581. /**
  93582. * @returns the name of this class
  93583. */
  93584. WebVRFreeCamera.prototype.getClassName = function () {
  93585. return "WebVRFreeCamera";
  93586. };
  93587. /**
  93588. * Calls resetPose on the vrDisplay
  93589. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  93590. */
  93591. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  93592. //uses the vrDisplay's "resetPose()".
  93593. //pitch and roll won't be affected.
  93594. this._vrDevice.resetPose();
  93595. };
  93596. /**
  93597. * Updates the rig cameras (left and right eye)
  93598. */
  93599. WebVRFreeCamera.prototype._updateRigCameras = function () {
  93600. var camLeft = this._rigCameras[0];
  93601. var camRight = this._rigCameras[1];
  93602. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  93603. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  93604. camLeft.position.copyFrom(this._deviceRoomPosition);
  93605. camRight.position.copyFrom(this._deviceRoomPosition);
  93606. };
  93607. /**
  93608. * Updates the cached values of the camera
  93609. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  93610. */
  93611. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  93612. var _this = this;
  93613. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  93614. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  93615. if (!this.updateCacheCalled) {
  93616. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  93617. this.updateCacheCalled = true;
  93618. this.update();
  93619. }
  93620. // Set working vector to the device position in room space rotated by the new rotation
  93621. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  93622. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  93623. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  93624. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  93625. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  93626. // Add translation from anchor position
  93627. this._deviceToWorld.getTranslationToRef(this._workingVector);
  93628. this._workingVector.addInPlace(this.position);
  93629. this._workingVector.subtractInPlace(this._cache.position);
  93630. this._deviceToWorld.setTranslation(this._workingVector);
  93631. // Set an inverted matrix to be used when updating the camera
  93632. this._deviceToWorld.invertToRef(this._worldToDevice);
  93633. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  93634. this.controllers.forEach(function (controller) {
  93635. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  93636. controller.update();
  93637. });
  93638. }
  93639. if (!ignoreParentClass) {
  93640. _super.prototype._updateCache.call(this);
  93641. }
  93642. this.updateCacheCalled = false;
  93643. };
  93644. /**
  93645. * Updates the current device position and rotation in the babylon world
  93646. */
  93647. WebVRFreeCamera.prototype.update = function () {
  93648. // Get current device position in babylon world
  93649. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  93650. // Get current device rotation in babylon world
  93651. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  93652. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  93653. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  93654. if (this._poseSet) {
  93655. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  93656. }
  93657. _super.prototype.update.call(this);
  93658. };
  93659. /**
  93660. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  93661. * @returns an identity matrix
  93662. */
  93663. WebVRFreeCamera.prototype._getViewMatrix = function () {
  93664. return BABYLON.Matrix.Identity();
  93665. };
  93666. /**
  93667. * This function is called by the two RIG cameras.
  93668. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  93669. */
  93670. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  93671. var _this = this;
  93672. // Update the parent camera prior to using a child camera to avoid desynchronization
  93673. var parentCamera = this._cameraRigParams["parentCamera"];
  93674. parentCamera._updateCache();
  93675. //WebVR 1.1
  93676. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  93677. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  93678. if (!this.getScene().useRightHandedSystem) {
  93679. [2, 6, 8, 9, 14].forEach(function (num) {
  93680. _this._webvrViewMatrix.m[num] *= -1;
  93681. });
  93682. }
  93683. // update the camera rotation matrix
  93684. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  93685. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  93686. // Computing target and final matrix
  93687. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  93688. // should the view matrix be updated with scale and position offset?
  93689. if (parentCamera.deviceScaleFactor !== 1) {
  93690. this._webvrViewMatrix.invert();
  93691. // scale the position, if set
  93692. if (parentCamera.deviceScaleFactor) {
  93693. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  93694. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  93695. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  93696. }
  93697. this._webvrViewMatrix.invert();
  93698. }
  93699. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  93700. // Compute global position
  93701. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  93702. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  93703. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  93704. this._workingMatrix.getTranslationToRef(this._globalPosition);
  93705. this._markSyncedWithParent();
  93706. return this._webvrViewMatrix;
  93707. };
  93708. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  93709. var _this = this;
  93710. var parentCamera = this.parent;
  93711. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  93712. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  93713. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  93714. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  93715. //babylon compatible matrix
  93716. if (!this.getScene().useRightHandedSystem) {
  93717. [8, 9, 10, 11].forEach(function (num) {
  93718. _this._projectionMatrix.m[num] *= -1;
  93719. });
  93720. }
  93721. return this._projectionMatrix;
  93722. };
  93723. /**
  93724. * Initializes the controllers and their meshes
  93725. */
  93726. WebVRFreeCamera.prototype.initControllers = function () {
  93727. var _this = this;
  93728. this.controllers = [];
  93729. var manager = this.getScene().gamepadManager;
  93730. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  93731. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  93732. var webVrController = gamepad;
  93733. if (webVrController.defaultModel) {
  93734. webVrController.defaultModel.setEnabled(false);
  93735. }
  93736. if (webVrController.hand === "right") {
  93737. _this._rightController = null;
  93738. }
  93739. if (webVrController.hand === "left") {
  93740. _this._leftController = null;
  93741. }
  93742. var controllerIndex = _this.controllers.indexOf(webVrController);
  93743. if (controllerIndex !== -1) {
  93744. _this.controllers.splice(controllerIndex, 1);
  93745. }
  93746. }
  93747. });
  93748. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  93749. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  93750. var webVrController_1 = gamepad;
  93751. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  93752. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  93753. if (_this.webVROptions.controllerMeshes) {
  93754. if (webVrController_1.defaultModel) {
  93755. webVrController_1.defaultModel.setEnabled(true);
  93756. }
  93757. else {
  93758. // Load the meshes
  93759. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  93760. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  93761. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  93762. if (_this.webVROptions.defaultLightingOnControllers) {
  93763. if (!_this._lightOnControllers) {
  93764. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  93765. }
  93766. var activateLightOnSubMeshes_1 = function (mesh, light) {
  93767. var children = mesh.getChildren();
  93768. if (children.length !== 0) {
  93769. children.forEach(function (mesh) {
  93770. light.includedOnlyMeshes.push(mesh);
  93771. activateLightOnSubMeshes_1(mesh, light);
  93772. });
  93773. }
  93774. };
  93775. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  93776. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  93777. }
  93778. });
  93779. }
  93780. }
  93781. webVrController_1.attachToPoseControlledCamera(_this);
  93782. // since this is async - sanity check. Is the controller already stored?
  93783. if (_this.controllers.indexOf(webVrController_1) === -1) {
  93784. //add to the controllers array
  93785. _this.controllers.push(webVrController_1);
  93786. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  93787. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  93788. // So we're overriding setting left & right manually to be sure
  93789. var firstViveWandDetected = false;
  93790. for (var i = 0; i < _this.controllers.length; i++) {
  93791. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93792. if (!firstViveWandDetected) {
  93793. firstViveWandDetected = true;
  93794. _this.controllers[i].hand = "left";
  93795. }
  93796. else {
  93797. _this.controllers[i].hand = "right";
  93798. }
  93799. }
  93800. }
  93801. //did we find enough controllers? Great! let the developer know.
  93802. if (_this.controllers.length >= 2) {
  93803. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  93804. }
  93805. }
  93806. }
  93807. });
  93808. };
  93809. return WebVRFreeCamera;
  93810. }(BABYLON.FreeCamera));
  93811. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  93812. })(BABYLON || (BABYLON = {}));
  93813. //# sourceMappingURL=babylon.webVRCamera.js.map
  93814. var BABYLON;
  93815. (function (BABYLON) {
  93816. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  93817. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  93818. });
  93819. // We're mainly based on the logic defined into the FreeCamera code
  93820. /**
  93821. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  93822. * being tilted forward or back and left or right.
  93823. */
  93824. var DeviceOrientationCamera = /** @class */ (function (_super) {
  93825. __extends(DeviceOrientationCamera, _super);
  93826. /**
  93827. * Creates a new device orientation camera
  93828. * @param name The name of the camera
  93829. * @param position The start position camera
  93830. * @param scene The scene the camera belongs to
  93831. */
  93832. function DeviceOrientationCamera(name, position, scene) {
  93833. var _this = _super.call(this, name, position, scene) || this;
  93834. _this._quaternionCache = new BABYLON.Quaternion();
  93835. _this.inputs.addDeviceOrientation();
  93836. return _this;
  93837. }
  93838. /**
  93839. * Gets the current instance class name ("DeviceOrientationCamera").
  93840. * This helps avoiding instanceof at run time.
  93841. * @returns the class name
  93842. */
  93843. DeviceOrientationCamera.prototype.getClassName = function () {
  93844. return "DeviceOrientationCamera";
  93845. };
  93846. /**
  93847. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  93848. */
  93849. DeviceOrientationCamera.prototype._checkInputs = function () {
  93850. _super.prototype._checkInputs.call(this);
  93851. this._quaternionCache.copyFrom(this.rotationQuaternion);
  93852. if (this._initialQuaternion) {
  93853. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93854. }
  93855. };
  93856. /**
  93857. * Reset the camera to its default orientation on the specified axis only.
  93858. * @param axis The axis to reset
  93859. */
  93860. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  93861. var _this = this;
  93862. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  93863. //can only work if this camera has a rotation quaternion already.
  93864. if (!this.rotationQuaternion)
  93865. return;
  93866. if (!this._initialQuaternion) {
  93867. this._initialQuaternion = new BABYLON.Quaternion();
  93868. }
  93869. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  93870. ['x', 'y', 'z'].forEach(function (axisName) {
  93871. if (!axis[axisName]) {
  93872. _this._initialQuaternion[axisName] = 0;
  93873. }
  93874. else {
  93875. _this._initialQuaternion[axisName] *= -1;
  93876. }
  93877. });
  93878. this._initialQuaternion.normalize();
  93879. //force rotation update
  93880. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93881. };
  93882. return DeviceOrientationCamera;
  93883. }(BABYLON.FreeCamera));
  93884. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  93885. })(BABYLON || (BABYLON = {}));
  93886. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  93887. var BABYLON;
  93888. (function (BABYLON) {
  93889. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93890. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93891. });
  93892. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  93893. __extends(VRDeviceOrientationFreeCamera, _super);
  93894. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93895. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93896. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93897. var _this = _super.call(this, name, position, scene) || this;
  93898. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93899. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93900. return _this;
  93901. }
  93902. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  93903. return "VRDeviceOrientationFreeCamera";
  93904. };
  93905. return VRDeviceOrientationFreeCamera;
  93906. }(BABYLON.DeviceOrientationCamera));
  93907. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  93908. })(BABYLON || (BABYLON = {}));
  93909. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  93910. var BABYLON;
  93911. (function (BABYLON) {
  93912. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93913. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  93914. });
  93915. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  93916. __extends(VRDeviceOrientationArcRotateCamera, _super);
  93917. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  93918. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93919. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93920. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  93921. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93922. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93923. _this.inputs.addVRDeviceOrientation();
  93924. return _this;
  93925. }
  93926. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  93927. return "VRDeviceOrientationArcRotateCamera";
  93928. };
  93929. return VRDeviceOrientationArcRotateCamera;
  93930. }(BABYLON.ArcRotateCamera));
  93931. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  93932. })(BABYLON || (BABYLON = {}));
  93933. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  93934. var BABYLON;
  93935. (function (BABYLON) {
  93936. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  93937. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  93938. });
  93939. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  93940. __extends(VRDeviceOrientationGamepadCamera, _super);
  93941. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93942. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93943. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93944. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  93945. _this.inputs.addGamepad();
  93946. return _this;
  93947. }
  93948. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  93949. return "VRDeviceOrientationGamepadCamera";
  93950. };
  93951. return VRDeviceOrientationGamepadCamera;
  93952. }(BABYLON.VRDeviceOrientationFreeCamera));
  93953. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  93954. })(BABYLON || (BABYLON = {}));
  93955. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  93956. var BABYLON;
  93957. (function (BABYLON) {
  93958. var VRExperienceHelperGazer = /** @class */ (function () {
  93959. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  93960. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  93961. this.scene = scene;
  93962. this._pointerDownOnMeshAsked = false;
  93963. this._isActionableMesh = false;
  93964. this._teleportationRequestInitiated = false;
  93965. this._teleportationBackRequestInitiated = false;
  93966. this._rotationRightAsked = false;
  93967. this._rotationLeftAsked = false;
  93968. this._dpadPressed = true;
  93969. this._activePointer = false;
  93970. this._id = VRExperienceHelperGazer._idCounter++;
  93971. // Gaze tracker
  93972. if (!gazeTrackerToClone) {
  93973. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  93974. this._gazeTracker.bakeCurrentTransformIntoVertices();
  93975. this._gazeTracker.isPickable = false;
  93976. this._gazeTracker.isVisible = false;
  93977. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  93978. targetMat.specularColor = BABYLON.Color3.Black();
  93979. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93980. targetMat.backFaceCulling = false;
  93981. this._gazeTracker.material = targetMat;
  93982. }
  93983. else {
  93984. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  93985. }
  93986. }
  93987. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  93988. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  93989. };
  93990. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  93991. this._pointerDownOnMeshAsked = true;
  93992. if (this._currentHit) {
  93993. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  93994. }
  93995. };
  93996. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  93997. if (this._currentHit) {
  93998. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  93999. }
  94000. this._pointerDownOnMeshAsked = false;
  94001. };
  94002. VRExperienceHelperGazer.prototype._activatePointer = function () {
  94003. this._activePointer = true;
  94004. };
  94005. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  94006. this._activePointer = false;
  94007. };
  94008. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  94009. if (distance === void 0) { distance = 100; }
  94010. };
  94011. VRExperienceHelperGazer.prototype.dispose = function () {
  94012. this._interactionsEnabled = false;
  94013. this._teleportationEnabled = false;
  94014. if (this._gazeTracker) {
  94015. this._gazeTracker.dispose();
  94016. }
  94017. };
  94018. VRExperienceHelperGazer._idCounter = 0;
  94019. return VRExperienceHelperGazer;
  94020. }());
  94021. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  94022. __extends(VRExperienceHelperControllerGazer, _super);
  94023. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  94024. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  94025. _this.webVRController = webVRController;
  94026. // Laser pointer
  94027. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  94028. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  94029. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  94030. laserPointerMaterial.alpha = 0.6;
  94031. _this._laserPointer.material = laserPointerMaterial;
  94032. _this._laserPointer.rotation.x = Math.PI / 2;
  94033. _this._laserPointer.position.z = -0.5;
  94034. _this._laserPointer.isVisible = false;
  94035. _this._laserPointer.isPickable = false;
  94036. if (!webVRController.mesh) {
  94037. // Create an empty mesh that is used prior to loading the high quality model
  94038. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  94039. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  94040. preloadPointerPose.rotation.x = -0.7;
  94041. preloadMesh.addChild(preloadPointerPose);
  94042. webVRController.attachToMesh(preloadMesh);
  94043. }
  94044. _this._setLaserPointerParent(webVRController.mesh);
  94045. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  94046. _this._setLaserPointerParent(mesh);
  94047. });
  94048. return _this;
  94049. }
  94050. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  94051. return this.webVRController.getForwardRay(length);
  94052. };
  94053. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  94054. _super.prototype._activatePointer.call(this);
  94055. this._laserPointer.isVisible = true;
  94056. };
  94057. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  94058. _super.prototype._deactivatePointer.call(this);
  94059. this._laserPointer.isVisible = false;
  94060. };
  94061. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  94062. this._laserPointer.material.emissiveColor = color;
  94063. };
  94064. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  94065. var makeNotPick = function (root) {
  94066. root.isPickable = false;
  94067. root.getChildMeshes().forEach(function (c) {
  94068. makeNotPick(c);
  94069. });
  94070. };
  94071. makeNotPick(mesh);
  94072. var childMeshes = mesh.getChildMeshes();
  94073. this.webVRController._pointingPoseNode = null;
  94074. for (var i = 0; i < childMeshes.length; i++) {
  94075. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  94076. mesh = childMeshes[i];
  94077. this.webVRController._pointingPoseNode = mesh;
  94078. break;
  94079. }
  94080. }
  94081. this._laserPointer.parent = mesh;
  94082. };
  94083. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  94084. if (distance === void 0) { distance = 100; }
  94085. this._laserPointer.scaling.y = distance;
  94086. this._laserPointer.position.z = -distance / 2;
  94087. };
  94088. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  94089. _super.prototype.dispose.call(this);
  94090. this._laserPointer.dispose();
  94091. if (this._meshAttachedObserver) {
  94092. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  94093. }
  94094. };
  94095. return VRExperienceHelperControllerGazer;
  94096. }(VRExperienceHelperGazer));
  94097. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  94098. __extends(VRExperienceHelperCameraGazer, _super);
  94099. function VRExperienceHelperCameraGazer(getCamera, scene) {
  94100. var _this = _super.call(this, scene) || this;
  94101. _this.getCamera = getCamera;
  94102. return _this;
  94103. }
  94104. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  94105. var camera = this.getCamera();
  94106. if (camera) {
  94107. return camera.getForwardRay(length);
  94108. }
  94109. else {
  94110. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  94111. }
  94112. };
  94113. return VRExperienceHelperCameraGazer;
  94114. }(VRExperienceHelperGazer));
  94115. /**
  94116. * Helps to quickly add VR support to an existing scene.
  94117. * See http://doc.babylonjs.com/how_to/webvr_helper
  94118. */
  94119. var VRExperienceHelper = /** @class */ (function () {
  94120. /**
  94121. * Instantiates a VRExperienceHelper.
  94122. * Helps to quickly add VR support to an existing scene.
  94123. * @param scene The scene the VRExperienceHelper belongs to.
  94124. * @param webVROptions Options to modify the vr experience helper's behavior.
  94125. */
  94126. function VRExperienceHelper(scene,
  94127. /** Options to modify the vr experience helper's behavior. */
  94128. webVROptions) {
  94129. if (webVROptions === void 0) { webVROptions = {}; }
  94130. var _this = this;
  94131. this.webVROptions = webVROptions;
  94132. // Can the system support WebVR, even if a headset isn't plugged in?
  94133. this._webVRsupported = false;
  94134. // If WebVR is supported, is a headset plugged in and are we ready to present?
  94135. this._webVRready = false;
  94136. // Are we waiting for the requestPresent callback to complete?
  94137. this._webVRrequesting = false;
  94138. // Are we presenting to the headset right now?
  94139. this._webVRpresenting = false;
  94140. // Are we presenting in the fullscreen fallback?
  94141. this._fullscreenVRpresenting = false;
  94142. /**
  94143. * Observable raised when entering VR.
  94144. */
  94145. this.onEnteringVRObservable = new BABYLON.Observable();
  94146. /**
  94147. * Observable raised when exiting VR.
  94148. */
  94149. this.onExitingVRObservable = new BABYLON.Observable();
  94150. /**
  94151. * Observable raised when controller mesh is loaded.
  94152. */
  94153. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  94154. this._useCustomVRButton = false;
  94155. this._teleportationRequested = false;
  94156. this._teleportActive = false;
  94157. this._floorMeshesCollection = [];
  94158. this._rotationAllowed = true;
  94159. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  94160. this._isDefaultTeleportationTarget = true;
  94161. this._teleportationFillColor = "#444444";
  94162. this._teleportationBorderColor = "#FFFFFF";
  94163. this._rotationAngle = 0;
  94164. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  94165. this._padSensibilityUp = 0.65;
  94166. this._padSensibilityDown = 0.35;
  94167. this.leftController = null;
  94168. this.rightController = null;
  94169. /**
  94170. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  94171. */
  94172. this.onNewMeshSelected = new BABYLON.Observable();
  94173. /**
  94174. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  94175. */
  94176. this.onNewMeshPicked = new BABYLON.Observable();
  94177. /**
  94178. * Observable raised before camera teleportation
  94179. */
  94180. this.onBeforeCameraTeleport = new BABYLON.Observable();
  94181. /**
  94182. * Observable raised after camera teleportation
  94183. */
  94184. this.onAfterCameraTeleport = new BABYLON.Observable();
  94185. /**
  94186. * Observable raised when current selected mesh gets unselected
  94187. */
  94188. this.onSelectedMeshUnselected = new BABYLON.Observable();
  94189. /**
  94190. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  94191. */
  94192. this.teleportationEnabled = true;
  94193. this._teleportationInitialized = false;
  94194. this._interactionsEnabled = false;
  94195. this._interactionsRequested = false;
  94196. this._displayGaze = true;
  94197. this._displayLaserPointer = true;
  94198. this._onResize = function () {
  94199. _this.moveButtonToBottomRight();
  94200. if (_this._fullscreenVRpresenting && _this._webVRready) {
  94201. _this.exitVR();
  94202. }
  94203. };
  94204. this._onFullscreenChange = function () {
  94205. if (document.fullscreen !== undefined) {
  94206. _this._fullscreenVRpresenting = document.fullscreen;
  94207. }
  94208. else if (document.mozFullScreen !== undefined) {
  94209. _this._fullscreenVRpresenting = document.mozFullScreen;
  94210. }
  94211. else if (document.webkitIsFullScreen !== undefined) {
  94212. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  94213. }
  94214. else if (document.msIsFullScreen !== undefined) {
  94215. _this._fullscreenVRpresenting = document.msIsFullScreen;
  94216. }
  94217. else if (document.msFullscreenElement !== undefined) {
  94218. _this._fullscreenVRpresenting = document.msFullscreenElement;
  94219. }
  94220. if (!_this._fullscreenVRpresenting && _this._canvas) {
  94221. _this.exitVR();
  94222. if (!_this._useCustomVRButton) {
  94223. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  94224. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  94225. }
  94226. }
  94227. };
  94228. this.beforeRender = function () {
  94229. if (_this.leftController && _this.leftController._activePointer) {
  94230. _this._castRayAndSelectObject(_this.leftController);
  94231. }
  94232. if (_this.rightController && _this.rightController._activePointer) {
  94233. _this._castRayAndSelectObject(_this.rightController);
  94234. }
  94235. if (_this._noControllerIsActive) {
  94236. _this._castRayAndSelectObject(_this._cameraGazer);
  94237. }
  94238. else {
  94239. _this._cameraGazer._gazeTracker.isVisible = false;
  94240. }
  94241. };
  94242. this._onNewGamepadConnected = function (gamepad) {
  94243. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  94244. if (gamepad.leftStick) {
  94245. gamepad.onleftstickchanged(function (stickValues) {
  94246. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  94247. // Listening to classic/xbox gamepad only if no VR controller is active
  94248. if ((!_this.leftController && !_this.rightController) ||
  94249. ((_this.leftController && !_this.leftController._activePointer) &&
  94250. (_this.rightController && !_this.rightController._activePointer))) {
  94251. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  94252. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  94253. }
  94254. }
  94255. });
  94256. }
  94257. if (gamepad.rightStick) {
  94258. gamepad.onrightstickchanged(function (stickValues) {
  94259. if (_this._teleportationInitialized) {
  94260. _this._checkRotate(stickValues, _this._cameraGazer);
  94261. }
  94262. });
  94263. }
  94264. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  94265. gamepad.onbuttondown(function (buttonPressed) {
  94266. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  94267. _this._cameraGazer._selectionPointerDown();
  94268. }
  94269. });
  94270. gamepad.onbuttonup(function (buttonPressed) {
  94271. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  94272. _this._cameraGazer._selectionPointerUp();
  94273. }
  94274. });
  94275. }
  94276. }
  94277. else {
  94278. var webVRController = gamepad;
  94279. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  94280. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  94281. _this.rightController = controller;
  94282. }
  94283. else {
  94284. _this.leftController = controller;
  94285. }
  94286. _this._tryEnableInteractionOnController(controller);
  94287. }
  94288. };
  94289. // 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
  94290. this._tryEnableInteractionOnController = function (controller) {
  94291. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  94292. _this._enableInteractionOnController(controller);
  94293. }
  94294. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  94295. _this._enableTeleportationOnController(controller);
  94296. }
  94297. };
  94298. this._onNewGamepadDisconnected = function (gamepad) {
  94299. if (gamepad instanceof BABYLON.WebVRController) {
  94300. if (gamepad.hand === "left" && _this.leftController != null) {
  94301. _this.leftController.dispose();
  94302. _this.leftController = null;
  94303. }
  94304. if (gamepad.hand === "right" && _this.rightController != null) {
  94305. _this.rightController.dispose();
  94306. _this.rightController = null;
  94307. }
  94308. }
  94309. };
  94310. this._workingVector = BABYLON.Vector3.Zero();
  94311. this._workingQuaternion = BABYLON.Quaternion.Identity();
  94312. this._workingMatrix = BABYLON.Matrix.Identity();
  94313. this._scene = scene;
  94314. this._canvas = scene.getEngine().getRenderingCanvas();
  94315. // Parse options
  94316. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  94317. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  94318. }
  94319. if (webVROptions.createDeviceOrientationCamera === undefined) {
  94320. webVROptions.createDeviceOrientationCamera = true;
  94321. }
  94322. if (webVROptions.laserToggle === undefined) {
  94323. webVROptions.laserToggle = true;
  94324. }
  94325. if (webVROptions.defaultHeight === undefined) {
  94326. webVROptions.defaultHeight = 1.7;
  94327. }
  94328. if (webVROptions.useCustomVRButton) {
  94329. this._useCustomVRButton = true;
  94330. if (webVROptions.customVRButton) {
  94331. this._btnVR = webVROptions.customVRButton;
  94332. }
  94333. }
  94334. if (webVROptions.rayLength) {
  94335. this._rayLength = webVROptions.rayLength;
  94336. }
  94337. this._defaultHeight = webVROptions.defaultHeight;
  94338. if (webVROptions.positionScale) {
  94339. this._rayLength *= webVROptions.positionScale;
  94340. this._defaultHeight *= webVROptions.positionScale;
  94341. }
  94342. // Set position
  94343. if (this._scene.activeCamera) {
  94344. this._position = this._scene.activeCamera.position.clone();
  94345. }
  94346. else {
  94347. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  94348. }
  94349. // Set non-vr camera
  94350. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  94351. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  94352. // Copy data from existing camera
  94353. if (this._scene.activeCamera) {
  94354. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  94355. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  94356. // Set rotation from previous camera
  94357. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  94358. var targetCamera = this._scene.activeCamera;
  94359. if (targetCamera.rotationQuaternion) {
  94360. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  94361. }
  94362. else {
  94363. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  94364. }
  94365. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  94366. }
  94367. }
  94368. this._scene.activeCamera = this._deviceOrientationCamera;
  94369. if (this._canvas) {
  94370. this._scene.activeCamera.attachControl(this._canvas);
  94371. }
  94372. }
  94373. else {
  94374. this._existingCamera = this._scene.activeCamera;
  94375. }
  94376. // Create VR cameras
  94377. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  94378. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  94379. }
  94380. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  94381. this._webVRCamera.useStandingMatrix();
  94382. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  94383. // Create default button
  94384. if (!this._useCustomVRButton) {
  94385. this._btnVR = document.createElement("BUTTON");
  94386. this._btnVR.className = "babylonVRicon";
  94387. this._btnVR.id = "babylonVRiconbtn";
  94388. this._btnVR.title = "Click to switch to VR";
  94389. 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) }";
  94390. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  94391. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  94392. // css += ".babylonVRicon.vrdisplaysupported { }";
  94393. // css += ".babylonVRicon.vrdisplayready { }";
  94394. // css += ".babylonVRicon.vrdisplayrequesting { }";
  94395. var style = document.createElement('style');
  94396. style.appendChild(document.createTextNode(css));
  94397. document.getElementsByTagName('head')[0].appendChild(style);
  94398. this.moveButtonToBottomRight();
  94399. }
  94400. // VR button click event
  94401. if (this._btnVR) {
  94402. this._btnVR.addEventListener("click", function () {
  94403. if (!_this.isInVRMode) {
  94404. _this.enterVR();
  94405. }
  94406. else {
  94407. _this.exitVR();
  94408. }
  94409. });
  94410. }
  94411. // Window events
  94412. window.addEventListener("resize", this._onResize);
  94413. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  94414. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  94415. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  94416. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  94417. document.onmsfullscreenchange = this._onFullscreenChange;
  94418. // Display vr button when headset is connected
  94419. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  94420. this.displayVRButton();
  94421. }
  94422. else {
  94423. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  94424. if (e.vrDisplay) {
  94425. _this.displayVRButton();
  94426. }
  94427. });
  94428. }
  94429. // Exiting VR mode using 'ESC' key on desktop
  94430. this._onKeyDown = function (event) {
  94431. if (event.keyCode === 27 && _this.isInVRMode) {
  94432. _this.exitVR();
  94433. }
  94434. };
  94435. document.addEventListener("keydown", this._onKeyDown);
  94436. // Exiting VR mode double tapping the touch screen
  94437. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  94438. if (_this.isInVRMode) {
  94439. _this.exitVR();
  94440. if (_this._fullscreenVRpresenting) {
  94441. _this._scene.getEngine().switchFullscreen(true);
  94442. }
  94443. }
  94444. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  94445. // Listen for WebVR display changes
  94446. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  94447. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  94448. this._onVRRequestPresentStart = function () {
  94449. _this._webVRrequesting = true;
  94450. _this.updateButtonVisibility();
  94451. };
  94452. this._onVRRequestPresentComplete = function (success) {
  94453. _this._webVRrequesting = false;
  94454. _this.updateButtonVisibility();
  94455. };
  94456. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  94457. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  94458. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  94459. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94460. scene.onDisposeObservable.add(function () {
  94461. _this.dispose();
  94462. });
  94463. // Gamepad connection events
  94464. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  94465. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  94466. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  94467. this.updateButtonVisibility();
  94468. //create easing functions
  94469. this._circleEase = new BABYLON.CircleEase();
  94470. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  94471. if (this.webVROptions.floorMeshes) {
  94472. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  94473. }
  94474. }
  94475. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  94476. /** Return this.onEnteringVRObservable
  94477. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  94478. */
  94479. get: function () {
  94480. return this.onEnteringVRObservable;
  94481. },
  94482. enumerable: true,
  94483. configurable: true
  94484. });
  94485. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  94486. /** Return this.onExitingVRObservable
  94487. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  94488. */
  94489. get: function () {
  94490. return this.onExitingVRObservable;
  94491. },
  94492. enumerable: true,
  94493. configurable: true
  94494. });
  94495. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  94496. /** Return this.onControllerMeshLoadedObservable
  94497. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  94498. */
  94499. get: function () {
  94500. return this.onControllerMeshLoadedObservable;
  94501. },
  94502. enumerable: true,
  94503. configurable: true
  94504. });
  94505. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  94506. /**
  94507. * The mesh used to display where the user is going to teleport.
  94508. */
  94509. get: function () {
  94510. return this._teleportationTarget;
  94511. },
  94512. /**
  94513. * Sets the mesh to be used to display where the user is going to teleport.
  94514. */
  94515. set: function (value) {
  94516. if (value) {
  94517. value.name = "teleportationTarget";
  94518. this._isDefaultTeleportationTarget = false;
  94519. this._teleportationTarget = value;
  94520. }
  94521. },
  94522. enumerable: true,
  94523. configurable: true
  94524. });
  94525. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  94526. /**
  94527. * The mesh used to display where the user is selecting,
  94528. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  94529. * See http://doc.babylonjs.com/resources/baking_transformations
  94530. */
  94531. get: function () {
  94532. return this._cameraGazer._gazeTracker;
  94533. },
  94534. set: function (value) {
  94535. if (value) {
  94536. this._cameraGazer._gazeTracker = value;
  94537. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  94538. this._cameraGazer._gazeTracker.isPickable = false;
  94539. this._cameraGazer._gazeTracker.isVisible = false;
  94540. this._cameraGazer._gazeTracker.name = "gazeTracker";
  94541. if (this.leftController) {
  94542. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  94543. }
  94544. if (this.rightController) {
  94545. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  94546. }
  94547. }
  94548. },
  94549. enumerable: true,
  94550. configurable: true
  94551. });
  94552. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  94553. /**
  94554. * If the ray of the gaze should be displayed.
  94555. */
  94556. get: function () {
  94557. return this._displayGaze;
  94558. },
  94559. /**
  94560. * Sets if the ray of the gaze should be displayed.
  94561. */
  94562. set: function (value) {
  94563. this._displayGaze = value;
  94564. if (!value) {
  94565. this._cameraGazer._gazeTracker.isVisible = false;
  94566. if (this.leftController) {
  94567. this.leftController._gazeTracker.isVisible = false;
  94568. }
  94569. if (this.rightController) {
  94570. this.rightController._gazeTracker.isVisible = false;
  94571. }
  94572. }
  94573. },
  94574. enumerable: true,
  94575. configurable: true
  94576. });
  94577. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  94578. /**
  94579. * If the ray of the LaserPointer should be displayed.
  94580. */
  94581. get: function () {
  94582. return this._displayLaserPointer;
  94583. },
  94584. /**
  94585. * Sets if the ray of the LaserPointer should be displayed.
  94586. */
  94587. set: function (value) {
  94588. this._displayLaserPointer = value;
  94589. if (!value) {
  94590. if (this.rightController) {
  94591. this.rightController._deactivatePointer();
  94592. this.rightController._gazeTracker.isVisible = false;
  94593. }
  94594. if (this.leftController) {
  94595. this.leftController._deactivatePointer();
  94596. this.leftController._gazeTracker.isVisible = false;
  94597. }
  94598. }
  94599. else {
  94600. if (this.rightController) {
  94601. this.rightController._activatePointer();
  94602. }
  94603. if (this.leftController) {
  94604. this.leftController._activatePointer();
  94605. }
  94606. }
  94607. },
  94608. enumerable: true,
  94609. configurable: true
  94610. });
  94611. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  94612. /**
  94613. * The deviceOrientationCamera used as the camera when not in VR.
  94614. */
  94615. get: function () {
  94616. return this._deviceOrientationCamera;
  94617. },
  94618. enumerable: true,
  94619. configurable: true
  94620. });
  94621. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  94622. /**
  94623. * Based on the current WebVR support, returns the current VR camera used.
  94624. */
  94625. get: function () {
  94626. if (this._webVRready) {
  94627. return this._webVRCamera;
  94628. }
  94629. else {
  94630. return this._scene.activeCamera;
  94631. }
  94632. },
  94633. enumerable: true,
  94634. configurable: true
  94635. });
  94636. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  94637. /**
  94638. * The webVRCamera which is used when in VR.
  94639. */
  94640. get: function () {
  94641. return this._webVRCamera;
  94642. },
  94643. enumerable: true,
  94644. configurable: true
  94645. });
  94646. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  94647. /**
  94648. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  94649. */
  94650. get: function () {
  94651. return this._vrDeviceOrientationCamera;
  94652. },
  94653. enumerable: true,
  94654. configurable: true
  94655. });
  94656. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  94657. get: function () {
  94658. var result = this._cameraGazer._teleportationRequestInitiated
  94659. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  94660. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  94661. return result;
  94662. },
  94663. enumerable: true,
  94664. configurable: true
  94665. });
  94666. // Raised when one of the controller has loaded successfully its associated default mesh
  94667. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  94668. if (this.leftController && this.leftController.webVRController == webVRController) {
  94669. if (webVRController.mesh) {
  94670. this.leftController._setLaserPointerParent(webVRController.mesh);
  94671. }
  94672. }
  94673. if (this.rightController && this.rightController.webVRController == webVRController) {
  94674. if (webVRController.mesh) {
  94675. this.rightController._setLaserPointerParent(webVRController.mesh);
  94676. }
  94677. }
  94678. try {
  94679. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  94680. }
  94681. catch (err) {
  94682. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  94683. }
  94684. };
  94685. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  94686. /**
  94687. * Gets a value indicating if we are currently in VR mode.
  94688. */
  94689. get: function () {
  94690. return this._webVRpresenting || this._fullscreenVRpresenting;
  94691. },
  94692. enumerable: true,
  94693. configurable: true
  94694. });
  94695. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  94696. var vrDisplay = this._scene.getEngine().getVRDevice();
  94697. if (vrDisplay) {
  94698. var wasPresenting = this._webVRpresenting;
  94699. // A VR display is connected
  94700. this._webVRpresenting = vrDisplay.isPresenting;
  94701. if (wasPresenting && !this._webVRpresenting)
  94702. this.exitVR();
  94703. }
  94704. else {
  94705. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  94706. }
  94707. this.updateButtonVisibility();
  94708. };
  94709. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  94710. this._webVRsupported = eventArgs.vrSupported;
  94711. this._webVRready = !!eventArgs.vrDisplay;
  94712. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  94713. this.updateButtonVisibility();
  94714. };
  94715. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  94716. if (this._canvas && !this._useCustomVRButton) {
  94717. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  94718. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  94719. }
  94720. };
  94721. VRExperienceHelper.prototype.displayVRButton = function () {
  94722. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  94723. document.body.appendChild(this._btnVR);
  94724. this._btnVRDisplayed = true;
  94725. }
  94726. };
  94727. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  94728. if (!this._btnVR || this._useCustomVRButton) {
  94729. return;
  94730. }
  94731. this._btnVR.className = "babylonVRicon";
  94732. if (this.isInVRMode) {
  94733. this._btnVR.className += " vrdisplaypresenting";
  94734. }
  94735. else {
  94736. if (this._webVRready)
  94737. this._btnVR.className += " vrdisplayready";
  94738. if (this._webVRsupported)
  94739. this._btnVR.className += " vrdisplaysupported";
  94740. if (this._webVRrequesting)
  94741. this._btnVR.className += " vrdisplayrequesting";
  94742. }
  94743. };
  94744. /**
  94745. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  94746. * Otherwise, will use the fullscreen API.
  94747. */
  94748. VRExperienceHelper.prototype.enterVR = function () {
  94749. if (this.onEnteringVRObservable) {
  94750. try {
  94751. this.onEnteringVRObservable.notifyObservers(this);
  94752. }
  94753. catch (err) {
  94754. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  94755. }
  94756. }
  94757. if (this._scene.activeCamera) {
  94758. this._position = this._scene.activeCamera.position.clone();
  94759. // make sure that we return to the last active camera
  94760. this._existingCamera = this._scene.activeCamera;
  94761. }
  94762. if (this._webVRrequesting)
  94763. return;
  94764. // If WebVR is supported and a headset is connected
  94765. if (this._webVRready) {
  94766. if (!this._webVRpresenting) {
  94767. this._webVRCamera.position = this._position;
  94768. this._scene.activeCamera = this._webVRCamera;
  94769. }
  94770. }
  94771. else if (this._vrDeviceOrientationCamera) {
  94772. this._vrDeviceOrientationCamera.position = this._position;
  94773. if (this._scene.activeCamera) {
  94774. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  94775. }
  94776. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  94777. this._scene.getEngine().switchFullscreen(true);
  94778. this.updateButtonVisibility();
  94779. }
  94780. if (this._scene.activeCamera && this._canvas) {
  94781. this._scene.activeCamera.attachControl(this._canvas);
  94782. }
  94783. if (this._interactionsEnabled) {
  94784. this._scene.registerBeforeRender(this.beforeRender);
  94785. }
  94786. };
  94787. /**
  94788. * Attempt to exit VR, or fullscreen.
  94789. */
  94790. VRExperienceHelper.prototype.exitVR = function () {
  94791. if (this.onExitingVRObservable) {
  94792. try {
  94793. this.onExitingVRObservable.notifyObservers(this);
  94794. }
  94795. catch (err) {
  94796. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  94797. }
  94798. }
  94799. if (this._webVRpresenting) {
  94800. this._scene.getEngine().disableVR();
  94801. }
  94802. if (this._scene.activeCamera) {
  94803. this._position = this._scene.activeCamera.position.clone();
  94804. }
  94805. if (this._deviceOrientationCamera) {
  94806. this._deviceOrientationCamera.position = this._position;
  94807. this._scene.activeCamera = this._deviceOrientationCamera;
  94808. if (this._canvas) {
  94809. this._scene.activeCamera.attachControl(this._canvas);
  94810. }
  94811. }
  94812. else if (this._existingCamera) {
  94813. this._existingCamera.position = this._position;
  94814. this._scene.activeCamera = this._existingCamera;
  94815. }
  94816. this.updateButtonVisibility();
  94817. if (this._interactionsEnabled) {
  94818. this._scene.unregisterBeforeRender(this.beforeRender);
  94819. }
  94820. // resize to update width and height when exiting vr exits fullscreen
  94821. this._scene.getEngine().resize();
  94822. };
  94823. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  94824. /**
  94825. * The position of the vr experience helper.
  94826. */
  94827. get: function () {
  94828. return this._position;
  94829. },
  94830. /**
  94831. * Sets the position of the vr experience helper.
  94832. */
  94833. set: function (value) {
  94834. this._position = value;
  94835. if (this._scene.activeCamera) {
  94836. this._scene.activeCamera.position = value;
  94837. }
  94838. },
  94839. enumerable: true,
  94840. configurable: true
  94841. });
  94842. /**
  94843. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  94844. */
  94845. VRExperienceHelper.prototype.enableInteractions = function () {
  94846. var _this = this;
  94847. if (!this._interactionsEnabled) {
  94848. this._interactionsRequested = true;
  94849. if (this.leftController) {
  94850. this._enableInteractionOnController(this.leftController);
  94851. }
  94852. if (this.rightController) {
  94853. this._enableInteractionOnController(this.rightController);
  94854. }
  94855. this.raySelectionPredicate = function (mesh) {
  94856. return mesh.isVisible && mesh.isPickable;
  94857. };
  94858. this.meshSelectionPredicate = function (mesh) {
  94859. return true;
  94860. };
  94861. this._raySelectionPredicate = function (mesh) {
  94862. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  94863. && mesh.name.indexOf("teleportationTarget") === -1
  94864. && mesh.name.indexOf("torusTeleportation") === -1)) {
  94865. return _this.raySelectionPredicate(mesh);
  94866. }
  94867. return false;
  94868. };
  94869. this._interactionsEnabled = true;
  94870. }
  94871. };
  94872. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  94873. get: function () {
  94874. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  94875. },
  94876. enumerable: true,
  94877. configurable: true
  94878. });
  94879. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  94880. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  94881. if (this._floorMeshesCollection[i].id === mesh.id) {
  94882. return true;
  94883. }
  94884. }
  94885. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  94886. return true;
  94887. }
  94888. return false;
  94889. };
  94890. /**
  94891. * Adds a floor mesh to be used for teleportation.
  94892. * @param floorMesh the mesh to be used for teleportation.
  94893. */
  94894. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  94895. if (!this._floorMeshesCollection) {
  94896. return;
  94897. }
  94898. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  94899. return;
  94900. }
  94901. this._floorMeshesCollection.push(floorMesh);
  94902. };
  94903. /**
  94904. * Removes a floor mesh from being used for teleportation.
  94905. * @param floorMesh the mesh to be removed.
  94906. */
  94907. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  94908. if (!this._floorMeshesCollection) {
  94909. return;
  94910. }
  94911. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  94912. if (meshIndex !== -1) {
  94913. this._floorMeshesCollection.splice(meshIndex, 1);
  94914. }
  94915. };
  94916. /**
  94917. * Enables interactions and teleportation using the VR controllers and gaze.
  94918. * @param vrTeleportationOptions options to modify teleportation behavior.
  94919. */
  94920. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  94921. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  94922. if (!this._teleportationInitialized) {
  94923. this._teleportationRequested = true;
  94924. this.enableInteractions();
  94925. if (vrTeleportationOptions.floorMeshName) {
  94926. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  94927. }
  94928. if (vrTeleportationOptions.floorMeshes) {
  94929. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  94930. }
  94931. if (this.leftController != null) {
  94932. this._enableTeleportationOnController(this.leftController);
  94933. }
  94934. if (this.rightController != null) {
  94935. this._enableTeleportationOnController(this.rightController);
  94936. }
  94937. // Creates an image processing post process for the vignette not relying
  94938. // on the main scene configuration for image processing to reduce setup and spaces
  94939. // (gamma/linear) conflicts.
  94940. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  94941. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  94942. imageProcessingConfiguration.vignetteEnabled = true;
  94943. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  94944. this._webVRCamera.detachPostProcess(this._postProcessMove);
  94945. this._teleportationInitialized = true;
  94946. if (this._isDefaultTeleportationTarget) {
  94947. this._createTeleportationCircles();
  94948. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  94949. }
  94950. }
  94951. };
  94952. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  94953. var _this = this;
  94954. var controllerMesh = controller.webVRController.mesh;
  94955. if (controllerMesh) {
  94956. controller._interactionsEnabled = true;
  94957. controller._activatePointer();
  94958. if (this.webVROptions.laserToggle) {
  94959. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  94960. // Enabling / disabling laserPointer
  94961. if (_this._displayLaserPointer && stateObject.value === 1) {
  94962. if (controller._activePointer) {
  94963. controller._deactivatePointer();
  94964. }
  94965. else {
  94966. controller._activatePointer();
  94967. }
  94968. if (_this.displayGaze) {
  94969. controller._gazeTracker.isVisible = controller._activePointer;
  94970. }
  94971. }
  94972. });
  94973. }
  94974. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  94975. var gazer = controller;
  94976. if (_this._noControllerIsActive) {
  94977. gazer = _this._cameraGazer;
  94978. }
  94979. if (!gazer._pointerDownOnMeshAsked) {
  94980. if (stateObject.value > _this._padSensibilityUp) {
  94981. gazer._selectionPointerDown();
  94982. }
  94983. }
  94984. else if (stateObject.value < _this._padSensibilityDown) {
  94985. gazer._selectionPointerUp();
  94986. }
  94987. });
  94988. }
  94989. };
  94990. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  94991. // Dont teleport if another gaze already requested teleportation
  94992. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  94993. return;
  94994. }
  94995. if (!gazer._teleportationRequestInitiated) {
  94996. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  94997. gazer._activatePointer();
  94998. gazer._teleportationRequestInitiated = true;
  94999. }
  95000. }
  95001. else {
  95002. // Listening to the proper controller values changes to confirm teleportation
  95003. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  95004. if (this._teleportActive) {
  95005. this._teleportCamera(this._haloCenter);
  95006. }
  95007. gazer._teleportationRequestInitiated = false;
  95008. }
  95009. }
  95010. };
  95011. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  95012. // Only rotate when user is not currently selecting a teleportation location
  95013. if (gazer._teleportationRequestInitiated) {
  95014. return;
  95015. }
  95016. if (!gazer._rotationLeftAsked) {
  95017. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  95018. gazer._rotationLeftAsked = true;
  95019. if (this._rotationAllowed) {
  95020. this._rotateCamera(false);
  95021. }
  95022. }
  95023. }
  95024. else {
  95025. if (stateObject.x > -this._padSensibilityDown) {
  95026. gazer._rotationLeftAsked = false;
  95027. }
  95028. }
  95029. if (!gazer._rotationRightAsked) {
  95030. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  95031. gazer._rotationRightAsked = true;
  95032. if (this._rotationAllowed) {
  95033. this._rotateCamera(true);
  95034. }
  95035. }
  95036. }
  95037. else {
  95038. if (stateObject.x < this._padSensibilityDown) {
  95039. gazer._rotationRightAsked = false;
  95040. }
  95041. }
  95042. };
  95043. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  95044. // Only teleport backwards when user is not currently selecting a teleportation location
  95045. if (gazer._teleportationRequestInitiated) {
  95046. return;
  95047. }
  95048. // Teleport backwards
  95049. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  95050. if (!gazer._teleportationBackRequestInitiated) {
  95051. if (!this.currentVRCamera) {
  95052. return;
  95053. }
  95054. // Get rotation and position of the current camera
  95055. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  95056. var position = this.currentVRCamera.position;
  95057. // If the camera has device position, use that instead
  95058. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  95059. rotation = this.currentVRCamera.deviceRotationQuaternion;
  95060. position = this.currentVRCamera.devicePosition;
  95061. }
  95062. // Get matrix with only the y rotation of the device rotation
  95063. rotation.toEulerAnglesToRef(this._workingVector);
  95064. this._workingVector.z = 0;
  95065. this._workingVector.x = 0;
  95066. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  95067. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  95068. // Rotate backwards ray by device rotation to cast at the ground behind the user
  95069. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  95070. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  95071. var ray = new BABYLON.Ray(position, this._workingVector);
  95072. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  95073. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  95074. this._teleportCamera(hit.pickedPoint);
  95075. }
  95076. gazer._teleportationBackRequestInitiated = true;
  95077. }
  95078. }
  95079. else {
  95080. gazer._teleportationBackRequestInitiated = false;
  95081. }
  95082. };
  95083. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  95084. var _this = this;
  95085. var controllerMesh = controller.webVRController.mesh;
  95086. if (controllerMesh) {
  95087. if (!controller._interactionsEnabled) {
  95088. this._enableInteractionOnController(controller);
  95089. }
  95090. controller._interactionsEnabled = true;
  95091. controller._teleportationEnabled = true;
  95092. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  95093. controller._dpadPressed = false;
  95094. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  95095. controller._dpadPressed = stateObject.pressed;
  95096. if (!controller._dpadPressed) {
  95097. controller._rotationLeftAsked = false;
  95098. controller._rotationRightAsked = false;
  95099. controller._teleportationBackRequestInitiated = false;
  95100. }
  95101. });
  95102. }
  95103. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  95104. if (_this.teleportationEnabled) {
  95105. _this._checkTeleportBackwards(stateObject, controller);
  95106. _this._checkTeleportWithRay(stateObject, controller);
  95107. }
  95108. _this._checkRotate(stateObject, controller);
  95109. });
  95110. }
  95111. };
  95112. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  95113. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  95114. this._teleportationTarget.isPickable = false;
  95115. var length = 512;
  95116. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  95117. dynamicTexture.hasAlpha = true;
  95118. var context = dynamicTexture.getContext();
  95119. var centerX = length / 2;
  95120. var centerY = length / 2;
  95121. var radius = 200;
  95122. context.beginPath();
  95123. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  95124. context.fillStyle = this._teleportationFillColor;
  95125. context.fill();
  95126. context.lineWidth = 10;
  95127. context.strokeStyle = this._teleportationBorderColor;
  95128. context.stroke();
  95129. context.closePath();
  95130. dynamicTexture.update();
  95131. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  95132. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  95133. this._teleportationTarget.material = teleportationCircleMaterial;
  95134. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  95135. torus.isPickable = false;
  95136. torus.parent = this._teleportationTarget;
  95137. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  95138. var keys = [];
  95139. keys.push({
  95140. frame: 0,
  95141. value: 0
  95142. });
  95143. keys.push({
  95144. frame: 30,
  95145. value: 0.4
  95146. });
  95147. keys.push({
  95148. frame: 60,
  95149. value: 0
  95150. });
  95151. animationInnerCircle.setKeys(keys);
  95152. var easingFunction = new BABYLON.SineEase();
  95153. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  95154. animationInnerCircle.setEasingFunction(easingFunction);
  95155. torus.animations = [];
  95156. torus.animations.push(animationInnerCircle);
  95157. this._scene.beginAnimation(torus, 0, 60, true);
  95158. this._hideTeleportationTarget();
  95159. };
  95160. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  95161. this._teleportActive = true;
  95162. if (this._teleportationInitialized) {
  95163. this._teleportationTarget.isVisible = true;
  95164. if (this._isDefaultTeleportationTarget) {
  95165. this._teleportationTarget.getChildren()[0].isVisible = true;
  95166. }
  95167. }
  95168. };
  95169. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  95170. this._teleportActive = false;
  95171. if (this._teleportationInitialized) {
  95172. this._teleportationTarget.isVisible = false;
  95173. if (this._isDefaultTeleportationTarget) {
  95174. this._teleportationTarget.getChildren()[0].isVisible = false;
  95175. }
  95176. }
  95177. };
  95178. VRExperienceHelper.prototype._rotateCamera = function (right) {
  95179. var _this = this;
  95180. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  95181. return;
  95182. }
  95183. if (right) {
  95184. this._rotationAngle++;
  95185. }
  95186. else {
  95187. this._rotationAngle--;
  95188. }
  95189. this.currentVRCamera.animations = [];
  95190. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  95191. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95192. var animationRotationKeys = [];
  95193. animationRotationKeys.push({
  95194. frame: 0,
  95195. value: this.currentVRCamera.rotationQuaternion
  95196. });
  95197. animationRotationKeys.push({
  95198. frame: 6,
  95199. value: target
  95200. });
  95201. animationRotation.setKeys(animationRotationKeys);
  95202. animationRotation.setEasingFunction(this._circleEase);
  95203. this.currentVRCamera.animations.push(animationRotation);
  95204. this._postProcessMove.animations = [];
  95205. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95206. var vignetteWeightKeys = [];
  95207. vignetteWeightKeys.push({
  95208. frame: 0,
  95209. value: 0
  95210. });
  95211. vignetteWeightKeys.push({
  95212. frame: 3,
  95213. value: 4
  95214. });
  95215. vignetteWeightKeys.push({
  95216. frame: 6,
  95217. value: 0
  95218. });
  95219. animationPP.setKeys(vignetteWeightKeys);
  95220. animationPP.setEasingFunction(this._circleEase);
  95221. this._postProcessMove.animations.push(animationPP);
  95222. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95223. var vignetteStretchKeys = [];
  95224. vignetteStretchKeys.push({
  95225. frame: 0,
  95226. value: 0
  95227. });
  95228. vignetteStretchKeys.push({
  95229. frame: 3,
  95230. value: 10
  95231. });
  95232. vignetteStretchKeys.push({
  95233. frame: 6,
  95234. value: 0
  95235. });
  95236. animationPP2.setKeys(vignetteStretchKeys);
  95237. animationPP2.setEasingFunction(this._circleEase);
  95238. this._postProcessMove.animations.push(animationPP2);
  95239. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  95240. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  95241. this._postProcessMove.samples = 4;
  95242. this._webVRCamera.attachPostProcess(this._postProcessMove);
  95243. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  95244. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  95245. });
  95246. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  95247. };
  95248. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  95249. if (hit.pickedPoint) {
  95250. if (gazer._teleportationRequestInitiated) {
  95251. this._displayTeleportationTarget();
  95252. this._haloCenter.copyFrom(hit.pickedPoint);
  95253. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  95254. }
  95255. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  95256. if (pickNormal) {
  95257. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  95258. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  95259. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  95260. }
  95261. this._teleportationTarget.position.y += 0.1;
  95262. }
  95263. };
  95264. VRExperienceHelper.prototype._teleportCamera = function (location) {
  95265. var _this = this;
  95266. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  95267. return;
  95268. }
  95269. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  95270. // offset of the headset from the anchor.
  95271. if (this.webVRCamera.leftCamera) {
  95272. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  95273. this._workingVector.subtractInPlace(this.webVRCamera.position);
  95274. location.subtractToRef(this._workingVector, this._workingVector);
  95275. }
  95276. else {
  95277. this._workingVector.copyFrom(location);
  95278. }
  95279. // Add height to account for user's height offset
  95280. if (this.isInVRMode) {
  95281. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  95282. }
  95283. else {
  95284. this._workingVector.y += this._defaultHeight;
  95285. }
  95286. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  95287. // Create animation from the camera's position to the new location
  95288. this.currentVRCamera.animations = [];
  95289. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95290. var animationCameraTeleportationKeys = [{
  95291. frame: 0,
  95292. value: this.currentVRCamera.position
  95293. },
  95294. {
  95295. frame: 11,
  95296. value: this._workingVector
  95297. }
  95298. ];
  95299. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  95300. animationCameraTeleportation.setEasingFunction(this._circleEase);
  95301. this.currentVRCamera.animations.push(animationCameraTeleportation);
  95302. this._postProcessMove.animations = [];
  95303. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95304. var vignetteWeightKeys = [];
  95305. vignetteWeightKeys.push({
  95306. frame: 0,
  95307. value: 0
  95308. });
  95309. vignetteWeightKeys.push({
  95310. frame: 5,
  95311. value: 8
  95312. });
  95313. vignetteWeightKeys.push({
  95314. frame: 11,
  95315. value: 0
  95316. });
  95317. animationPP.setKeys(vignetteWeightKeys);
  95318. this._postProcessMove.animations.push(animationPP);
  95319. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95320. var vignetteStretchKeys = [];
  95321. vignetteStretchKeys.push({
  95322. frame: 0,
  95323. value: 0
  95324. });
  95325. vignetteStretchKeys.push({
  95326. frame: 5,
  95327. value: 10
  95328. });
  95329. vignetteStretchKeys.push({
  95330. frame: 11,
  95331. value: 0
  95332. });
  95333. animationPP2.setKeys(vignetteStretchKeys);
  95334. this._postProcessMove.animations.push(animationPP2);
  95335. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  95336. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  95337. this._webVRCamera.attachPostProcess(this._postProcessMove);
  95338. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  95339. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  95340. });
  95341. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  95342. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  95343. });
  95344. this._hideTeleportationTarget();
  95345. };
  95346. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  95347. if (normal) {
  95348. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  95349. if (angle < Math.PI / 2) {
  95350. normal.scaleInPlace(-1);
  95351. }
  95352. }
  95353. return normal;
  95354. };
  95355. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  95356. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  95357. return;
  95358. }
  95359. var ray = gazer._getForwardRay(this._rayLength);
  95360. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  95361. if (hit) {
  95362. // Populate the contrllers mesh that can be used for drag/drop
  95363. if (gazer._laserPointer) {
  95364. hit.originMesh = gazer._laserPointer.parent;
  95365. }
  95366. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  95367. }
  95368. gazer._currentHit = hit;
  95369. // Moving the gazeTracker on the mesh face targetted
  95370. if (hit && hit.pickedPoint) {
  95371. if (this._displayGaze) {
  95372. var multiplier = 1;
  95373. gazer._gazeTracker.isVisible = true;
  95374. if (gazer._isActionableMesh) {
  95375. multiplier = 3;
  95376. }
  95377. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  95378. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  95379. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  95380. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  95381. // To avoid z-fighting
  95382. var deltaFighting = 0.002;
  95383. if (pickNormal) {
  95384. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  95385. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  95386. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  95387. }
  95388. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  95389. if (gazer._gazeTracker.position.x < 0) {
  95390. gazer._gazeTracker.position.x += deltaFighting;
  95391. }
  95392. else {
  95393. gazer._gazeTracker.position.x -= deltaFighting;
  95394. }
  95395. if (gazer._gazeTracker.position.y < 0) {
  95396. gazer._gazeTracker.position.y += deltaFighting;
  95397. }
  95398. else {
  95399. gazer._gazeTracker.position.y -= deltaFighting;
  95400. }
  95401. if (gazer._gazeTracker.position.z < 0) {
  95402. gazer._gazeTracker.position.z += deltaFighting;
  95403. }
  95404. else {
  95405. gazer._gazeTracker.position.z -= deltaFighting;
  95406. }
  95407. }
  95408. // Changing the size of the laser pointer based on the distance from the targetted point
  95409. gazer._updatePointerDistance(hit.distance);
  95410. }
  95411. else {
  95412. gazer._updatePointerDistance();
  95413. gazer._gazeTracker.isVisible = false;
  95414. }
  95415. if (hit && hit.pickedMesh) {
  95416. // The object selected is the floor, we're in a teleportation scenario
  95417. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  95418. // Moving the teleportation area to this targetted point
  95419. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  95420. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  95421. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  95422. }
  95423. gazer._currentMeshSelected = null;
  95424. if (gazer._teleportationRequestInitiated) {
  95425. this._moveTeleportationSelectorTo(hit, gazer, ray);
  95426. }
  95427. return;
  95428. }
  95429. // If not, we're in a selection scenario
  95430. //this._teleportationAllowed = false;
  95431. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  95432. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  95433. this.onNewMeshPicked.notifyObservers(hit);
  95434. gazer._currentMeshSelected = hit.pickedMesh;
  95435. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  95436. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  95437. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  95438. gazer._isActionableMesh = true;
  95439. }
  95440. else {
  95441. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95442. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95443. gazer._isActionableMesh = false;
  95444. }
  95445. try {
  95446. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  95447. }
  95448. catch (err) {
  95449. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  95450. }
  95451. }
  95452. else {
  95453. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  95454. gazer._currentMeshSelected = null;
  95455. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95456. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95457. }
  95458. }
  95459. }
  95460. else {
  95461. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  95462. gazer._currentMeshSelected = null;
  95463. //this._teleportationAllowed = false;
  95464. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95465. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95466. }
  95467. };
  95468. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  95469. if (mesh) {
  95470. this.onSelectedMeshUnselected.notifyObservers(mesh);
  95471. }
  95472. };
  95473. /**
  95474. * Sets the color of the laser ray from the vr controllers.
  95475. * @param color new color for the ray.
  95476. */
  95477. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  95478. if (this.leftController) {
  95479. this.leftController._setLaserPointerColor(color);
  95480. }
  95481. if (this.rightController) {
  95482. this.rightController._setLaserPointerColor(color);
  95483. }
  95484. };
  95485. /**
  95486. * Sets the color of the ray from the vr headsets gaze.
  95487. * @param color new color for the ray.
  95488. */
  95489. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  95490. if (!this._cameraGazer._gazeTracker.material) {
  95491. return;
  95492. }
  95493. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  95494. if (this.leftController) {
  95495. this.leftController._gazeTracker.material.emissiveColor = color;
  95496. }
  95497. if (this.rightController) {
  95498. this.rightController._gazeTracker.material.emissiveColor = color;
  95499. }
  95500. };
  95501. /**
  95502. * Exits VR and disposes of the vr experience helper
  95503. */
  95504. VRExperienceHelper.prototype.dispose = function () {
  95505. if (this.isInVRMode) {
  95506. this.exitVR();
  95507. }
  95508. if (this._postProcessMove) {
  95509. this._postProcessMove.dispose();
  95510. }
  95511. if (this._webVRCamera) {
  95512. this._webVRCamera.dispose();
  95513. }
  95514. if (this._vrDeviceOrientationCamera) {
  95515. this._vrDeviceOrientationCamera.dispose();
  95516. }
  95517. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  95518. document.body.removeChild(this._btnVR);
  95519. }
  95520. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  95521. this._deviceOrientationCamera.dispose();
  95522. }
  95523. if (this._cameraGazer) {
  95524. this._cameraGazer.dispose();
  95525. }
  95526. if (this.leftController) {
  95527. this.leftController.dispose();
  95528. }
  95529. if (this.rightController) {
  95530. this.rightController.dispose();
  95531. }
  95532. if (this._teleportationTarget) {
  95533. this._teleportationTarget.dispose();
  95534. }
  95535. this._floorMeshesCollection = [];
  95536. document.removeEventListener("keydown", this._onKeyDown);
  95537. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  95538. window.removeEventListener("resize", this._onResize);
  95539. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  95540. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  95541. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  95542. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  95543. document.onmsfullscreenchange = null;
  95544. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  95545. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  95546. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  95547. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  95548. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  95549. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  95550. this._scene.unregisterBeforeRender(this.beforeRender);
  95551. };
  95552. /**
  95553. * Gets the name of the VRExperienceHelper class
  95554. * @returns "VRExperienceHelper"
  95555. */
  95556. VRExperienceHelper.prototype.getClassName = function () {
  95557. return "VRExperienceHelper";
  95558. };
  95559. return VRExperienceHelper;
  95560. }());
  95561. BABYLON.VRExperienceHelper = VRExperienceHelper;
  95562. })(BABYLON || (BABYLON = {}));
  95563. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  95564. // Mainly based on these 2 articles :
  95565. // 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
  95566. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  95567. var BABYLON;
  95568. (function (BABYLON) {
  95569. /**
  95570. * Defines the potential axis of a Joystick
  95571. */
  95572. var JoystickAxis;
  95573. (function (JoystickAxis) {
  95574. /** X axis */
  95575. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  95576. /** Y axis */
  95577. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  95578. /** Z axis */
  95579. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  95580. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  95581. /**
  95582. * Class used to define virtual joystick (used in touch mode)
  95583. */
  95584. var VirtualJoystick = /** @class */ (function () {
  95585. /**
  95586. * Creates a new virtual joystick
  95587. * @param leftJoystick defines that the joystick is for left hand (false by default)
  95588. */
  95589. function VirtualJoystick(leftJoystick) {
  95590. var _this = this;
  95591. if (leftJoystick) {
  95592. this._leftJoystick = true;
  95593. }
  95594. else {
  95595. this._leftJoystick = false;
  95596. }
  95597. VirtualJoystick._globalJoystickIndex++;
  95598. // By default left & right arrow keys are moving the X
  95599. // and up & down keys are moving the Y
  95600. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  95601. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  95602. this.reverseLeftRight = false;
  95603. this.reverseUpDown = false;
  95604. // collections of pointers
  95605. this._touches = new BABYLON.StringDictionary();
  95606. this.deltaPosition = BABYLON.Vector3.Zero();
  95607. this._joystickSensibility = 25;
  95608. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  95609. this._onResize = function (evt) {
  95610. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  95611. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  95612. if (VirtualJoystick.vjCanvas) {
  95613. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  95614. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  95615. }
  95616. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  95617. };
  95618. // injecting a canvas element on top of the canvas 3D game
  95619. if (!VirtualJoystick.vjCanvas) {
  95620. window.addEventListener("resize", this._onResize, false);
  95621. VirtualJoystick.vjCanvas = document.createElement("canvas");
  95622. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  95623. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  95624. VirtualJoystick.vjCanvas.width = window.innerWidth;
  95625. VirtualJoystick.vjCanvas.height = window.innerHeight;
  95626. VirtualJoystick.vjCanvas.style.width = "100%";
  95627. VirtualJoystick.vjCanvas.style.height = "100%";
  95628. VirtualJoystick.vjCanvas.style.position = "absolute";
  95629. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  95630. VirtualJoystick.vjCanvas.style.top = "0px";
  95631. VirtualJoystick.vjCanvas.style.left = "0px";
  95632. VirtualJoystick.vjCanvas.style.zIndex = "5";
  95633. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  95634. // Support for jQuery PEP polyfill
  95635. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  95636. var context = VirtualJoystick.vjCanvas.getContext('2d');
  95637. if (!context) {
  95638. throw new Error("Unable to create canvas for virtual joystick");
  95639. }
  95640. VirtualJoystick.vjCanvasContext = context;
  95641. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  95642. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  95643. document.body.appendChild(VirtualJoystick.vjCanvas);
  95644. }
  95645. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  95646. this.pressed = false;
  95647. // default joystick color
  95648. this._joystickColor = "cyan";
  95649. this._joystickPointerID = -1;
  95650. // current joystick position
  95651. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  95652. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  95653. // origin joystick position
  95654. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  95655. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  95656. this._onPointerDownHandlerRef = function (evt) {
  95657. _this._onPointerDown(evt);
  95658. };
  95659. this._onPointerMoveHandlerRef = function (evt) {
  95660. _this._onPointerMove(evt);
  95661. };
  95662. this._onPointerUpHandlerRef = function (evt) {
  95663. _this._onPointerUp(evt);
  95664. };
  95665. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  95666. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  95667. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  95668. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  95669. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  95670. evt.preventDefault(); // Disables system menu
  95671. }, false);
  95672. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  95673. }
  95674. /**
  95675. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  95676. * @param newJoystickSensibility defines the new sensibility
  95677. */
  95678. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  95679. this._joystickSensibility = newJoystickSensibility;
  95680. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  95681. };
  95682. VirtualJoystick.prototype._onPointerDown = function (e) {
  95683. var positionOnScreenCondition;
  95684. e.preventDefault();
  95685. if (this._leftJoystick === true) {
  95686. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  95687. }
  95688. else {
  95689. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  95690. }
  95691. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  95692. // First contact will be dedicated to the virtual joystick
  95693. this._joystickPointerID = e.pointerId;
  95694. this._joystickPointerStartPos.x = e.clientX;
  95695. this._joystickPointerStartPos.y = e.clientY;
  95696. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  95697. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  95698. this._deltaJoystickVector.x = 0;
  95699. this._deltaJoystickVector.y = 0;
  95700. this.pressed = true;
  95701. this._touches.add(e.pointerId.toString(), e);
  95702. }
  95703. else {
  95704. // You can only trigger the action buttons with a joystick declared
  95705. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  95706. this._action();
  95707. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  95708. }
  95709. }
  95710. };
  95711. VirtualJoystick.prototype._onPointerMove = function (e) {
  95712. // If the current pointer is the one associated to the joystick (first touch contact)
  95713. if (this._joystickPointerID == e.pointerId) {
  95714. this._joystickPointerPos.x = e.clientX;
  95715. this._joystickPointerPos.y = e.clientY;
  95716. this._deltaJoystickVector = this._joystickPointerPos.clone();
  95717. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  95718. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  95719. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  95720. switch (this._axisTargetedByLeftAndRight) {
  95721. case JoystickAxis.X:
  95722. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  95723. break;
  95724. case JoystickAxis.Y:
  95725. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  95726. break;
  95727. case JoystickAxis.Z:
  95728. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  95729. break;
  95730. }
  95731. var directionUpDown = this.reverseUpDown ? 1 : -1;
  95732. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  95733. switch (this._axisTargetedByUpAndDown) {
  95734. case JoystickAxis.X:
  95735. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  95736. break;
  95737. case JoystickAxis.Y:
  95738. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  95739. break;
  95740. case JoystickAxis.Z:
  95741. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  95742. break;
  95743. }
  95744. }
  95745. else {
  95746. var data = this._touches.get(e.pointerId.toString());
  95747. if (data) {
  95748. data.x = e.clientX;
  95749. data.y = e.clientY;
  95750. }
  95751. }
  95752. };
  95753. VirtualJoystick.prototype._onPointerUp = function (e) {
  95754. if (this._joystickPointerID == e.pointerId) {
  95755. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  95756. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  95757. this._joystickPointerID = -1;
  95758. this.pressed = false;
  95759. }
  95760. else {
  95761. var touch = this._touches.get(e.pointerId.toString());
  95762. if (touch) {
  95763. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  95764. }
  95765. }
  95766. this._deltaJoystickVector.x = 0;
  95767. this._deltaJoystickVector.y = 0;
  95768. this._touches.remove(e.pointerId.toString());
  95769. };
  95770. /**
  95771. * Change the color of the virtual joystick
  95772. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  95773. */
  95774. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  95775. this._joystickColor = newColor;
  95776. };
  95777. /**
  95778. * Defines a callback to call when the joystick is touched
  95779. * @param action defines the callback
  95780. */
  95781. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  95782. this._action = action;
  95783. };
  95784. /**
  95785. * Defines which axis you'd like to control for left & right
  95786. * @param axis defines the axis to use
  95787. */
  95788. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  95789. switch (axis) {
  95790. case JoystickAxis.X:
  95791. case JoystickAxis.Y:
  95792. case JoystickAxis.Z:
  95793. this._axisTargetedByLeftAndRight = axis;
  95794. break;
  95795. default:
  95796. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  95797. break;
  95798. }
  95799. };
  95800. /**
  95801. * Defines which axis you'd like to control for up & down
  95802. * @param axis defines the axis to use
  95803. */
  95804. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  95805. switch (axis) {
  95806. case JoystickAxis.X:
  95807. case JoystickAxis.Y:
  95808. case JoystickAxis.Z:
  95809. this._axisTargetedByUpAndDown = axis;
  95810. break;
  95811. default:
  95812. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  95813. break;
  95814. }
  95815. };
  95816. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  95817. var _this = this;
  95818. if (this.pressed) {
  95819. this._touches.forEach(function (key, touch) {
  95820. if (touch.pointerId === _this._joystickPointerID) {
  95821. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  95822. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  95823. VirtualJoystick.vjCanvasContext.beginPath();
  95824. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95825. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95826. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  95827. VirtualJoystick.vjCanvasContext.stroke();
  95828. VirtualJoystick.vjCanvasContext.closePath();
  95829. VirtualJoystick.vjCanvasContext.beginPath();
  95830. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95831. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  95832. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  95833. VirtualJoystick.vjCanvasContext.stroke();
  95834. VirtualJoystick.vjCanvasContext.closePath();
  95835. VirtualJoystick.vjCanvasContext.beginPath();
  95836. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95837. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  95838. VirtualJoystick.vjCanvasContext.stroke();
  95839. VirtualJoystick.vjCanvasContext.closePath();
  95840. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  95841. }
  95842. else {
  95843. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  95844. VirtualJoystick.vjCanvasContext.beginPath();
  95845. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  95846. VirtualJoystick.vjCanvasContext.beginPath();
  95847. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  95848. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95849. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  95850. VirtualJoystick.vjCanvasContext.stroke();
  95851. VirtualJoystick.vjCanvasContext.closePath();
  95852. touch.prevX = touch.x;
  95853. touch.prevY = touch.y;
  95854. }
  95855. ;
  95856. });
  95857. }
  95858. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  95859. };
  95860. /**
  95861. * Release internal HTML canvas
  95862. */
  95863. VirtualJoystick.prototype.releaseCanvas = function () {
  95864. if (VirtualJoystick.vjCanvas) {
  95865. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  95866. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  95867. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  95868. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  95869. window.removeEventListener("resize", this._onResize);
  95870. document.body.removeChild(VirtualJoystick.vjCanvas);
  95871. VirtualJoystick.vjCanvas = null;
  95872. }
  95873. };
  95874. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  95875. VirtualJoystick._globalJoystickIndex = 0;
  95876. return VirtualJoystick;
  95877. }());
  95878. BABYLON.VirtualJoystick = VirtualJoystick;
  95879. })(BABYLON || (BABYLON = {}));
  95880. //# sourceMappingURL=babylon.virtualJoystick.js.map
  95881. var BABYLON;
  95882. (function (BABYLON) {
  95883. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  95884. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  95885. });
  95886. // We're mainly based on the logic defined into the FreeCamera code
  95887. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  95888. __extends(VirtualJoysticksCamera, _super);
  95889. function VirtualJoysticksCamera(name, position, scene) {
  95890. var _this = _super.call(this, name, position, scene) || this;
  95891. _this.inputs.addVirtualJoystick();
  95892. return _this;
  95893. }
  95894. VirtualJoysticksCamera.prototype.getClassName = function () {
  95895. return "VirtualJoysticksCamera";
  95896. };
  95897. return VirtualJoysticksCamera;
  95898. }(BABYLON.FreeCamera));
  95899. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  95900. })(BABYLON || (BABYLON = {}));
  95901. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  95902. var BABYLON;
  95903. (function (BABYLON) {
  95904. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  95905. function FreeCameraVirtualJoystickInput() {
  95906. }
  95907. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  95908. return this._leftjoystick;
  95909. };
  95910. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  95911. return this._rightjoystick;
  95912. };
  95913. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  95914. if (this._leftjoystick) {
  95915. var camera = this.camera;
  95916. var speed = camera._computeLocalCameraSpeed() * 50;
  95917. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  95918. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  95919. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  95920. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  95921. if (!this._leftjoystick.pressed) {
  95922. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  95923. }
  95924. if (!this._rightjoystick.pressed) {
  95925. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  95926. }
  95927. }
  95928. };
  95929. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  95930. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  95931. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  95932. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  95933. this._leftjoystick.setJoystickSensibility(0.15);
  95934. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  95935. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  95936. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  95937. this._rightjoystick.reverseUpDown = true;
  95938. this._rightjoystick.setJoystickSensibility(0.05);
  95939. this._rightjoystick.setJoystickColor("yellow");
  95940. };
  95941. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  95942. this._leftjoystick.releaseCanvas();
  95943. this._rightjoystick.releaseCanvas();
  95944. };
  95945. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  95946. return "FreeCameraVirtualJoystickInput";
  95947. };
  95948. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  95949. return "virtualJoystick";
  95950. };
  95951. return FreeCameraVirtualJoystickInput;
  95952. }());
  95953. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  95954. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  95955. })(BABYLON || (BABYLON = {}));
  95956. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  95957. var BABYLON;
  95958. (function (BABYLON) {
  95959. var SimplificationSettings = /** @class */ (function () {
  95960. function SimplificationSettings(quality, distance, optimizeMesh) {
  95961. this.quality = quality;
  95962. this.distance = distance;
  95963. this.optimizeMesh = optimizeMesh;
  95964. }
  95965. return SimplificationSettings;
  95966. }());
  95967. BABYLON.SimplificationSettings = SimplificationSettings;
  95968. var SimplificationQueue = /** @class */ (function () {
  95969. function SimplificationQueue() {
  95970. this.running = false;
  95971. this._simplificationArray = [];
  95972. }
  95973. SimplificationQueue.prototype.addTask = function (task) {
  95974. this._simplificationArray.push(task);
  95975. };
  95976. SimplificationQueue.prototype.executeNext = function () {
  95977. var task = this._simplificationArray.pop();
  95978. if (task) {
  95979. this.running = true;
  95980. this.runSimplification(task);
  95981. }
  95982. else {
  95983. this.running = false;
  95984. }
  95985. };
  95986. SimplificationQueue.prototype.runSimplification = function (task) {
  95987. var _this = this;
  95988. if (task.parallelProcessing) {
  95989. //parallel simplifier
  95990. task.settings.forEach(function (setting) {
  95991. var simplifier = _this.getSimplifier(task);
  95992. simplifier.simplify(setting, function (newMesh) {
  95993. task.mesh.addLODLevel(setting.distance, newMesh);
  95994. newMesh.isVisible = true;
  95995. //check if it is the last
  95996. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  95997. //all done, run the success callback.
  95998. task.successCallback();
  95999. }
  96000. _this.executeNext();
  96001. });
  96002. });
  96003. }
  96004. else {
  96005. //single simplifier.
  96006. var simplifier = this.getSimplifier(task);
  96007. var runDecimation = function (setting, callback) {
  96008. simplifier.simplify(setting, function (newMesh) {
  96009. task.mesh.addLODLevel(setting.distance, newMesh);
  96010. newMesh.isVisible = true;
  96011. //run the next quality level
  96012. callback();
  96013. });
  96014. };
  96015. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  96016. runDecimation(task.settings[loop.index], function () {
  96017. loop.executeNext();
  96018. });
  96019. }, function () {
  96020. //execution ended, run the success callback.
  96021. if (task.successCallback) {
  96022. task.successCallback();
  96023. }
  96024. _this.executeNext();
  96025. });
  96026. }
  96027. };
  96028. SimplificationQueue.prototype.getSimplifier = function (task) {
  96029. switch (task.simplificationType) {
  96030. case SimplificationType.QUADRATIC:
  96031. default:
  96032. return new QuadraticErrorSimplification(task.mesh);
  96033. }
  96034. };
  96035. return SimplificationQueue;
  96036. }());
  96037. BABYLON.SimplificationQueue = SimplificationQueue;
  96038. /**
  96039. * The implemented types of simplification
  96040. * At the moment only Quadratic Error Decimation is implemented
  96041. */
  96042. var SimplificationType;
  96043. (function (SimplificationType) {
  96044. /** Quadratic error decimation */
  96045. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  96046. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  96047. var DecimationTriangle = /** @class */ (function () {
  96048. function DecimationTriangle(vertices) {
  96049. this.vertices = vertices;
  96050. this.error = new Array(4);
  96051. this.deleted = false;
  96052. this.isDirty = false;
  96053. this.deletePending = false;
  96054. this.borderFactor = 0;
  96055. }
  96056. return DecimationTriangle;
  96057. }());
  96058. BABYLON.DecimationTriangle = DecimationTriangle;
  96059. var DecimationVertex = /** @class */ (function () {
  96060. function DecimationVertex(position, id) {
  96061. this.position = position;
  96062. this.id = id;
  96063. this.isBorder = true;
  96064. this.q = new QuadraticMatrix();
  96065. this.triangleCount = 0;
  96066. this.triangleStart = 0;
  96067. this.originalOffsets = [];
  96068. }
  96069. DecimationVertex.prototype.updatePosition = function (newPosition) {
  96070. this.position.copyFrom(newPosition);
  96071. };
  96072. return DecimationVertex;
  96073. }());
  96074. BABYLON.DecimationVertex = DecimationVertex;
  96075. var QuadraticMatrix = /** @class */ (function () {
  96076. function QuadraticMatrix(data) {
  96077. this.data = new Array(10);
  96078. for (var i = 0; i < 10; ++i) {
  96079. if (data && data[i]) {
  96080. this.data[i] = data[i];
  96081. }
  96082. else {
  96083. this.data[i] = 0;
  96084. }
  96085. }
  96086. }
  96087. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  96088. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  96089. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  96090. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  96091. return det;
  96092. };
  96093. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  96094. for (var i = 0; i < 10; ++i) {
  96095. this.data[i] += matrix.data[i];
  96096. }
  96097. };
  96098. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  96099. for (var i = 0; i < 10; ++i) {
  96100. this.data[i] += data[i];
  96101. }
  96102. };
  96103. QuadraticMatrix.prototype.add = function (matrix) {
  96104. var m = new QuadraticMatrix();
  96105. for (var i = 0; i < 10; ++i) {
  96106. m.data[i] = this.data[i] + matrix.data[i];
  96107. }
  96108. return m;
  96109. };
  96110. QuadraticMatrix.FromData = function (a, b, c, d) {
  96111. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  96112. };
  96113. //returning an array to avoid garbage collection
  96114. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  96115. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  96116. };
  96117. return QuadraticMatrix;
  96118. }());
  96119. BABYLON.QuadraticMatrix = QuadraticMatrix;
  96120. var Reference = /** @class */ (function () {
  96121. function Reference(vertexId, triangleId) {
  96122. this.vertexId = vertexId;
  96123. this.triangleId = triangleId;
  96124. }
  96125. return Reference;
  96126. }());
  96127. BABYLON.Reference = Reference;
  96128. /**
  96129. * An implementation of the Quadratic Error simplification algorithm.
  96130. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  96131. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  96132. * @author RaananW
  96133. */
  96134. var QuadraticErrorSimplification = /** @class */ (function () {
  96135. function QuadraticErrorSimplification(_mesh) {
  96136. this._mesh = _mesh;
  96137. this.syncIterations = 5000;
  96138. this.aggressiveness = 7;
  96139. this.decimationIterations = 100;
  96140. this.boundingBoxEpsilon = BABYLON.Epsilon;
  96141. }
  96142. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  96143. var _this = this;
  96144. this.initDecimatedMesh();
  96145. //iterating through the submeshes array, one after the other.
  96146. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  96147. _this.initWithMesh(loop.index, function () {
  96148. _this.runDecimation(settings, loop.index, function () {
  96149. loop.executeNext();
  96150. });
  96151. }, settings.optimizeMesh);
  96152. }, function () {
  96153. setTimeout(function () {
  96154. successCallback(_this._reconstructedMesh);
  96155. }, 0);
  96156. });
  96157. };
  96158. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  96159. var _this = this;
  96160. var targetCount = ~~(this.triangles.length * settings.quality);
  96161. var deletedTriangles = 0;
  96162. var triangleCount = this.triangles.length;
  96163. var iterationFunction = function (iteration, callback) {
  96164. setTimeout(function () {
  96165. if (iteration % 5 === 0) {
  96166. _this.updateMesh(iteration === 0);
  96167. }
  96168. for (var i = 0; i < _this.triangles.length; ++i) {
  96169. _this.triangles[i].isDirty = false;
  96170. }
  96171. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  96172. var trianglesIterator = function (i) {
  96173. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  96174. var t = _this.triangles[tIdx];
  96175. if (!t)
  96176. return;
  96177. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  96178. return;
  96179. }
  96180. for (var j = 0; j < 3; ++j) {
  96181. if (t.error[j] < threshold) {
  96182. var deleted0 = [];
  96183. var deleted1 = [];
  96184. var v0 = t.vertices[j];
  96185. var v1 = t.vertices[(j + 1) % 3];
  96186. if (v0.isBorder || v1.isBorder)
  96187. continue;
  96188. var p = BABYLON.Vector3.Zero();
  96189. var n = BABYLON.Vector3.Zero();
  96190. var uv = BABYLON.Vector2.Zero();
  96191. var color = new BABYLON.Color4(0, 0, 0, 1);
  96192. _this.calculateError(v0, v1, p, n, uv, color);
  96193. var delTr = new Array();
  96194. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  96195. continue;
  96196. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  96197. continue;
  96198. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  96199. continue;
  96200. var uniqueArray = new Array();
  96201. delTr.forEach(function (deletedT) {
  96202. if (uniqueArray.indexOf(deletedT) === -1) {
  96203. deletedT.deletePending = true;
  96204. uniqueArray.push(deletedT);
  96205. }
  96206. });
  96207. if (uniqueArray.length % 2 !== 0) {
  96208. continue;
  96209. }
  96210. v0.q = v1.q.add(v0.q);
  96211. v0.updatePosition(p);
  96212. var tStart = _this.references.length;
  96213. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  96214. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  96215. var tCount = _this.references.length - tStart;
  96216. if (tCount <= v0.triangleCount) {
  96217. if (tCount) {
  96218. for (var c = 0; c < tCount; c++) {
  96219. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  96220. }
  96221. }
  96222. }
  96223. else {
  96224. v0.triangleStart = tStart;
  96225. }
  96226. v0.triangleCount = tCount;
  96227. break;
  96228. }
  96229. }
  96230. };
  96231. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  96232. }, 0);
  96233. };
  96234. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  96235. if (triangleCount - deletedTriangles <= targetCount)
  96236. loop.breakLoop();
  96237. else {
  96238. iterationFunction(loop.index, function () {
  96239. loop.executeNext();
  96240. });
  96241. }
  96242. }, function () {
  96243. setTimeout(function () {
  96244. //reconstruct this part of the mesh
  96245. _this.reconstructMesh(submeshIndex);
  96246. successCallback();
  96247. }, 0);
  96248. });
  96249. };
  96250. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  96251. var _this = this;
  96252. this.vertices = [];
  96253. this.triangles = [];
  96254. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96255. var indices = this._mesh.getIndices();
  96256. var submesh = this._mesh.subMeshes[submeshIndex];
  96257. var findInVertices = function (positionToSearch) {
  96258. if (optimizeMesh) {
  96259. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  96260. if (_this.vertices[ii].position.equals(positionToSearch)) {
  96261. return _this.vertices[ii];
  96262. }
  96263. }
  96264. }
  96265. return null;
  96266. };
  96267. var vertexReferences = [];
  96268. var vertexInit = function (i) {
  96269. if (!positionData) {
  96270. return;
  96271. }
  96272. var offset = i + submesh.verticesStart;
  96273. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  96274. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  96275. vertex.originalOffsets.push(offset);
  96276. if (vertex.id === _this.vertices.length) {
  96277. _this.vertices.push(vertex);
  96278. }
  96279. vertexReferences.push(vertex.id);
  96280. };
  96281. //var totalVertices = mesh.getTotalVertices();
  96282. var totalVertices = submesh.verticesCount;
  96283. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  96284. var indicesInit = function (i) {
  96285. if (!indices) {
  96286. return;
  96287. }
  96288. var offset = (submesh.indexStart / 3) + i;
  96289. var pos = (offset * 3);
  96290. var i0 = indices[pos + 0];
  96291. var i1 = indices[pos + 1];
  96292. var i2 = indices[pos + 2];
  96293. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  96294. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  96295. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  96296. var triangle = new DecimationTriangle([v0, v1, v2]);
  96297. triangle.originalOffset = pos;
  96298. _this.triangles.push(triangle);
  96299. };
  96300. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  96301. _this.init(callback);
  96302. });
  96303. });
  96304. };
  96305. QuadraticErrorSimplification.prototype.init = function (callback) {
  96306. var _this = this;
  96307. var triangleInit1 = function (i) {
  96308. var t = _this.triangles[i];
  96309. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  96310. for (var j = 0; j < 3; j++) {
  96311. 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))));
  96312. }
  96313. };
  96314. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  96315. var triangleInit2 = function (i) {
  96316. var t = _this.triangles[i];
  96317. for (var j = 0; j < 3; ++j) {
  96318. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  96319. }
  96320. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  96321. };
  96322. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  96323. callback();
  96324. });
  96325. });
  96326. };
  96327. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  96328. var newTriangles = [];
  96329. var i;
  96330. for (i = 0; i < this.vertices.length; ++i) {
  96331. this.vertices[i].triangleCount = 0;
  96332. }
  96333. var t;
  96334. var j;
  96335. for (i = 0; i < this.triangles.length; ++i) {
  96336. if (!this.triangles[i].deleted) {
  96337. t = this.triangles[i];
  96338. for (j = 0; j < 3; ++j) {
  96339. t.vertices[j].triangleCount = 1;
  96340. }
  96341. newTriangles.push(t);
  96342. }
  96343. }
  96344. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  96345. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  96346. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  96347. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  96348. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  96349. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  96350. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  96351. var vertexCount = 0;
  96352. for (i = 0; i < this.vertices.length; ++i) {
  96353. var vertex = this.vertices[i];
  96354. vertex.id = vertexCount;
  96355. if (vertex.triangleCount) {
  96356. vertex.originalOffsets.forEach(function (originalOffset) {
  96357. if (!normalData) {
  96358. return;
  96359. }
  96360. newPositionData.push(vertex.position.x);
  96361. newPositionData.push(vertex.position.y);
  96362. newPositionData.push(vertex.position.z);
  96363. newNormalData.push(normalData[originalOffset * 3]);
  96364. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  96365. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  96366. if (uvs && uvs.length) {
  96367. newUVsData.push(uvs[(originalOffset * 2)]);
  96368. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  96369. }
  96370. else if (colorsData && colorsData.length) {
  96371. newColorsData.push(colorsData[(originalOffset * 4)]);
  96372. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  96373. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  96374. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  96375. }
  96376. ++vertexCount;
  96377. });
  96378. }
  96379. }
  96380. var startingIndex = this._reconstructedMesh.getTotalIndices();
  96381. var startingVertex = this._reconstructedMesh.getTotalVertices();
  96382. var submeshesArray = this._reconstructedMesh.subMeshes;
  96383. this._reconstructedMesh.subMeshes = [];
  96384. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  96385. var originalIndices = this._mesh.getIndices();
  96386. for (i = 0; i < newTriangles.length; ++i) {
  96387. t = newTriangles[i]; //now get the new referencing point for each vertex
  96388. [0, 1, 2].forEach(function (idx) {
  96389. var id = originalIndices[t.originalOffset + idx];
  96390. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  96391. if (offset < 0)
  96392. offset = 0;
  96393. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  96394. });
  96395. }
  96396. //overwriting the old vertex buffers and indices.
  96397. this._reconstructedMesh.setIndices(newIndicesArray);
  96398. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  96399. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  96400. if (newUVsData.length > 0)
  96401. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  96402. if (newColorsData.length > 0)
  96403. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  96404. //create submesh
  96405. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  96406. if (submeshIndex > 0) {
  96407. this._reconstructedMesh.subMeshes = [];
  96408. submeshesArray.forEach(function (submesh) {
  96409. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  96410. });
  96411. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  96412. }
  96413. };
  96414. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  96415. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  96416. this._reconstructedMesh.material = this._mesh.material;
  96417. this._reconstructedMesh.parent = this._mesh.parent;
  96418. this._reconstructedMesh.isVisible = false;
  96419. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  96420. };
  96421. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  96422. for (var i = 0; i < vertex1.triangleCount; ++i) {
  96423. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  96424. if (t.deleted)
  96425. continue;
  96426. var s = this.references[vertex1.triangleStart + i].vertexId;
  96427. var v1 = t.vertices[(s + 1) % 3];
  96428. var v2 = t.vertices[(s + 2) % 3];
  96429. if ((v1 === vertex2 || v2 === vertex2)) {
  96430. deletedArray[i] = true;
  96431. delTr.push(t);
  96432. continue;
  96433. }
  96434. var d1 = v1.position.subtract(point);
  96435. d1 = d1.normalize();
  96436. var d2 = v2.position.subtract(point);
  96437. d2 = d2.normalize();
  96438. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  96439. return true;
  96440. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  96441. deletedArray[i] = false;
  96442. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  96443. return true;
  96444. }
  96445. return false;
  96446. };
  96447. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  96448. var newDeleted = deletedTriangles;
  96449. for (var i = 0; i < vertex.triangleCount; ++i) {
  96450. var ref = this.references[vertex.triangleStart + i];
  96451. var t = this.triangles[ref.triangleId];
  96452. if (t.deleted)
  96453. continue;
  96454. if (deletedArray[i] && t.deletePending) {
  96455. t.deleted = true;
  96456. newDeleted++;
  96457. continue;
  96458. }
  96459. t.vertices[ref.vertexId] = origVertex;
  96460. t.isDirty = true;
  96461. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  96462. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  96463. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  96464. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  96465. this.references.push(ref);
  96466. }
  96467. return newDeleted;
  96468. };
  96469. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  96470. for (var i = 0; i < this.vertices.length; ++i) {
  96471. var vCount = [];
  96472. var vId = [];
  96473. var v = this.vertices[i];
  96474. var j;
  96475. for (j = 0; j < v.triangleCount; ++j) {
  96476. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  96477. for (var ii = 0; ii < 3; ii++) {
  96478. var ofs = 0;
  96479. var vv = triangle.vertices[ii];
  96480. while (ofs < vCount.length) {
  96481. if (vId[ofs] === vv.id)
  96482. break;
  96483. ++ofs;
  96484. }
  96485. if (ofs === vCount.length) {
  96486. vCount.push(1);
  96487. vId.push(vv.id);
  96488. }
  96489. else {
  96490. vCount[ofs]++;
  96491. }
  96492. }
  96493. }
  96494. for (j = 0; j < vCount.length; ++j) {
  96495. if (vCount[j] === 1) {
  96496. this.vertices[vId[j]].isBorder = true;
  96497. }
  96498. else {
  96499. this.vertices[vId[j]].isBorder = false;
  96500. }
  96501. }
  96502. }
  96503. };
  96504. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  96505. if (identifyBorders === void 0) { identifyBorders = false; }
  96506. var i;
  96507. if (!identifyBorders) {
  96508. var newTrianglesVector = [];
  96509. for (i = 0; i < this.triangles.length; ++i) {
  96510. if (!this.triangles[i].deleted) {
  96511. newTrianglesVector.push(this.triangles[i]);
  96512. }
  96513. }
  96514. this.triangles = newTrianglesVector;
  96515. }
  96516. for (i = 0; i < this.vertices.length; ++i) {
  96517. this.vertices[i].triangleCount = 0;
  96518. this.vertices[i].triangleStart = 0;
  96519. }
  96520. var t;
  96521. var j;
  96522. var v;
  96523. for (i = 0; i < this.triangles.length; ++i) {
  96524. t = this.triangles[i];
  96525. for (j = 0; j < 3; ++j) {
  96526. v = t.vertices[j];
  96527. v.triangleCount++;
  96528. }
  96529. }
  96530. var tStart = 0;
  96531. for (i = 0; i < this.vertices.length; ++i) {
  96532. this.vertices[i].triangleStart = tStart;
  96533. tStart += this.vertices[i].triangleCount;
  96534. this.vertices[i].triangleCount = 0;
  96535. }
  96536. var newReferences = new Array(this.triangles.length * 3);
  96537. for (i = 0; i < this.triangles.length; ++i) {
  96538. t = this.triangles[i];
  96539. for (j = 0; j < 3; ++j) {
  96540. v = t.vertices[j];
  96541. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  96542. v.triangleCount++;
  96543. }
  96544. }
  96545. this.references = newReferences;
  96546. if (identifyBorders) {
  96547. this.identifyBorder();
  96548. }
  96549. };
  96550. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  96551. var x = point.x;
  96552. var y = point.y;
  96553. var z = point.z;
  96554. 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
  96555. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  96556. };
  96557. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  96558. var q = vertex1.q.add(vertex2.q);
  96559. var border = vertex1.isBorder && vertex2.isBorder;
  96560. var error = 0;
  96561. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  96562. if (qDet !== 0 && !border) {
  96563. if (!pointResult) {
  96564. pointResult = BABYLON.Vector3.Zero();
  96565. }
  96566. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  96567. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  96568. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  96569. error = this.vertexError(q, pointResult);
  96570. }
  96571. else {
  96572. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  96573. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  96574. var error1 = this.vertexError(q, vertex1.position);
  96575. var error2 = this.vertexError(q, vertex2.position);
  96576. var error3 = this.vertexError(q, p3);
  96577. error = Math.min(error1, error2, error3);
  96578. if (error === error1) {
  96579. if (pointResult) {
  96580. pointResult.copyFrom(vertex1.position);
  96581. }
  96582. }
  96583. else if (error === error2) {
  96584. if (pointResult) {
  96585. pointResult.copyFrom(vertex2.position);
  96586. }
  96587. }
  96588. else {
  96589. if (pointResult) {
  96590. pointResult.copyFrom(p3);
  96591. }
  96592. }
  96593. }
  96594. return error;
  96595. };
  96596. return QuadraticErrorSimplification;
  96597. }());
  96598. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  96599. })(BABYLON || (BABYLON = {}));
  96600. //# sourceMappingURL=babylon.meshSimplification.js.map
  96601. var BABYLON;
  96602. (function (BABYLON) {
  96603. var MeshLODLevel = /** @class */ (function () {
  96604. function MeshLODLevel(distance, mesh) {
  96605. this.distance = distance;
  96606. this.mesh = mesh;
  96607. }
  96608. return MeshLODLevel;
  96609. }());
  96610. BABYLON.MeshLODLevel = MeshLODLevel;
  96611. })(BABYLON || (BABYLON = {}));
  96612. //# sourceMappingURL=babylon.meshLODLevel.js.map
  96613. var BABYLON;
  96614. (function (BABYLON) {
  96615. /**
  96616. * Defines the root class used to create scene optimization to use with SceneOptimizer
  96617. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96618. */
  96619. var SceneOptimization = /** @class */ (function () {
  96620. /**
  96621. * Creates the SceneOptimization object
  96622. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96623. * @param desc defines the description associated with the optimization
  96624. */
  96625. function SceneOptimization(
  96626. /**
  96627. * Defines the priority of this optimization (0 by default which means first in the list)
  96628. */
  96629. priority) {
  96630. if (priority === void 0) { priority = 0; }
  96631. this.priority = priority;
  96632. }
  96633. /**
  96634. * Gets a string describing the action executed by the current optimization
  96635. * @returns description string
  96636. */
  96637. SceneOptimization.prototype.getDescription = function () {
  96638. return "";
  96639. };
  96640. /**
  96641. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96642. * @param scene defines the current scene where to apply this optimization
  96643. * @param optimizer defines the current optimizer
  96644. * @returns true if everything that can be done was applied
  96645. */
  96646. SceneOptimization.prototype.apply = function (scene, optimizer) {
  96647. return true;
  96648. };
  96649. ;
  96650. return SceneOptimization;
  96651. }());
  96652. BABYLON.SceneOptimization = SceneOptimization;
  96653. /**
  96654. * Defines an optimization used to reduce the size of render target textures
  96655. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96656. */
  96657. var TextureOptimization = /** @class */ (function (_super) {
  96658. __extends(TextureOptimization, _super);
  96659. /**
  96660. * Creates the TextureOptimization object
  96661. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96662. * @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
  96663. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  96664. */
  96665. function TextureOptimization(
  96666. /**
  96667. * Defines the priority of this optimization (0 by default which means first in the list)
  96668. */
  96669. priority,
  96670. /**
  96671. * 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
  96672. */
  96673. maximumSize,
  96674. /**
  96675. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  96676. */
  96677. step) {
  96678. if (priority === void 0) { priority = 0; }
  96679. if (maximumSize === void 0) { maximumSize = 1024; }
  96680. if (step === void 0) { step = 0.5; }
  96681. var _this = _super.call(this, priority) || this;
  96682. _this.priority = priority;
  96683. _this.maximumSize = maximumSize;
  96684. _this.step = step;
  96685. return _this;
  96686. }
  96687. /**
  96688. * Gets a string describing the action executed by the current optimization
  96689. * @returns description string
  96690. */
  96691. TextureOptimization.prototype.getDescription = function () {
  96692. return "Reducing render target texture size to " + this.maximumSize;
  96693. };
  96694. /**
  96695. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96696. * @param scene defines the current scene where to apply this optimization
  96697. * @param optimizer defines the current optimizer
  96698. * @returns true if everything that can be done was applied
  96699. */
  96700. TextureOptimization.prototype.apply = function (scene, optimizer) {
  96701. var allDone = true;
  96702. for (var index = 0; index < scene.textures.length; index++) {
  96703. var texture = scene.textures[index];
  96704. if (!texture.canRescale || texture.getContext) {
  96705. continue;
  96706. }
  96707. var currentSize = texture.getSize();
  96708. var maxDimension = Math.max(currentSize.width, currentSize.height);
  96709. if (maxDimension > this.maximumSize) {
  96710. texture.scale(this.step);
  96711. allDone = false;
  96712. }
  96713. }
  96714. return allDone;
  96715. };
  96716. return TextureOptimization;
  96717. }(SceneOptimization));
  96718. BABYLON.TextureOptimization = TextureOptimization;
  96719. /**
  96720. * Defines an optimization used to increase or decrease the rendering resolution
  96721. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96722. */
  96723. var HardwareScalingOptimization = /** @class */ (function (_super) {
  96724. __extends(HardwareScalingOptimization, _super);
  96725. /**
  96726. * Creates the HardwareScalingOptimization object
  96727. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96728. * @param maximumScale defines the maximum scale to use (2 by default)
  96729. * @param step defines the step to use between two passes (0.5 by default)
  96730. */
  96731. function HardwareScalingOptimization(
  96732. /**
  96733. * Defines the priority of this optimization (0 by default which means first in the list)
  96734. */
  96735. priority,
  96736. /**
  96737. * Defines the maximum scale to use (2 by default)
  96738. */
  96739. maximumScale,
  96740. /**
  96741. * Defines the step to use between two passes (0.5 by default)
  96742. */
  96743. step) {
  96744. if (priority === void 0) { priority = 0; }
  96745. if (maximumScale === void 0) { maximumScale = 2; }
  96746. if (step === void 0) { step = 0.25; }
  96747. var _this = _super.call(this, priority) || this;
  96748. _this.priority = priority;
  96749. _this.maximumScale = maximumScale;
  96750. _this.step = step;
  96751. _this._currentScale = -1;
  96752. _this._directionOffset = 1;
  96753. return _this;
  96754. }
  96755. /**
  96756. * Gets a string describing the action executed by the current optimization
  96757. * @return description string
  96758. */
  96759. HardwareScalingOptimization.prototype.getDescription = function () {
  96760. return "Setting hardware scaling level to " + this._currentScale;
  96761. };
  96762. /**
  96763. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96764. * @param scene defines the current scene where to apply this optimization
  96765. * @param optimizer defines the current optimizer
  96766. * @returns true if everything that can be done was applied
  96767. */
  96768. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  96769. if (this._currentScale === -1) {
  96770. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  96771. if (this._currentScale > this.maximumScale) {
  96772. this._directionOffset = -1;
  96773. }
  96774. }
  96775. this._currentScale += this._directionOffset * this.step;
  96776. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  96777. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  96778. };
  96779. ;
  96780. return HardwareScalingOptimization;
  96781. }(SceneOptimization));
  96782. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  96783. /**
  96784. * Defines an optimization used to remove shadows
  96785. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96786. */
  96787. var ShadowsOptimization = /** @class */ (function (_super) {
  96788. __extends(ShadowsOptimization, _super);
  96789. function ShadowsOptimization() {
  96790. return _super !== null && _super.apply(this, arguments) || this;
  96791. }
  96792. /**
  96793. * Gets a string describing the action executed by the current optimization
  96794. * @return description string
  96795. */
  96796. ShadowsOptimization.prototype.getDescription = function () {
  96797. return "Turning shadows on/off";
  96798. };
  96799. /**
  96800. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96801. * @param scene defines the current scene where to apply this optimization
  96802. * @param optimizer defines the current optimizer
  96803. * @returns true if everything that can be done was applied
  96804. */
  96805. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  96806. scene.shadowsEnabled = optimizer.isInImprovementMode;
  96807. return true;
  96808. };
  96809. ;
  96810. return ShadowsOptimization;
  96811. }(SceneOptimization));
  96812. BABYLON.ShadowsOptimization = ShadowsOptimization;
  96813. /**
  96814. * Defines an optimization used to turn post-processes off
  96815. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96816. */
  96817. var PostProcessesOptimization = /** @class */ (function (_super) {
  96818. __extends(PostProcessesOptimization, _super);
  96819. function PostProcessesOptimization() {
  96820. return _super !== null && _super.apply(this, arguments) || this;
  96821. }
  96822. /**
  96823. * Gets a string describing the action executed by the current optimization
  96824. * @return description string
  96825. */
  96826. PostProcessesOptimization.prototype.getDescription = function () {
  96827. return "Turning post-processes on/off";
  96828. };
  96829. /**
  96830. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96831. * @param scene defines the current scene where to apply this optimization
  96832. * @param optimizer defines the current optimizer
  96833. * @returns true if everything that can be done was applied
  96834. */
  96835. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  96836. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  96837. return true;
  96838. };
  96839. ;
  96840. return PostProcessesOptimization;
  96841. }(SceneOptimization));
  96842. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  96843. /**
  96844. * Defines an optimization used to turn lens flares off
  96845. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96846. */
  96847. var LensFlaresOptimization = /** @class */ (function (_super) {
  96848. __extends(LensFlaresOptimization, _super);
  96849. function LensFlaresOptimization() {
  96850. return _super !== null && _super.apply(this, arguments) || this;
  96851. }
  96852. /**
  96853. * Gets a string describing the action executed by the current optimization
  96854. * @return description string
  96855. */
  96856. LensFlaresOptimization.prototype.getDescription = function () {
  96857. return "Turning lens flares on/off";
  96858. };
  96859. /**
  96860. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96861. * @param scene defines the current scene where to apply this optimization
  96862. * @param optimizer defines the current optimizer
  96863. * @returns true if everything that can be done was applied
  96864. */
  96865. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  96866. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  96867. return true;
  96868. };
  96869. ;
  96870. return LensFlaresOptimization;
  96871. }(SceneOptimization));
  96872. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  96873. /**
  96874. * Defines an optimization based on user defined callback.
  96875. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96876. */
  96877. var CustomOptimization = /** @class */ (function (_super) {
  96878. __extends(CustomOptimization, _super);
  96879. function CustomOptimization() {
  96880. return _super !== null && _super.apply(this, arguments) || this;
  96881. }
  96882. /**
  96883. * Gets a string describing the action executed by the current optimization
  96884. * @returns description string
  96885. */
  96886. CustomOptimization.prototype.getDescription = function () {
  96887. if (this.onGetDescription) {
  96888. return this.onGetDescription();
  96889. }
  96890. return "Running user defined callback";
  96891. };
  96892. /**
  96893. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96894. * @param scene defines the current scene where to apply this optimization
  96895. * @param optimizer defines the current optimizer
  96896. * @returns true if everything that can be done was applied
  96897. */
  96898. CustomOptimization.prototype.apply = function (scene, optimizer) {
  96899. if (this.onApply) {
  96900. return this.onApply(scene, optimizer);
  96901. }
  96902. return true;
  96903. };
  96904. ;
  96905. return CustomOptimization;
  96906. }(SceneOptimization));
  96907. BABYLON.CustomOptimization = CustomOptimization;
  96908. /**
  96909. * Defines an optimization used to turn particles off
  96910. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96911. */
  96912. var ParticlesOptimization = /** @class */ (function (_super) {
  96913. __extends(ParticlesOptimization, _super);
  96914. function ParticlesOptimization() {
  96915. return _super !== null && _super.apply(this, arguments) || this;
  96916. }
  96917. /**
  96918. * Gets a string describing the action executed by the current optimization
  96919. * @return description string
  96920. */
  96921. ParticlesOptimization.prototype.getDescription = function () {
  96922. return "Turning particles on/off";
  96923. };
  96924. /**
  96925. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96926. * @param scene defines the current scene where to apply this optimization
  96927. * @param optimizer defines the current optimizer
  96928. * @returns true if everything that can be done was applied
  96929. */
  96930. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  96931. scene.particlesEnabled = optimizer.isInImprovementMode;
  96932. return true;
  96933. };
  96934. ;
  96935. return ParticlesOptimization;
  96936. }(SceneOptimization));
  96937. BABYLON.ParticlesOptimization = ParticlesOptimization;
  96938. /**
  96939. * Defines an optimization used to turn render targets off
  96940. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96941. */
  96942. var RenderTargetsOptimization = /** @class */ (function (_super) {
  96943. __extends(RenderTargetsOptimization, _super);
  96944. function RenderTargetsOptimization() {
  96945. return _super !== null && _super.apply(this, arguments) || this;
  96946. }
  96947. /**
  96948. * Gets a string describing the action executed by the current optimization
  96949. * @return description string
  96950. */
  96951. RenderTargetsOptimization.prototype.getDescription = function () {
  96952. return "Turning render targets off";
  96953. };
  96954. /**
  96955. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96956. * @param scene defines the current scene where to apply this optimization
  96957. * @param optimizer defines the current optimizer
  96958. * @returns true if everything that can be done was applied
  96959. */
  96960. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  96961. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  96962. return true;
  96963. };
  96964. ;
  96965. return RenderTargetsOptimization;
  96966. }(SceneOptimization));
  96967. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  96968. /**
  96969. * Defines an optimization used to merge meshes with compatible materials
  96970. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96971. */
  96972. var MergeMeshesOptimization = /** @class */ (function (_super) {
  96973. __extends(MergeMeshesOptimization, _super);
  96974. function MergeMeshesOptimization() {
  96975. var _this = _super !== null && _super.apply(this, arguments) || this;
  96976. _this._canBeMerged = function (abstractMesh) {
  96977. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  96978. return false;
  96979. }
  96980. var mesh = abstractMesh;
  96981. if (mesh.isDisposed()) {
  96982. return false;
  96983. }
  96984. if (!mesh.isVisible || !mesh.isEnabled()) {
  96985. return false;
  96986. }
  96987. if (mesh.instances.length > 0) {
  96988. return false;
  96989. }
  96990. if (mesh.skeleton || mesh.hasLODLevels) {
  96991. return false;
  96992. }
  96993. return true;
  96994. };
  96995. return _this;
  96996. }
  96997. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  96998. /**
  96999. * Gets or sets a boolean which defines if optimization octree has to be updated
  97000. */
  97001. get: function () {
  97002. return MergeMeshesOptimization._UpdateSelectionTree;
  97003. },
  97004. /**
  97005. * Gets or sets a boolean which defines if optimization octree has to be updated
  97006. */
  97007. set: function (value) {
  97008. MergeMeshesOptimization._UpdateSelectionTree = value;
  97009. },
  97010. enumerable: true,
  97011. configurable: true
  97012. });
  97013. /**
  97014. * Gets a string describing the action executed by the current optimization
  97015. * @return description string
  97016. */
  97017. MergeMeshesOptimization.prototype.getDescription = function () {
  97018. return "Merging similar meshes together";
  97019. };
  97020. /**
  97021. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97022. * @param scene defines the current scene where to apply this optimization
  97023. * @param optimizer defines the current optimizer
  97024. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  97025. * @returns true if everything that can be done was applied
  97026. */
  97027. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  97028. var globalPool = scene.meshes.slice(0);
  97029. var globalLength = globalPool.length;
  97030. for (var index = 0; index < globalLength; index++) {
  97031. var currentPool = new Array();
  97032. var current = globalPool[index];
  97033. // Checks
  97034. if (!this._canBeMerged(current)) {
  97035. continue;
  97036. }
  97037. currentPool.push(current);
  97038. // Find compatible meshes
  97039. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  97040. var otherMesh = globalPool[subIndex];
  97041. if (!this._canBeMerged(otherMesh)) {
  97042. continue;
  97043. }
  97044. if (otherMesh.material !== current.material) {
  97045. continue;
  97046. }
  97047. if (otherMesh.checkCollisions !== current.checkCollisions) {
  97048. continue;
  97049. }
  97050. currentPool.push(otherMesh);
  97051. globalLength--;
  97052. globalPool.splice(subIndex, 1);
  97053. subIndex--;
  97054. }
  97055. if (currentPool.length < 2) {
  97056. continue;
  97057. }
  97058. // Merge meshes
  97059. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  97060. }
  97061. if (updateSelectionTree != undefined) {
  97062. if (updateSelectionTree) {
  97063. scene.createOrUpdateSelectionOctree();
  97064. }
  97065. }
  97066. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  97067. scene.createOrUpdateSelectionOctree();
  97068. }
  97069. return true;
  97070. };
  97071. ;
  97072. MergeMeshesOptimization._UpdateSelectionTree = false;
  97073. return MergeMeshesOptimization;
  97074. }(SceneOptimization));
  97075. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  97076. /**
  97077. * Defines a list of options used by SceneOptimizer
  97078. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97079. */
  97080. var SceneOptimizerOptions = /** @class */ (function () {
  97081. /**
  97082. * Creates a new list of options used by SceneOptimizer
  97083. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  97084. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  97085. */
  97086. function SceneOptimizerOptions(
  97087. /**
  97088. * Defines the target frame rate to reach (60 by default)
  97089. */
  97090. targetFrameRate,
  97091. /**
  97092. * Defines the interval between two checkes (2000ms by default)
  97093. */
  97094. trackerDuration) {
  97095. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  97096. if (trackerDuration === void 0) { trackerDuration = 2000; }
  97097. this.targetFrameRate = targetFrameRate;
  97098. this.trackerDuration = trackerDuration;
  97099. /**
  97100. * Gets the list of optimizations to apply
  97101. */
  97102. this.optimizations = new Array();
  97103. }
  97104. /**
  97105. * Add a new optimization
  97106. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  97107. * @returns the current SceneOptimizerOptions
  97108. */
  97109. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  97110. this.optimizations.push(optimization);
  97111. return this;
  97112. };
  97113. /**
  97114. * Add a new custom optimization
  97115. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  97116. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  97117. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  97118. * @returns the current SceneOptimizerOptions
  97119. */
  97120. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  97121. if (priority === void 0) { priority = 0; }
  97122. var optimization = new CustomOptimization(priority);
  97123. optimization.onApply = onApply;
  97124. optimization.onGetDescription = onGetDescription;
  97125. this.optimizations.push(optimization);
  97126. return this;
  97127. };
  97128. /**
  97129. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  97130. * @param targetFrameRate defines the target frame rate (60 by default)
  97131. * @returns a SceneOptimizerOptions object
  97132. */
  97133. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  97134. var result = new SceneOptimizerOptions(targetFrameRate);
  97135. var priority = 0;
  97136. result.addOptimization(new MergeMeshesOptimization(priority));
  97137. result.addOptimization(new ShadowsOptimization(priority));
  97138. result.addOptimization(new LensFlaresOptimization(priority));
  97139. // Next priority
  97140. priority++;
  97141. result.addOptimization(new PostProcessesOptimization(priority));
  97142. result.addOptimization(new ParticlesOptimization(priority));
  97143. // Next priority
  97144. priority++;
  97145. result.addOptimization(new TextureOptimization(priority, 1024));
  97146. return result;
  97147. };
  97148. /**
  97149. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  97150. * @param targetFrameRate defines the target frame rate (60 by default)
  97151. * @returns a SceneOptimizerOptions object
  97152. */
  97153. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  97154. var result = new SceneOptimizerOptions(targetFrameRate);
  97155. var priority = 0;
  97156. result.addOptimization(new MergeMeshesOptimization(priority));
  97157. result.addOptimization(new ShadowsOptimization(priority));
  97158. result.addOptimization(new LensFlaresOptimization(priority));
  97159. // Next priority
  97160. priority++;
  97161. result.addOptimization(new PostProcessesOptimization(priority));
  97162. result.addOptimization(new ParticlesOptimization(priority));
  97163. // Next priority
  97164. priority++;
  97165. result.addOptimization(new TextureOptimization(priority, 512));
  97166. // Next priority
  97167. priority++;
  97168. result.addOptimization(new RenderTargetsOptimization(priority));
  97169. // Next priority
  97170. priority++;
  97171. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  97172. return result;
  97173. };
  97174. /**
  97175. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  97176. * @param targetFrameRate defines the target frame rate (60 by default)
  97177. * @returns a SceneOptimizerOptions object
  97178. */
  97179. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  97180. var result = new SceneOptimizerOptions(targetFrameRate);
  97181. var priority = 0;
  97182. result.addOptimization(new MergeMeshesOptimization(priority));
  97183. result.addOptimization(new ShadowsOptimization(priority));
  97184. result.addOptimization(new LensFlaresOptimization(priority));
  97185. // Next priority
  97186. priority++;
  97187. result.addOptimization(new PostProcessesOptimization(priority));
  97188. result.addOptimization(new ParticlesOptimization(priority));
  97189. // Next priority
  97190. priority++;
  97191. result.addOptimization(new TextureOptimization(priority, 256));
  97192. // Next priority
  97193. priority++;
  97194. result.addOptimization(new RenderTargetsOptimization(priority));
  97195. // Next priority
  97196. priority++;
  97197. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  97198. return result;
  97199. };
  97200. return SceneOptimizerOptions;
  97201. }());
  97202. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  97203. /**
  97204. * Class used to run optimizations in order to reach a target frame rate
  97205. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97206. */
  97207. var SceneOptimizer = /** @class */ (function () {
  97208. /**
  97209. * Creates a new SceneOptimizer
  97210. * @param scene defines the scene to work on
  97211. * @param options defines the options to use with the SceneOptimizer
  97212. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  97213. * @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)
  97214. */
  97215. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  97216. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  97217. if (improvementMode === void 0) { improvementMode = false; }
  97218. var _this = this;
  97219. this._isRunning = false;
  97220. this._currentPriorityLevel = 0;
  97221. this._targetFrameRate = 60;
  97222. this._trackerDuration = 2000;
  97223. this._currentFrameRate = 0;
  97224. this._improvementMode = false;
  97225. /**
  97226. * Defines an observable called when the optimizer reaches the target frame rate
  97227. */
  97228. this.onSuccessObservable = new BABYLON.Observable();
  97229. /**
  97230. * Defines an observable called when the optimizer enables an optimization
  97231. */
  97232. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  97233. /**
  97234. * Defines an observable called when the optimizer is not able to reach the target frame rate
  97235. */
  97236. this.onFailureObservable = new BABYLON.Observable();
  97237. if (!options) {
  97238. this._options = new SceneOptimizerOptions();
  97239. }
  97240. else {
  97241. this._options = options;
  97242. }
  97243. if (this._options.targetFrameRate) {
  97244. this._targetFrameRate = this._options.targetFrameRate;
  97245. }
  97246. if (this._options.trackerDuration) {
  97247. this._trackerDuration = this._options.trackerDuration;
  97248. }
  97249. if (autoGeneratePriorities) {
  97250. var priority = 0;
  97251. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  97252. var optim = _a[_i];
  97253. optim.priority = priority++;
  97254. }
  97255. }
  97256. this._improvementMode = improvementMode;
  97257. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97258. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  97259. _this._sceneDisposeObserver = null;
  97260. _this.dispose();
  97261. });
  97262. }
  97263. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  97264. /**
  97265. * Gets a boolean indicating if the optimizer is in improvement mode
  97266. */
  97267. get: function () {
  97268. return this._improvementMode;
  97269. },
  97270. enumerable: true,
  97271. configurable: true
  97272. });
  97273. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  97274. /**
  97275. * Gets the current priority level (0 at start)
  97276. */
  97277. get: function () {
  97278. return this._currentPriorityLevel;
  97279. },
  97280. enumerable: true,
  97281. configurable: true
  97282. });
  97283. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  97284. /**
  97285. * Gets the current frame rate checked by the SceneOptimizer
  97286. */
  97287. get: function () {
  97288. return this._currentFrameRate;
  97289. },
  97290. enumerable: true,
  97291. configurable: true
  97292. });
  97293. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  97294. /**
  97295. * Gets or sets the current target frame rate (60 by default)
  97296. */
  97297. get: function () {
  97298. return this._targetFrameRate;
  97299. },
  97300. /**
  97301. * Gets or sets the current target frame rate (60 by default)
  97302. */
  97303. set: function (value) {
  97304. this._targetFrameRate = value;
  97305. },
  97306. enumerable: true,
  97307. configurable: true
  97308. });
  97309. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  97310. /**
  97311. * Gets or sets the current interval between two checks (every 2000ms by default)
  97312. */
  97313. get: function () {
  97314. return this._trackerDuration;
  97315. },
  97316. /**
  97317. * Gets or sets the current interval between two checks (every 2000ms by default)
  97318. */
  97319. set: function (value) {
  97320. this._trackerDuration = value;
  97321. },
  97322. enumerable: true,
  97323. configurable: true
  97324. });
  97325. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  97326. /**
  97327. * Gets the list of active optimizations
  97328. */
  97329. get: function () {
  97330. return this._options.optimizations;
  97331. },
  97332. enumerable: true,
  97333. configurable: true
  97334. });
  97335. /**
  97336. * Stops the current optimizer
  97337. */
  97338. SceneOptimizer.prototype.stop = function () {
  97339. this._isRunning = false;
  97340. };
  97341. /**
  97342. * Reset the optimizer to initial step (current priority level = 0)
  97343. */
  97344. SceneOptimizer.prototype.reset = function () {
  97345. this._currentPriorityLevel = 0;
  97346. };
  97347. /**
  97348. * Start the optimizer. By default it will try to reach a specific framerate
  97349. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  97350. */
  97351. SceneOptimizer.prototype.start = function () {
  97352. var _this = this;
  97353. if (this._isRunning) {
  97354. return;
  97355. }
  97356. this._isRunning = true;
  97357. // Let's wait for the scene to be ready before running our check
  97358. this._scene.executeWhenReady(function () {
  97359. setTimeout(function () {
  97360. _this._checkCurrentState();
  97361. }, _this._trackerDuration);
  97362. });
  97363. };
  97364. SceneOptimizer.prototype._checkCurrentState = function () {
  97365. var _this = this;
  97366. if (!this._isRunning) {
  97367. return;
  97368. }
  97369. var scene = this._scene;
  97370. var options = this._options;
  97371. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  97372. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  97373. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  97374. this._isRunning = false;
  97375. this.onSuccessObservable.notifyObservers(this);
  97376. return;
  97377. }
  97378. // Apply current level of optimizations
  97379. var allDone = true;
  97380. var noOptimizationApplied = true;
  97381. for (var index = 0; index < options.optimizations.length; index++) {
  97382. var optimization = options.optimizations[index];
  97383. if (optimization.priority === this._currentPriorityLevel) {
  97384. noOptimizationApplied = false;
  97385. allDone = allDone && optimization.apply(scene, this);
  97386. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  97387. }
  97388. }
  97389. // If no optimization was applied, this is a failure :(
  97390. if (noOptimizationApplied) {
  97391. this._isRunning = false;
  97392. this.onFailureObservable.notifyObservers(this);
  97393. return;
  97394. }
  97395. // If all optimizations were done, move to next level
  97396. if (allDone) {
  97397. this._currentPriorityLevel++;
  97398. }
  97399. // Let's the system running for a specific amount of time before checking FPS
  97400. scene.executeWhenReady(function () {
  97401. setTimeout(function () {
  97402. _this._checkCurrentState();
  97403. }, _this._trackerDuration);
  97404. });
  97405. };
  97406. /**
  97407. * Release all resources
  97408. */
  97409. SceneOptimizer.prototype.dispose = function () {
  97410. this.stop();
  97411. this.onSuccessObservable.clear();
  97412. this.onFailureObservable.clear();
  97413. this.onNewOptimizationAppliedObservable.clear();
  97414. if (this._sceneDisposeObserver) {
  97415. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  97416. }
  97417. };
  97418. /**
  97419. * Helper function to create a SceneOptimizer with one single line of code
  97420. * @param scene defines the scene to work on
  97421. * @param options defines the options to use with the SceneOptimizer
  97422. * @param onSuccess defines a callback to call on success
  97423. * @param onFailure defines a callback to call on failure
  97424. * @returns the new SceneOptimizer object
  97425. */
  97426. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  97427. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  97428. if (onSuccess) {
  97429. optimizer.onSuccessObservable.add(function () {
  97430. onSuccess();
  97431. });
  97432. }
  97433. if (onFailure) {
  97434. optimizer.onFailureObservable.add(function () {
  97435. onFailure();
  97436. });
  97437. }
  97438. optimizer.start();
  97439. return optimizer;
  97440. };
  97441. return SceneOptimizer;
  97442. }());
  97443. BABYLON.SceneOptimizer = SceneOptimizer;
  97444. })(BABYLON || (BABYLON = {}));
  97445. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  97446. var BABYLON;
  97447. (function (BABYLON) {
  97448. var OutlineRenderer = /** @class */ (function () {
  97449. function OutlineRenderer(scene) {
  97450. this.zOffset = 1;
  97451. this._scene = scene;
  97452. }
  97453. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  97454. var _this = this;
  97455. if (useOverlay === void 0) { useOverlay = false; }
  97456. var scene = this._scene;
  97457. var engine = this._scene.getEngine();
  97458. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  97459. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  97460. return;
  97461. }
  97462. var mesh = subMesh.getRenderingMesh();
  97463. var material = subMesh.getMaterial();
  97464. if (!material || !scene.activeCamera) {
  97465. return;
  97466. }
  97467. engine.enableEffect(this._effect);
  97468. // Logarithmic depth
  97469. if (material.useLogarithmicDepth) {
  97470. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  97471. }
  97472. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  97473. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  97474. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  97475. // Bones
  97476. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  97477. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  97478. }
  97479. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  97480. // Alpha test
  97481. if (material && material.needAlphaTesting()) {
  97482. var alphaTexture = material.getAlphaTestTexture();
  97483. if (alphaTexture) {
  97484. this._effect.setTexture("diffuseSampler", alphaTexture);
  97485. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  97486. }
  97487. }
  97488. engine.setZOffset(-this.zOffset);
  97489. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  97490. engine.setZOffset(0);
  97491. };
  97492. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  97493. var defines = [];
  97494. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  97495. var mesh = subMesh.getMesh();
  97496. var material = subMesh.getMaterial();
  97497. if (material) {
  97498. // Alpha test
  97499. if (material.needAlphaTesting()) {
  97500. defines.push("#define ALPHATEST");
  97501. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97502. attribs.push(BABYLON.VertexBuffer.UVKind);
  97503. defines.push("#define UV1");
  97504. }
  97505. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  97506. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97507. defines.push("#define UV2");
  97508. }
  97509. }
  97510. //Logarithmic depth
  97511. if (material.useLogarithmicDepth) {
  97512. defines.push("#define LOGARITHMICDEPTH");
  97513. }
  97514. }
  97515. // Bones
  97516. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  97517. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  97518. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  97519. if (mesh.numBoneInfluencers > 4) {
  97520. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  97521. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  97522. }
  97523. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  97524. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  97525. }
  97526. else {
  97527. defines.push("#define NUM_BONE_INFLUENCERS 0");
  97528. }
  97529. // Instances
  97530. if (useInstances) {
  97531. defines.push("#define INSTANCES");
  97532. attribs.push("world0");
  97533. attribs.push("world1");
  97534. attribs.push("world2");
  97535. attribs.push("world3");
  97536. }
  97537. // Get correct effect
  97538. var join = defines.join("\n");
  97539. if (this._cachedDefines !== join) {
  97540. this._cachedDefines = join;
  97541. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  97542. }
  97543. return this._effect.isReady();
  97544. };
  97545. return OutlineRenderer;
  97546. }());
  97547. BABYLON.OutlineRenderer = OutlineRenderer;
  97548. })(BABYLON || (BABYLON = {}));
  97549. //# sourceMappingURL=babylon.outlineRenderer.js.map
  97550. var BABYLON;
  97551. (function (BABYLON) {
  97552. var FaceAdjacencies = /** @class */ (function () {
  97553. function FaceAdjacencies() {
  97554. this.edges = new Array();
  97555. this.edgesConnectedCount = 0;
  97556. }
  97557. return FaceAdjacencies;
  97558. }());
  97559. var EdgesRenderer = /** @class */ (function () {
  97560. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  97561. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  97562. if (epsilon === void 0) { epsilon = 0.95; }
  97563. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  97564. this.edgesWidthScalerForOrthographic = 1000.0;
  97565. this.edgesWidthScalerForPerspective = 50.0;
  97566. this._linesPositions = new Array();
  97567. this._linesNormals = new Array();
  97568. this._linesIndices = new Array();
  97569. this._buffers = {};
  97570. this._checkVerticesInsteadOfIndices = false;
  97571. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  97572. this.isEnabled = true;
  97573. this._source = source;
  97574. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  97575. this._epsilon = epsilon;
  97576. this._prepareRessources();
  97577. this._generateEdgesLines();
  97578. }
  97579. EdgesRenderer.prototype._prepareRessources = function () {
  97580. if (this._lineShader) {
  97581. return;
  97582. }
  97583. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  97584. attributes: ["position", "normal"],
  97585. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  97586. });
  97587. this._lineShader.disableDepthWrite = true;
  97588. this._lineShader.backFaceCulling = false;
  97589. };
  97590. EdgesRenderer.prototype._rebuild = function () {
  97591. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  97592. if (buffer) {
  97593. buffer._rebuild();
  97594. }
  97595. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  97596. if (buffer) {
  97597. buffer._rebuild();
  97598. }
  97599. var scene = this._source.getScene();
  97600. var engine = scene.getEngine();
  97601. this._ib = engine.createIndexBuffer(this._linesIndices);
  97602. };
  97603. EdgesRenderer.prototype.dispose = function () {
  97604. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  97605. if (buffer) {
  97606. buffer.dispose();
  97607. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  97608. }
  97609. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  97610. if (buffer) {
  97611. buffer.dispose();
  97612. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  97613. }
  97614. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  97615. this._lineShader.dispose();
  97616. };
  97617. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  97618. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  97619. return 0;
  97620. }
  97621. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  97622. return 1;
  97623. }
  97624. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  97625. return 2;
  97626. }
  97627. return -1;
  97628. };
  97629. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  97630. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  97631. return 0;
  97632. }
  97633. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  97634. return 1;
  97635. }
  97636. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  97637. return 2;
  97638. }
  97639. return -1;
  97640. };
  97641. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  97642. var needToCreateLine;
  97643. if (edge === undefined) {
  97644. needToCreateLine = true;
  97645. }
  97646. else {
  97647. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  97648. needToCreateLine = dotProduct < this._epsilon;
  97649. }
  97650. if (needToCreateLine) {
  97651. var offset = this._linesPositions.length / 3;
  97652. var normal = p0.subtract(p1);
  97653. normal.normalize();
  97654. // Positions
  97655. this._linesPositions.push(p0.x);
  97656. this._linesPositions.push(p0.y);
  97657. this._linesPositions.push(p0.z);
  97658. this._linesPositions.push(p0.x);
  97659. this._linesPositions.push(p0.y);
  97660. this._linesPositions.push(p0.z);
  97661. this._linesPositions.push(p1.x);
  97662. this._linesPositions.push(p1.y);
  97663. this._linesPositions.push(p1.z);
  97664. this._linesPositions.push(p1.x);
  97665. this._linesPositions.push(p1.y);
  97666. this._linesPositions.push(p1.z);
  97667. // Normals
  97668. this._linesNormals.push(p1.x);
  97669. this._linesNormals.push(p1.y);
  97670. this._linesNormals.push(p1.z);
  97671. this._linesNormals.push(-1);
  97672. this._linesNormals.push(p1.x);
  97673. this._linesNormals.push(p1.y);
  97674. this._linesNormals.push(p1.z);
  97675. this._linesNormals.push(1);
  97676. this._linesNormals.push(p0.x);
  97677. this._linesNormals.push(p0.y);
  97678. this._linesNormals.push(p0.z);
  97679. this._linesNormals.push(-1);
  97680. this._linesNormals.push(p0.x);
  97681. this._linesNormals.push(p0.y);
  97682. this._linesNormals.push(p0.z);
  97683. this._linesNormals.push(1);
  97684. // Indices
  97685. this._linesIndices.push(offset);
  97686. this._linesIndices.push(offset + 1);
  97687. this._linesIndices.push(offset + 2);
  97688. this._linesIndices.push(offset);
  97689. this._linesIndices.push(offset + 2);
  97690. this._linesIndices.push(offset + 3);
  97691. }
  97692. };
  97693. EdgesRenderer.prototype._generateEdgesLines = function () {
  97694. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  97695. var indices = this._source.getIndices();
  97696. if (!indices || !positions) {
  97697. return;
  97698. }
  97699. // First let's find adjacencies
  97700. var adjacencies = new Array();
  97701. var faceNormals = new Array();
  97702. var index;
  97703. var faceAdjacencies;
  97704. // Prepare faces
  97705. for (index = 0; index < indices.length; index += 3) {
  97706. faceAdjacencies = new FaceAdjacencies();
  97707. var p0Index = indices[index];
  97708. var p1Index = indices[index + 1];
  97709. var p2Index = indices[index + 2];
  97710. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  97711. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  97712. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  97713. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  97714. faceNormal.normalize();
  97715. faceNormals.push(faceNormal);
  97716. adjacencies.push(faceAdjacencies);
  97717. }
  97718. // Scan
  97719. for (index = 0; index < adjacencies.length; index++) {
  97720. faceAdjacencies = adjacencies[index];
  97721. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  97722. var otherFaceAdjacencies = adjacencies[otherIndex];
  97723. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  97724. break;
  97725. }
  97726. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  97727. continue;
  97728. }
  97729. var otherP0 = indices[otherIndex * 3];
  97730. var otherP1 = indices[otherIndex * 3 + 1];
  97731. var otherP2 = indices[otherIndex * 3 + 2];
  97732. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  97733. var otherEdgeIndex = 0;
  97734. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  97735. continue;
  97736. }
  97737. switch (edgeIndex) {
  97738. case 0:
  97739. if (this._checkVerticesInsteadOfIndices) {
  97740. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97741. }
  97742. else {
  97743. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  97744. }
  97745. break;
  97746. case 1:
  97747. if (this._checkVerticesInsteadOfIndices) {
  97748. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97749. }
  97750. else {
  97751. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  97752. }
  97753. break;
  97754. case 2:
  97755. if (this._checkVerticesInsteadOfIndices) {
  97756. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97757. }
  97758. else {
  97759. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  97760. }
  97761. break;
  97762. }
  97763. if (otherEdgeIndex === -1) {
  97764. continue;
  97765. }
  97766. faceAdjacencies.edges[edgeIndex] = otherIndex;
  97767. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  97768. faceAdjacencies.edgesConnectedCount++;
  97769. otherFaceAdjacencies.edgesConnectedCount++;
  97770. if (faceAdjacencies.edgesConnectedCount === 3) {
  97771. break;
  97772. }
  97773. }
  97774. }
  97775. }
  97776. // Create lines
  97777. for (index = 0; index < adjacencies.length; index++) {
  97778. // 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
  97779. var current = adjacencies[index];
  97780. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  97781. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  97782. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  97783. }
  97784. // Merge into a single mesh
  97785. var engine = this._source.getScene().getEngine();
  97786. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  97787. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  97788. this._ib = engine.createIndexBuffer(this._linesIndices);
  97789. this._indicesCount = this._linesIndices.length;
  97790. };
  97791. EdgesRenderer.prototype.render = function () {
  97792. var scene = this._source.getScene();
  97793. if (!this._lineShader.isReady() || !scene.activeCamera) {
  97794. return;
  97795. }
  97796. var engine = scene.getEngine();
  97797. this._lineShader._preBind();
  97798. // VBOs
  97799. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  97800. scene.resetCachedMaterial();
  97801. this._lineShader.setColor4("color", this._source.edgesColor);
  97802. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  97803. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  97804. }
  97805. else {
  97806. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  97807. }
  97808. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  97809. this._lineShader.bind(this._source.getWorldMatrix());
  97810. // Draw order
  97811. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  97812. this._lineShader.unbind();
  97813. engine.setDepthWrite(true);
  97814. };
  97815. return EdgesRenderer;
  97816. }());
  97817. BABYLON.EdgesRenderer = EdgesRenderer;
  97818. })(BABYLON || (BABYLON = {}));
  97819. //# sourceMappingURL=babylon.edgesRenderer.js.map
  97820. var BABYLON;
  97821. (function (BABYLON) {
  97822. // Adds the parser to the scene parsers.
  97823. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  97824. if (parsedData.effectLayers) {
  97825. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  97826. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  97827. container.effectLayers.push(effectLayer);
  97828. }
  97829. }
  97830. });
  97831. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  97832. var index = this.effectLayers.indexOf(toRemove);
  97833. if (index !== -1) {
  97834. this.effectLayers.splice(index, 1);
  97835. }
  97836. return index;
  97837. };
  97838. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  97839. this.effectLayers.push(newEffectLayer);
  97840. };
  97841. /**
  97842. * Defines the layer scene component responsible to manage any effect layers
  97843. * in a given scene.
  97844. */
  97845. var EffectLayerSceneComponent = /** @class */ (function () {
  97846. /**
  97847. * Creates a new instance of the component for the given scene
  97848. * @param scene Defines the scene to register the component in
  97849. */
  97850. function EffectLayerSceneComponent(scene) {
  97851. /**
  97852. * The component name helpfull to identify the component in the list of scene components.
  97853. */
  97854. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  97855. this._renderEffects = false;
  97856. this._needStencil = false;
  97857. this._previousStencilState = false;
  97858. this.scene = scene;
  97859. this._engine = scene.getEngine();
  97860. scene.effectLayers = new Array();
  97861. }
  97862. /**
  97863. * Registers the component in a given scene
  97864. */
  97865. EffectLayerSceneComponent.prototype.register = function () {
  97866. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  97867. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  97868. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  97869. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  97870. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  97871. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  97872. };
  97873. /**
  97874. * Rebuilds the elements related to this component in case of
  97875. * context lost for instance.
  97876. */
  97877. EffectLayerSceneComponent.prototype.rebuild = function () {
  97878. var layers = this.scene.effectLayers;
  97879. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  97880. var effectLayer = layers_1[_i];
  97881. effectLayer._rebuild();
  97882. }
  97883. };
  97884. /**
  97885. * Serializes the component data to the specified json object
  97886. * @param serializationObject The object to serialize to
  97887. */
  97888. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  97889. // Effect layers
  97890. serializationObject.effectLayers = [];
  97891. var layers = this.scene.effectLayers;
  97892. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  97893. var effectLayer = layers_2[_i];
  97894. if (effectLayer.serialize) {
  97895. serializationObject.effectLayers.push(effectLayer.serialize());
  97896. }
  97897. }
  97898. };
  97899. /**
  97900. * Adds all the element from the container to the scene
  97901. * @param container the container holding the elements
  97902. */
  97903. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  97904. var _this = this;
  97905. if (!container.effectLayers) {
  97906. return;
  97907. }
  97908. container.effectLayers.forEach(function (o) {
  97909. _this.scene.addEffectLayer(o);
  97910. });
  97911. };
  97912. /**
  97913. * Removes all the elements in the container from the scene
  97914. * @param container contains the elements to remove
  97915. */
  97916. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  97917. var _this = this;
  97918. if (!container.effectLayers) {
  97919. return;
  97920. }
  97921. container.effectLayers.forEach(function (o) {
  97922. _this.scene.removeEffectLayer(o);
  97923. });
  97924. };
  97925. /**
  97926. * Disposes the component and the associated ressources.
  97927. */
  97928. EffectLayerSceneComponent.prototype.dispose = function () {
  97929. var layers = this.scene.effectLayers;
  97930. while (layers.length) {
  97931. layers[0].dispose();
  97932. }
  97933. };
  97934. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  97935. var layers = this.scene.effectLayers;
  97936. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  97937. var layer = layers_3[_i];
  97938. if (!layer.hasMesh(mesh)) {
  97939. continue;
  97940. }
  97941. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  97942. var subMesh = _b[_a];
  97943. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  97944. return false;
  97945. }
  97946. }
  97947. }
  97948. return true;
  97949. };
  97950. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  97951. this._renderEffects = false;
  97952. this._needStencil = false;
  97953. var layers = this.scene.effectLayers;
  97954. if (layers && layers.length > 0) {
  97955. this._previousStencilState = this._engine.getStencilBuffer();
  97956. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  97957. var effectLayer = layers_4[_i];
  97958. if (effectLayer.shouldRender() &&
  97959. (!effectLayer.camera ||
  97960. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  97961. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  97962. this._renderEffects = true;
  97963. this._needStencil = this._needStencil || effectLayer.needStencil();
  97964. var renderTarget = effectLayer._mainTexture;
  97965. if (renderTarget._shouldRender()) {
  97966. this.scene.incrementRenderId();
  97967. renderTarget.render(false, false);
  97968. }
  97969. }
  97970. }
  97971. this.scene.incrementRenderId();
  97972. }
  97973. };
  97974. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  97975. // Activate effect Layer stencil
  97976. if (this._needStencil) {
  97977. this._engine.setStencilBuffer(true);
  97978. }
  97979. };
  97980. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  97981. // Restore effect Layer stencil
  97982. if (this._needStencil) {
  97983. this._engine.setStencilBuffer(this._previousStencilState);
  97984. }
  97985. };
  97986. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  97987. if (this._renderEffects) {
  97988. this._engine.setDepthBuffer(false);
  97989. var layers = this.scene.effectLayers;
  97990. for (var i = 0; i < layers.length; i++) {
  97991. var effectLayer = layers[i];
  97992. if (effectLayer.renderingGroupId === renderingGroupId) {
  97993. if (effectLayer.shouldRender()) {
  97994. effectLayer.render();
  97995. }
  97996. }
  97997. }
  97998. this._engine.setDepthBuffer(true);
  97999. }
  98000. };
  98001. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  98002. if (this._renderEffects) {
  98003. this._draw(-1);
  98004. }
  98005. };
  98006. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  98007. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  98008. this._draw(index);
  98009. }
  98010. };
  98011. return EffectLayerSceneComponent;
  98012. }());
  98013. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  98014. })(BABYLON || (BABYLON = {}));
  98015. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  98016. var __assign = (this && this.__assign) || Object.assign || function(t) {
  98017. for (var s, i = 1, n = arguments.length; i < n; i++) {
  98018. s = arguments[i];
  98019. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  98020. t[p] = s[p];
  98021. }
  98022. return t;
  98023. };
  98024. var BABYLON;
  98025. (function (BABYLON) {
  98026. /**
  98027. * The effect layer Helps adding post process effect blended with the main pass.
  98028. *
  98029. * This can be for instance use to generate glow or higlight effects on the scene.
  98030. *
  98031. * The effect layer class can not be used directly and is intented to inherited from to be
  98032. * customized per effects.
  98033. */
  98034. var EffectLayer = /** @class */ (function () {
  98035. /**
  98036. * Instantiates a new effect Layer and references it in the scene.
  98037. * @param name The name of the layer
  98038. * @param scene The scene to use the layer in
  98039. */
  98040. function EffectLayer(
  98041. /** The Friendly of the effect in the scene */
  98042. name, scene) {
  98043. this._vertexBuffers = {};
  98044. this._maxSize = 0;
  98045. this._mainTextureDesiredSize = { width: 0, height: 0 };
  98046. this._shouldRender = true;
  98047. this._postProcesses = [];
  98048. this._textures = [];
  98049. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  98050. /**
  98051. * The clear color of the texture used to generate the glow map.
  98052. */
  98053. this.neutralColor = new BABYLON.Color4();
  98054. /**
  98055. * Specifies wether the highlight layer is enabled or not.
  98056. */
  98057. this.isEnabled = true;
  98058. /**
  98059. * An event triggered when the effect layer has been disposed.
  98060. */
  98061. this.onDisposeObservable = new BABYLON.Observable();
  98062. /**
  98063. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  98064. */
  98065. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  98066. /**
  98067. * An event triggered when the generated texture is being merged in the scene.
  98068. */
  98069. this.onBeforeComposeObservable = new BABYLON.Observable();
  98070. /**
  98071. * An event triggered when the generated texture has been merged in the scene.
  98072. */
  98073. this.onAfterComposeObservable = new BABYLON.Observable();
  98074. /**
  98075. * An event triggered when the efffect layer changes its size.
  98076. */
  98077. this.onSizeChangedObservable = new BABYLON.Observable();
  98078. this.name = name;
  98079. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  98080. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  98081. if (!component) {
  98082. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  98083. this._scene._addComponent(component);
  98084. }
  98085. this._engine = this._scene.getEngine();
  98086. this._maxSize = this._engine.getCaps().maxTextureSize;
  98087. this._scene.effectLayers.push(this);
  98088. // Generate Buffers
  98089. this._generateIndexBuffer();
  98090. this._genrateVertexBuffer();
  98091. }
  98092. Object.defineProperty(EffectLayer.prototype, "camera", {
  98093. /**
  98094. * Gets the camera attached to the layer.
  98095. */
  98096. get: function () {
  98097. return this._effectLayerOptions.camera;
  98098. },
  98099. enumerable: true,
  98100. configurable: true
  98101. });
  98102. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  98103. /**
  98104. * Gets the rendering group id the layer should render in.
  98105. */
  98106. get: function () {
  98107. return this._effectLayerOptions.renderingGroupId;
  98108. },
  98109. enumerable: true,
  98110. configurable: true
  98111. });
  98112. /**
  98113. * Initializes the effect layer with the required options.
  98114. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  98115. */
  98116. EffectLayer.prototype._init = function (options) {
  98117. // Adapt options
  98118. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  98119. this._setMainTextureSize();
  98120. this._createMainTexture();
  98121. this._createTextureAndPostProcesses();
  98122. this._mergeEffect = this._createMergeEffect();
  98123. };
  98124. /**
  98125. * Generates the index buffer of the full screen quad blending to the main canvas.
  98126. */
  98127. EffectLayer.prototype._generateIndexBuffer = function () {
  98128. // Indices
  98129. var indices = [];
  98130. indices.push(0);
  98131. indices.push(1);
  98132. indices.push(2);
  98133. indices.push(0);
  98134. indices.push(2);
  98135. indices.push(3);
  98136. this._indexBuffer = this._engine.createIndexBuffer(indices);
  98137. };
  98138. /**
  98139. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  98140. */
  98141. EffectLayer.prototype._genrateVertexBuffer = function () {
  98142. // VBO
  98143. var vertices = [];
  98144. vertices.push(1, 1);
  98145. vertices.push(-1, 1);
  98146. vertices.push(-1, -1);
  98147. vertices.push(1, -1);
  98148. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  98149. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  98150. };
  98151. /**
  98152. * Sets the main texture desired size which is the closest power of two
  98153. * of the engine canvas size.
  98154. */
  98155. EffectLayer.prototype._setMainTextureSize = function () {
  98156. if (this._effectLayerOptions.mainTextureFixedSize) {
  98157. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  98158. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  98159. }
  98160. else {
  98161. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  98162. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  98163. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  98164. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  98165. }
  98166. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  98167. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  98168. };
  98169. /**
  98170. * Creates the main texture for the effect layer.
  98171. */
  98172. EffectLayer.prototype._createMainTexture = function () {
  98173. var _this = this;
  98174. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  98175. width: this._mainTextureDesiredSize.width,
  98176. height: this._mainTextureDesiredSize.height
  98177. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  98178. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  98179. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98180. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98181. this._mainTexture.anisotropicFilteringLevel = 1;
  98182. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98183. this._mainTexture.renderParticles = false;
  98184. this._mainTexture.renderList = null;
  98185. this._mainTexture.ignoreCameraViewport = true;
  98186. // Custom render function
  98187. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  98188. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  98189. var index;
  98190. var engine = _this._scene.getEngine();
  98191. if (depthOnlySubMeshes.length) {
  98192. engine.setColorWrite(false);
  98193. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  98194. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  98195. }
  98196. engine.setColorWrite(true);
  98197. }
  98198. for (index = 0; index < opaqueSubMeshes.length; index++) {
  98199. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  98200. }
  98201. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  98202. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  98203. }
  98204. for (index = 0; index < transparentSubMeshes.length; index++) {
  98205. _this._renderSubMesh(transparentSubMeshes.data[index]);
  98206. }
  98207. };
  98208. this._mainTexture.onClearObservable.add(function (engine) {
  98209. engine.clear(_this.neutralColor, true, true, true);
  98210. });
  98211. };
  98212. /**
  98213. * Checks for the readiness of the element composing the layer.
  98214. * @param subMesh the mesh to check for
  98215. * @param useInstances specify wether or not to use instances to render the mesh
  98216. * @param emissiveTexture the associated emissive texture used to generate the glow
  98217. * @return true if ready otherwise, false
  98218. */
  98219. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  98220. var material = subMesh.getMaterial();
  98221. if (!material) {
  98222. return false;
  98223. }
  98224. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  98225. return false;
  98226. }
  98227. var defines = [];
  98228. var attribs = [BABYLON.VertexBuffer.PositionKind];
  98229. var mesh = subMesh.getMesh();
  98230. var uv1 = false;
  98231. var uv2 = false;
  98232. // Alpha test
  98233. if (material && material.needAlphaTesting()) {
  98234. var alphaTexture = material.getAlphaTestTexture();
  98235. if (alphaTexture) {
  98236. defines.push("#define ALPHATEST");
  98237. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  98238. alphaTexture.coordinatesIndex === 1) {
  98239. defines.push("#define DIFFUSEUV2");
  98240. uv2 = true;
  98241. }
  98242. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  98243. defines.push("#define DIFFUSEUV1");
  98244. uv1 = true;
  98245. }
  98246. }
  98247. }
  98248. // Emissive
  98249. if (emissiveTexture) {
  98250. defines.push("#define EMISSIVE");
  98251. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  98252. emissiveTexture.coordinatesIndex === 1) {
  98253. defines.push("#define EMISSIVEUV2");
  98254. uv2 = true;
  98255. }
  98256. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  98257. defines.push("#define EMISSIVEUV1");
  98258. uv1 = true;
  98259. }
  98260. }
  98261. if (uv1) {
  98262. attribs.push(BABYLON.VertexBuffer.UVKind);
  98263. defines.push("#define UV1");
  98264. }
  98265. if (uv2) {
  98266. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  98267. defines.push("#define UV2");
  98268. }
  98269. // Bones
  98270. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  98271. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  98272. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  98273. if (mesh.numBoneInfluencers > 4) {
  98274. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  98275. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  98276. }
  98277. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  98278. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  98279. }
  98280. else {
  98281. defines.push("#define NUM_BONE_INFLUENCERS 0");
  98282. }
  98283. // Morph targets
  98284. var manager = mesh.morphTargetManager;
  98285. var morphInfluencers = 0;
  98286. if (manager) {
  98287. if (manager.numInfluencers > 0) {
  98288. defines.push("#define MORPHTARGETS");
  98289. morphInfluencers = manager.numInfluencers;
  98290. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  98291. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  98292. }
  98293. }
  98294. // Instances
  98295. if (useInstances) {
  98296. defines.push("#define INSTANCES");
  98297. attribs.push("world0");
  98298. attribs.push("world1");
  98299. attribs.push("world2");
  98300. attribs.push("world3");
  98301. }
  98302. // Get correct effect
  98303. var join = defines.join("\n");
  98304. if (this._cachedDefines !== join) {
  98305. this._cachedDefines = join;
  98306. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  98307. }
  98308. return this._effectLayerMapGenerationEffect.isReady();
  98309. };
  98310. /**
  98311. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  98312. */
  98313. EffectLayer.prototype.render = function () {
  98314. var currentEffect = this._mergeEffect;
  98315. // Check
  98316. if (!currentEffect.isReady())
  98317. return;
  98318. for (var i = 0; i < this._postProcesses.length; i++) {
  98319. if (!this._postProcesses[i].isReady()) {
  98320. return;
  98321. }
  98322. }
  98323. var engine = this._scene.getEngine();
  98324. this.onBeforeComposeObservable.notifyObservers(this);
  98325. // Render
  98326. engine.enableEffect(currentEffect);
  98327. engine.setState(false);
  98328. // VBOs
  98329. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  98330. // Cache
  98331. var previousAlphaMode = engine.getAlphaMode();
  98332. // Go Blend.
  98333. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  98334. // Blends the map on the main canvas.
  98335. this._internalRender(currentEffect);
  98336. // Restore Alpha
  98337. engine.setAlphaMode(previousAlphaMode);
  98338. this.onAfterComposeObservable.notifyObservers(this);
  98339. // Handle size changes.
  98340. var size = this._mainTexture.getSize();
  98341. this._setMainTextureSize();
  98342. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  98343. // Recreate RTT and post processes on size change.
  98344. this.onSizeChangedObservable.notifyObservers(this);
  98345. this._disposeTextureAndPostProcesses();
  98346. this._createMainTexture();
  98347. this._createTextureAndPostProcesses();
  98348. }
  98349. };
  98350. /**
  98351. * Determine if a given mesh will be used in the current effect.
  98352. * @param mesh mesh to test
  98353. * @returns true if the mesh will be used
  98354. */
  98355. EffectLayer.prototype.hasMesh = function (mesh) {
  98356. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  98357. return true;
  98358. }
  98359. return false;
  98360. };
  98361. /**
  98362. * Returns true if the layer contains information to display, otherwise false.
  98363. * @returns true if the glow layer should be rendered
  98364. */
  98365. EffectLayer.prototype.shouldRender = function () {
  98366. return this.isEnabled && this._shouldRender;
  98367. };
  98368. /**
  98369. * Returns true if the mesh should render, otherwise false.
  98370. * @param mesh The mesh to render
  98371. * @returns true if it should render otherwise false
  98372. */
  98373. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  98374. return true;
  98375. };
  98376. /**
  98377. * Returns true if the mesh should render, otherwise false.
  98378. * @param mesh The mesh to render
  98379. * @returns true if it should render otherwise false
  98380. */
  98381. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  98382. return true;
  98383. };
  98384. /**
  98385. * Renders the submesh passed in parameter to the generation map.
  98386. */
  98387. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  98388. var _this = this;
  98389. if (!this.shouldRender()) {
  98390. return;
  98391. }
  98392. var material = subMesh.getMaterial();
  98393. var mesh = subMesh.getRenderingMesh();
  98394. var scene = this._scene;
  98395. var engine = scene.getEngine();
  98396. if (!material) {
  98397. return;
  98398. }
  98399. // Do not block in blend mode.
  98400. if (material.needAlphaBlendingForMesh(mesh)) {
  98401. return;
  98402. }
  98403. // Culling
  98404. engine.setState(material.backFaceCulling);
  98405. // Managing instances
  98406. var batch = mesh._getInstancesRenderList(subMesh._id);
  98407. if (batch.mustReturn) {
  98408. return;
  98409. }
  98410. // Early Exit per mesh
  98411. if (!this._shouldRenderMesh(mesh)) {
  98412. return;
  98413. }
  98414. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  98415. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  98416. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  98417. engine.enableEffect(this._effectLayerMapGenerationEffect);
  98418. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  98419. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  98420. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  98421. // Alpha test
  98422. if (material && material.needAlphaTesting()) {
  98423. var alphaTexture = material.getAlphaTestTexture();
  98424. if (alphaTexture) {
  98425. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  98426. var textureMatrix = alphaTexture.getTextureMatrix();
  98427. if (textureMatrix) {
  98428. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  98429. }
  98430. }
  98431. }
  98432. // Glow emissive only
  98433. if (this._emissiveTextureAndColor.texture) {
  98434. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  98435. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  98436. }
  98437. // Bones
  98438. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  98439. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  98440. }
  98441. // Morph targets
  98442. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  98443. // Draw
  98444. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  98445. }
  98446. else {
  98447. // Need to reset refresh rate of the main map
  98448. this._mainTexture.resetRefreshCounter();
  98449. }
  98450. };
  98451. /**
  98452. * Rebuild the required buffers.
  98453. * @hidden Internal use only.
  98454. */
  98455. EffectLayer.prototype._rebuild = function () {
  98456. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98457. if (vb) {
  98458. vb._rebuild();
  98459. }
  98460. this._generateIndexBuffer();
  98461. };
  98462. /**
  98463. * Dispose only the render target textures and post process.
  98464. */
  98465. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  98466. this._mainTexture.dispose();
  98467. for (var i = 0; i < this._postProcesses.length; i++) {
  98468. if (this._postProcesses[i]) {
  98469. this._postProcesses[i].dispose();
  98470. }
  98471. }
  98472. this._postProcesses = [];
  98473. for (var i = 0; i < this._textures.length; i++) {
  98474. if (this._textures[i]) {
  98475. this._textures[i].dispose();
  98476. }
  98477. }
  98478. this._textures = [];
  98479. };
  98480. /**
  98481. * Dispose the highlight layer and free resources.
  98482. */
  98483. EffectLayer.prototype.dispose = function () {
  98484. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98485. if (vertexBuffer) {
  98486. vertexBuffer.dispose();
  98487. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  98488. }
  98489. if (this._indexBuffer) {
  98490. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  98491. this._indexBuffer = null;
  98492. }
  98493. // Clean textures and post processes
  98494. this._disposeTextureAndPostProcesses();
  98495. // Remove from scene
  98496. var index = this._scene.effectLayers.indexOf(this, 0);
  98497. if (index > -1) {
  98498. this._scene.effectLayers.splice(index, 1);
  98499. }
  98500. // Callback
  98501. this.onDisposeObservable.notifyObservers(this);
  98502. this.onDisposeObservable.clear();
  98503. this.onBeforeRenderMainTextureObservable.clear();
  98504. this.onBeforeComposeObservable.clear();
  98505. this.onAfterComposeObservable.clear();
  98506. this.onSizeChangedObservable.clear();
  98507. };
  98508. /**
  98509. * Gets the class name of the effect layer
  98510. * @returns the string with the class name of the effect layer
  98511. */
  98512. EffectLayer.prototype.getClassName = function () {
  98513. return "EffectLayer";
  98514. };
  98515. /**
  98516. * Creates an effect layer from parsed effect layer data
  98517. * @param parsedEffectLayer defines effect layer data
  98518. * @param scene defines the current scene
  98519. * @param rootUrl defines the root URL containing the effect layer information
  98520. * @returns a parsed effect Layer
  98521. */
  98522. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  98523. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  98524. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  98525. };
  98526. __decorate([
  98527. BABYLON.serialize()
  98528. ], EffectLayer.prototype, "name", void 0);
  98529. __decorate([
  98530. BABYLON.serializeAsColor4()
  98531. ], EffectLayer.prototype, "neutralColor", void 0);
  98532. __decorate([
  98533. BABYLON.serialize()
  98534. ], EffectLayer.prototype, "isEnabled", void 0);
  98535. __decorate([
  98536. BABYLON.serializeAsCameraReference()
  98537. ], EffectLayer.prototype, "camera", null);
  98538. __decorate([
  98539. BABYLON.serialize()
  98540. ], EffectLayer.prototype, "renderingGroupId", null);
  98541. return EffectLayer;
  98542. }());
  98543. BABYLON.EffectLayer = EffectLayer;
  98544. })(BABYLON || (BABYLON = {}));
  98545. //# sourceMappingURL=babylon.effectLayer.js.map
  98546. var BABYLON;
  98547. (function (BABYLON) {
  98548. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  98549. for (var index = 0; index < this.effectLayers.length; index++) {
  98550. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  98551. return this.effectLayers[index];
  98552. }
  98553. }
  98554. return null;
  98555. };
  98556. /**
  98557. * Special Glow Blur post process only blurring the alpha channel
  98558. * It enforces keeping the most luminous color in the color channel.
  98559. */
  98560. var GlowBlurPostProcess = /** @class */ (function (_super) {
  98561. __extends(GlowBlurPostProcess, _super);
  98562. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  98563. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  98564. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  98565. _this.direction = direction;
  98566. _this.kernel = kernel;
  98567. _this.onApplyObservable.add(function (effect) {
  98568. effect.setFloat2("screenSize", _this.width, _this.height);
  98569. effect.setVector2("direction", _this.direction);
  98570. effect.setFloat("blurWidth", _this.kernel);
  98571. });
  98572. return _this;
  98573. }
  98574. return GlowBlurPostProcess;
  98575. }(BABYLON.PostProcess));
  98576. /**
  98577. * The highlight layer Helps adding a glow effect around a mesh.
  98578. *
  98579. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  98580. * glowy meshes to your scene.
  98581. *
  98582. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  98583. */
  98584. var HighlightLayer = /** @class */ (function (_super) {
  98585. __extends(HighlightLayer, _super);
  98586. /**
  98587. * Instantiates a new highlight Layer and references it to the scene..
  98588. * @param name The name of the layer
  98589. * @param scene The scene to use the layer in
  98590. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  98591. */
  98592. function HighlightLayer(name, scene, options) {
  98593. var _this = _super.call(this, name, scene) || this;
  98594. _this.name = name;
  98595. /**
  98596. * Specifies whether or not the inner glow is ACTIVE in the layer.
  98597. */
  98598. _this.innerGlow = true;
  98599. /**
  98600. * Specifies whether or not the outer glow is ACTIVE in the layer.
  98601. */
  98602. _this.outerGlow = true;
  98603. /**
  98604. * An event triggered when the highlight layer is being blurred.
  98605. */
  98606. _this.onBeforeBlurObservable = new BABYLON.Observable();
  98607. /**
  98608. * An event triggered when the highlight layer has been blurred.
  98609. */
  98610. _this.onAfterBlurObservable = new BABYLON.Observable();
  98611. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  98612. _this._meshes = {};
  98613. _this._excludedMeshes = {};
  98614. _this.neutralColor = HighlightLayer.NeutralColor;
  98615. // Warn on stencil
  98616. if (!_this._engine.isStencilEnable) {
  98617. 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 }");
  98618. }
  98619. // Adapt options
  98620. _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);
  98621. // Initialize the layer
  98622. _this._init({
  98623. alphaBlendingMode: _this._options.alphaBlendingMode,
  98624. camera: _this._options.camera,
  98625. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  98626. mainTextureRatio: _this._options.mainTextureRatio,
  98627. renderingGroupId: _this._options.renderingGroupId
  98628. });
  98629. // Do not render as long as no meshes have been added
  98630. _this._shouldRender = false;
  98631. return _this;
  98632. }
  98633. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  98634. /**
  98635. * Gets the horizontal size of the blur.
  98636. */
  98637. get: function () {
  98638. return this._horizontalBlurPostprocess.kernel;
  98639. },
  98640. /**
  98641. * Specifies the horizontal size of the blur.
  98642. */
  98643. set: function (value) {
  98644. this._horizontalBlurPostprocess.kernel = value;
  98645. },
  98646. enumerable: true,
  98647. configurable: true
  98648. });
  98649. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  98650. /**
  98651. * Gets the vertical size of the blur.
  98652. */
  98653. get: function () {
  98654. return this._verticalBlurPostprocess.kernel;
  98655. },
  98656. /**
  98657. * Specifies the vertical size of the blur.
  98658. */
  98659. set: function (value) {
  98660. this._verticalBlurPostprocess.kernel = value;
  98661. },
  98662. enumerable: true,
  98663. configurable: true
  98664. });
  98665. /**
  98666. * Get the effect name of the layer.
  98667. * @return The effect name
  98668. */
  98669. HighlightLayer.prototype.getEffectName = function () {
  98670. return HighlightLayer.EffectName;
  98671. };
  98672. /**
  98673. * Create the merge effect. This is the shader use to blit the information back
  98674. * to the main canvas at the end of the scene rendering.
  98675. */
  98676. HighlightLayer.prototype._createMergeEffect = function () {
  98677. // Effect
  98678. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  98679. };
  98680. /**
  98681. * Creates the render target textures and post processes used in the highlight layer.
  98682. */
  98683. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  98684. var _this = this;
  98685. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  98686. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  98687. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  98688. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  98689. var textureType = 0;
  98690. if (this._engine.getCaps().textureHalfFloatRender) {
  98691. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98692. }
  98693. else {
  98694. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98695. }
  98696. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  98697. width: blurTextureWidth,
  98698. height: blurTextureHeight
  98699. }, this._scene, false, true, textureType);
  98700. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98701. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98702. this._blurTexture.anisotropicFilteringLevel = 16;
  98703. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  98704. this._blurTexture.renderParticles = false;
  98705. this._blurTexture.ignoreCameraViewport = true;
  98706. this._textures = [this._blurTexture];
  98707. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  98708. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  98709. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  98710. effect.setTexture("textureSampler", _this._mainTexture);
  98711. });
  98712. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  98713. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  98714. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  98715. });
  98716. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  98717. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  98718. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  98719. });
  98720. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  98721. }
  98722. else {
  98723. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  98724. width: blurTextureWidth,
  98725. height: blurTextureHeight
  98726. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98727. this._horizontalBlurPostprocess.width = blurTextureWidth;
  98728. this._horizontalBlurPostprocess.height = blurTextureHeight;
  98729. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  98730. effect.setTexture("textureSampler", _this._mainTexture);
  98731. });
  98732. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  98733. width: blurTextureWidth,
  98734. height: blurTextureHeight
  98735. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98736. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  98737. }
  98738. this._mainTexture.onAfterUnbindObservable.add(function () {
  98739. _this.onBeforeBlurObservable.notifyObservers(_this);
  98740. var internalTexture = _this._blurTexture.getInternalTexture();
  98741. if (internalTexture) {
  98742. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  98743. }
  98744. _this.onAfterBlurObservable.notifyObservers(_this);
  98745. });
  98746. // Prevent autoClear.
  98747. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  98748. };
  98749. /**
  98750. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  98751. */
  98752. HighlightLayer.prototype.needStencil = function () {
  98753. return true;
  98754. };
  98755. /**
  98756. * Checks for the readiness of the element composing the layer.
  98757. * @param subMesh the mesh to check for
  98758. * @param useInstances specify wether or not to use instances to render the mesh
  98759. * @param emissiveTexture the associated emissive texture used to generate the glow
  98760. * @return true if ready otherwise, false
  98761. */
  98762. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  98763. var material = subMesh.getMaterial();
  98764. var mesh = subMesh.getRenderingMesh();
  98765. if (!material || !mesh || !this._meshes) {
  98766. return false;
  98767. }
  98768. var emissiveTexture = null;
  98769. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  98770. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  98771. emissiveTexture = material.emissiveTexture;
  98772. }
  98773. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  98774. };
  98775. /**
  98776. * Implementation specific of rendering the generating effect on the main canvas.
  98777. * @param effect The effect used to render through
  98778. */
  98779. HighlightLayer.prototype._internalRender = function (effect) {
  98780. // Texture
  98781. effect.setTexture("textureSampler", this._blurTexture);
  98782. // Cache
  98783. var engine = this._engine;
  98784. var previousStencilBuffer = engine.getStencilBuffer();
  98785. var previousStencilFunction = engine.getStencilFunction();
  98786. var previousStencilMask = engine.getStencilMask();
  98787. var previousStencilOperationPass = engine.getStencilOperationPass();
  98788. var previousStencilOperationFail = engine.getStencilOperationFail();
  98789. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  98790. var previousStencilReference = engine.getStencilFunctionReference();
  98791. // Stencil operations
  98792. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  98793. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  98794. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  98795. // Draw order
  98796. engine.setStencilMask(0x00);
  98797. engine.setStencilBuffer(true);
  98798. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  98799. // 2 passes inner outer
  98800. if (this.outerGlow) {
  98801. effect.setFloat("offset", 0);
  98802. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  98803. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98804. }
  98805. if (this.innerGlow) {
  98806. effect.setFloat("offset", 1);
  98807. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  98808. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98809. }
  98810. // Restore Cache
  98811. engine.setStencilFunction(previousStencilFunction);
  98812. engine.setStencilMask(previousStencilMask);
  98813. engine.setStencilBuffer(previousStencilBuffer);
  98814. engine.setStencilOperationPass(previousStencilOperationPass);
  98815. engine.setStencilOperationFail(previousStencilOperationFail);
  98816. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  98817. engine.setStencilFunctionReference(previousStencilReference);
  98818. };
  98819. /**
  98820. * Returns true if the layer contains information to display, otherwise false.
  98821. */
  98822. HighlightLayer.prototype.shouldRender = function () {
  98823. if (_super.prototype.shouldRender.call(this)) {
  98824. return this._meshes ? true : false;
  98825. }
  98826. return false;
  98827. };
  98828. /**
  98829. * Returns true if the mesh should render, otherwise false.
  98830. * @param mesh The mesh to render
  98831. * @returns true if it should render otherwise false
  98832. */
  98833. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  98834. // Excluded Mesh
  98835. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  98836. return false;
  98837. }
  98838. ;
  98839. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98840. return false;
  98841. }
  98842. return true;
  98843. };
  98844. /**
  98845. * Sets the required values for both the emissive texture and and the main color.
  98846. */
  98847. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98848. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  98849. if (highlightLayerMesh) {
  98850. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  98851. }
  98852. else {
  98853. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98854. }
  98855. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  98856. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98857. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  98858. }
  98859. else {
  98860. this._emissiveTextureAndColor.texture = null;
  98861. }
  98862. };
  98863. /**
  98864. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  98865. * @param mesh The mesh to exclude from the highlight layer
  98866. */
  98867. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  98868. if (!this._excludedMeshes) {
  98869. return;
  98870. }
  98871. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98872. if (!meshExcluded) {
  98873. this._excludedMeshes[mesh.uniqueId] = {
  98874. mesh: mesh,
  98875. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  98876. mesh.getEngine().setStencilBuffer(false);
  98877. }),
  98878. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  98879. mesh.getEngine().setStencilBuffer(true);
  98880. }),
  98881. };
  98882. }
  98883. };
  98884. /**
  98885. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  98886. * @param mesh The mesh to highlight
  98887. */
  98888. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  98889. if (!this._excludedMeshes) {
  98890. return;
  98891. }
  98892. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98893. if (meshExcluded) {
  98894. if (meshExcluded.beforeRender) {
  98895. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  98896. }
  98897. if (meshExcluded.afterRender) {
  98898. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  98899. }
  98900. }
  98901. this._excludedMeshes[mesh.uniqueId] = null;
  98902. };
  98903. /**
  98904. * Determine if a given mesh will be highlighted by the current HighlightLayer
  98905. * @param mesh mesh to test
  98906. * @returns true if the mesh will be highlighted by the current HighlightLayer
  98907. */
  98908. HighlightLayer.prototype.hasMesh = function (mesh) {
  98909. if (!this._meshes) {
  98910. return false;
  98911. }
  98912. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98913. return false;
  98914. }
  98915. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  98916. };
  98917. /**
  98918. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  98919. * @param mesh The mesh to highlight
  98920. * @param color The color of the highlight
  98921. * @param glowEmissiveOnly Extract the glow from the emissive texture
  98922. */
  98923. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  98924. var _this = this;
  98925. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  98926. if (!this._meshes) {
  98927. return;
  98928. }
  98929. var meshHighlight = this._meshes[mesh.uniqueId];
  98930. if (meshHighlight) {
  98931. meshHighlight.color = color;
  98932. }
  98933. else {
  98934. this._meshes[mesh.uniqueId] = {
  98935. mesh: mesh,
  98936. color: color,
  98937. // Lambda required for capture due to Observable this context
  98938. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  98939. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  98940. _this._defaultStencilReference(mesh);
  98941. }
  98942. else {
  98943. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  98944. }
  98945. }),
  98946. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  98947. glowEmissiveOnly: glowEmissiveOnly
  98948. };
  98949. mesh.onDisposeObservable.add(function () {
  98950. _this._disposeMesh(mesh);
  98951. });
  98952. }
  98953. this._shouldRender = true;
  98954. };
  98955. /**
  98956. * Remove a mesh from the highlight layer in order to make it stop glowing.
  98957. * @param mesh The mesh to highlight
  98958. */
  98959. HighlightLayer.prototype.removeMesh = function (mesh) {
  98960. if (!this._meshes) {
  98961. return;
  98962. }
  98963. var meshHighlight = this._meshes[mesh.uniqueId];
  98964. if (meshHighlight) {
  98965. if (meshHighlight.observerHighlight) {
  98966. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98967. }
  98968. if (meshHighlight.observerDefault) {
  98969. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98970. }
  98971. delete this._meshes[mesh.uniqueId];
  98972. }
  98973. this._shouldRender = false;
  98974. for (var meshHighlightToCheck in this._meshes) {
  98975. if (this._meshes[meshHighlightToCheck]) {
  98976. this._shouldRender = true;
  98977. break;
  98978. }
  98979. }
  98980. };
  98981. /**
  98982. * Force the stencil to the normal expected value for none glowing parts
  98983. */
  98984. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  98985. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  98986. };
  98987. /**
  98988. * Free any resources and references associated to a mesh.
  98989. * Internal use
  98990. * @param mesh The mesh to free.
  98991. */
  98992. HighlightLayer.prototype._disposeMesh = function (mesh) {
  98993. this.removeMesh(mesh);
  98994. this.removeExcludedMesh(mesh);
  98995. };
  98996. /**
  98997. * Dispose the highlight layer and free resources.
  98998. */
  98999. HighlightLayer.prototype.dispose = function () {
  99000. if (this._meshes) {
  99001. // Clean mesh references
  99002. for (var id in this._meshes) {
  99003. var meshHighlight = this._meshes[id];
  99004. if (meshHighlight && meshHighlight.mesh) {
  99005. if (meshHighlight.observerHighlight) {
  99006. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  99007. }
  99008. if (meshHighlight.observerDefault) {
  99009. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  99010. }
  99011. }
  99012. }
  99013. this._meshes = null;
  99014. }
  99015. if (this._excludedMeshes) {
  99016. for (var id in this._excludedMeshes) {
  99017. var meshHighlight = this._excludedMeshes[id];
  99018. if (meshHighlight) {
  99019. if (meshHighlight.beforeRender) {
  99020. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  99021. }
  99022. if (meshHighlight.afterRender) {
  99023. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  99024. }
  99025. }
  99026. }
  99027. this._excludedMeshes = null;
  99028. }
  99029. _super.prototype.dispose.call(this);
  99030. };
  99031. /**
  99032. * Gets the class name of the effect layer
  99033. * @returns the string with the class name of the effect layer
  99034. */
  99035. HighlightLayer.prototype.getClassName = function () {
  99036. return "HighlightLayer";
  99037. };
  99038. /**
  99039. * Serializes this Highlight layer
  99040. * @returns a serialized Highlight layer object
  99041. */
  99042. HighlightLayer.prototype.serialize = function () {
  99043. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99044. serializationObject.customType = "BABYLON.HighlightLayer";
  99045. // Highlighted meshes
  99046. serializationObject.meshes = [];
  99047. if (this._meshes) {
  99048. for (var m in this._meshes) {
  99049. var mesh = this._meshes[m];
  99050. if (mesh) {
  99051. serializationObject.meshes.push({
  99052. glowEmissiveOnly: mesh.glowEmissiveOnly,
  99053. color: mesh.color.asArray(),
  99054. meshId: mesh.mesh.id
  99055. });
  99056. }
  99057. }
  99058. }
  99059. // Excluded meshes
  99060. serializationObject.excludedMeshes = [];
  99061. if (this._excludedMeshes) {
  99062. for (var e in this._excludedMeshes) {
  99063. var excludedMesh = this._excludedMeshes[e];
  99064. if (excludedMesh) {
  99065. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  99066. }
  99067. }
  99068. }
  99069. return serializationObject;
  99070. };
  99071. /**
  99072. * Creates a Highlight layer from parsed Highlight layer data
  99073. * @param parsedHightlightLayer defines the Highlight layer data
  99074. * @param scene defines the current scene
  99075. * @param rootUrl defines the root URL containing the Highlight layer information
  99076. * @returns a parsed Highlight layer
  99077. */
  99078. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  99079. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  99080. var index;
  99081. // Excluded meshes
  99082. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  99083. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  99084. if (mesh) {
  99085. hl.addExcludedMesh(mesh);
  99086. }
  99087. }
  99088. // Included meshes
  99089. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  99090. var highlightedMesh = parsedHightlightLayer.meshes[index];
  99091. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  99092. if (mesh) {
  99093. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  99094. }
  99095. }
  99096. return hl;
  99097. };
  99098. /**
  99099. * Effect Name of the highlight layer.
  99100. */
  99101. HighlightLayer.EffectName = "HighlightLayer";
  99102. /**
  99103. * The neutral color used during the preparation of the glow effect.
  99104. * This is black by default as the blend operation is a blend operation.
  99105. */
  99106. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  99107. /**
  99108. * Stencil value used for glowing meshes.
  99109. */
  99110. HighlightLayer.GlowingMeshStencilReference = 0x02;
  99111. /**
  99112. * Stencil value used for the other meshes in the scene.
  99113. */
  99114. HighlightLayer.NormalMeshStencilReference = 0x01;
  99115. __decorate([
  99116. BABYLON.serialize()
  99117. ], HighlightLayer.prototype, "innerGlow", void 0);
  99118. __decorate([
  99119. BABYLON.serialize()
  99120. ], HighlightLayer.prototype, "outerGlow", void 0);
  99121. __decorate([
  99122. BABYLON.serialize()
  99123. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  99124. __decorate([
  99125. BABYLON.serialize()
  99126. ], HighlightLayer.prototype, "blurVerticalSize", null);
  99127. __decorate([
  99128. BABYLON.serialize("options")
  99129. ], HighlightLayer.prototype, "_options", void 0);
  99130. return HighlightLayer;
  99131. }(BABYLON.EffectLayer));
  99132. BABYLON.HighlightLayer = HighlightLayer;
  99133. })(BABYLON || (BABYLON = {}));
  99134. //# sourceMappingURL=babylon.highlightLayer.js.map
  99135. var BABYLON;
  99136. (function (BABYLON) {
  99137. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  99138. for (var index = 0; index < this.effectLayers.length; index++) {
  99139. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  99140. return this.effectLayers[index];
  99141. }
  99142. }
  99143. return null;
  99144. };
  99145. /**
  99146. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  99147. *
  99148. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  99149. * glowy meshes to your scene.
  99150. *
  99151. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  99152. */
  99153. var GlowLayer = /** @class */ (function (_super) {
  99154. __extends(GlowLayer, _super);
  99155. /**
  99156. * Instantiates a new glow Layer and references it to the scene.
  99157. * @param name The name of the layer
  99158. * @param scene The scene to use the layer in
  99159. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  99160. */
  99161. function GlowLayer(name, scene, options) {
  99162. var _this = _super.call(this, name, scene) || this;
  99163. _this._intensity = 1.0;
  99164. _this._includedOnlyMeshes = [];
  99165. _this._excludedMeshes = [];
  99166. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  99167. // Adapt options
  99168. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  99169. // Initialize the layer
  99170. _this._init({
  99171. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  99172. camera: _this._options.camera,
  99173. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  99174. mainTextureRatio: _this._options.mainTextureRatio,
  99175. renderingGroupId: _this._options.renderingGroupId
  99176. });
  99177. return _this;
  99178. }
  99179. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  99180. /**
  99181. * Gets the kernel size of the blur.
  99182. */
  99183. get: function () {
  99184. return this._horizontalBlurPostprocess1.kernel;
  99185. },
  99186. /**
  99187. * Sets the kernel size of the blur.
  99188. */
  99189. set: function (value) {
  99190. this._horizontalBlurPostprocess1.kernel = value;
  99191. this._verticalBlurPostprocess1.kernel = value;
  99192. this._horizontalBlurPostprocess2.kernel = value;
  99193. this._verticalBlurPostprocess2.kernel = value;
  99194. },
  99195. enumerable: true,
  99196. configurable: true
  99197. });
  99198. Object.defineProperty(GlowLayer.prototype, "intensity", {
  99199. /**
  99200. * Gets the glow intensity.
  99201. */
  99202. get: function () {
  99203. return this._intensity;
  99204. },
  99205. /**
  99206. * Sets the glow intensity.
  99207. */
  99208. set: function (value) {
  99209. this._intensity = value;
  99210. },
  99211. enumerable: true,
  99212. configurable: true
  99213. });
  99214. /**
  99215. * Get the effect name of the layer.
  99216. * @return The effect name
  99217. */
  99218. GlowLayer.prototype.getEffectName = function () {
  99219. return GlowLayer.EffectName;
  99220. };
  99221. /**
  99222. * Create the merge effect. This is the shader use to blit the information back
  99223. * to the main canvas at the end of the scene rendering.
  99224. */
  99225. GlowLayer.prototype._createMergeEffect = function () {
  99226. // Effect
  99227. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  99228. };
  99229. /**
  99230. * Creates the render target textures and post processes used in the glow layer.
  99231. */
  99232. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  99233. var _this = this;
  99234. var blurTextureWidth = this._mainTextureDesiredSize.width;
  99235. var blurTextureHeight = this._mainTextureDesiredSize.height;
  99236. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  99237. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  99238. var textureType = 0;
  99239. if (this._engine.getCaps().textureHalfFloatRender) {
  99240. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99241. }
  99242. else {
  99243. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99244. }
  99245. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  99246. width: blurTextureWidth,
  99247. height: blurTextureHeight
  99248. }, this._scene, false, true, textureType);
  99249. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99250. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99251. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99252. this._blurTexture1.renderParticles = false;
  99253. this._blurTexture1.ignoreCameraViewport = true;
  99254. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  99255. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  99256. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  99257. width: blurTextureWidth2,
  99258. height: blurTextureHeight2
  99259. }, this._scene, false, true, textureType);
  99260. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99261. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99262. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99263. this._blurTexture2.renderParticles = false;
  99264. this._blurTexture2.ignoreCameraViewport = true;
  99265. this._textures = [this._blurTexture1, this._blurTexture2];
  99266. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  99267. width: blurTextureWidth,
  99268. height: blurTextureHeight
  99269. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99270. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  99271. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  99272. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  99273. effect.setTexture("textureSampler", _this._mainTexture);
  99274. });
  99275. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  99276. width: blurTextureWidth,
  99277. height: blurTextureHeight
  99278. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99279. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  99280. width: blurTextureWidth2,
  99281. height: blurTextureHeight2
  99282. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99283. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  99284. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  99285. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  99286. effect.setTexture("textureSampler", _this._blurTexture1);
  99287. });
  99288. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  99289. width: blurTextureWidth2,
  99290. height: blurTextureHeight2
  99291. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99292. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  99293. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  99294. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  99295. this._mainTexture.samples = this._options.mainTextureSamples;
  99296. this._mainTexture.onAfterUnbindObservable.add(function () {
  99297. var internalTexture = _this._blurTexture1.getInternalTexture();
  99298. if (internalTexture) {
  99299. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  99300. internalTexture = _this._blurTexture2.getInternalTexture();
  99301. if (internalTexture) {
  99302. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  99303. }
  99304. }
  99305. });
  99306. // Prevent autoClear.
  99307. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  99308. };
  99309. /**
  99310. * Checks for the readiness of the element composing the layer.
  99311. * @param subMesh the mesh to check for
  99312. * @param useInstances specify wether or not to use instances to render the mesh
  99313. * @param emissiveTexture the associated emissive texture used to generate the glow
  99314. * @return true if ready otherwise, false
  99315. */
  99316. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  99317. var material = subMesh.getMaterial();
  99318. var mesh = subMesh.getRenderingMesh();
  99319. if (!material || !mesh) {
  99320. return false;
  99321. }
  99322. var emissiveTexture = material.emissiveTexture;
  99323. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  99324. };
  99325. /**
  99326. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  99327. */
  99328. GlowLayer.prototype.needStencil = function () {
  99329. return false;
  99330. };
  99331. /**
  99332. * Implementation specific of rendering the generating effect on the main canvas.
  99333. * @param effect The effect used to render through
  99334. */
  99335. GlowLayer.prototype._internalRender = function (effect) {
  99336. // Texture
  99337. effect.setTexture("textureSampler", this._blurTexture1);
  99338. effect.setTexture("textureSampler2", this._blurTexture2);
  99339. effect.setFloat("offset", this._intensity);
  99340. // Cache
  99341. var engine = this._engine;
  99342. var previousStencilBuffer = engine.getStencilBuffer();
  99343. // Draw order
  99344. engine.setStencilBuffer(false);
  99345. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99346. // Draw order
  99347. engine.setStencilBuffer(previousStencilBuffer);
  99348. };
  99349. /**
  99350. * Sets the required values for both the emissive texture and and the main color.
  99351. */
  99352. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  99353. var textureLevel = 1.0;
  99354. if (this.customEmissiveTextureSelector) {
  99355. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  99356. }
  99357. else {
  99358. if (material) {
  99359. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  99360. if (this._emissiveTextureAndColor.texture) {
  99361. textureLevel = this._emissiveTextureAndColor.texture.level;
  99362. }
  99363. }
  99364. else {
  99365. this._emissiveTextureAndColor.texture = null;
  99366. }
  99367. }
  99368. if (this.customEmissiveColorSelector) {
  99369. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  99370. }
  99371. else {
  99372. if (material.emissiveColor) {
  99373. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  99374. }
  99375. else {
  99376. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  99377. }
  99378. }
  99379. };
  99380. /**
  99381. * Returns true if the mesh should render, otherwise false.
  99382. * @param mesh The mesh to render
  99383. * @returns true if it should render otherwise false
  99384. */
  99385. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  99386. return this.hasMesh(mesh);
  99387. };
  99388. /**
  99389. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  99390. * @param mesh The mesh to exclude from the glow layer
  99391. */
  99392. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  99393. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  99394. this._excludedMeshes.push(mesh.uniqueId);
  99395. }
  99396. };
  99397. /**
  99398. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  99399. * @param mesh The mesh to remove
  99400. */
  99401. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  99402. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  99403. if (index !== -1) {
  99404. this._excludedMeshes.splice(index, 1);
  99405. }
  99406. };
  99407. /**
  99408. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  99409. * @param mesh The mesh to include in the glow layer
  99410. */
  99411. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  99412. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  99413. this._includedOnlyMeshes.push(mesh.uniqueId);
  99414. }
  99415. };
  99416. /**
  99417. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  99418. * @param mesh The mesh to remove
  99419. */
  99420. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  99421. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  99422. if (index !== -1) {
  99423. this._includedOnlyMeshes.splice(index, 1);
  99424. }
  99425. };
  99426. /**
  99427. * Determine if a given mesh will be used in the glow layer
  99428. * @param mesh The mesh to test
  99429. * @returns true if the mesh will be highlighted by the current glow layer
  99430. */
  99431. GlowLayer.prototype.hasMesh = function (mesh) {
  99432. if (!_super.prototype.hasMesh.call(this, mesh)) {
  99433. return false;
  99434. }
  99435. // Included Mesh
  99436. if (this._includedOnlyMeshes.length) {
  99437. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  99438. }
  99439. ;
  99440. // Excluded Mesh
  99441. if (this._excludedMeshes.length) {
  99442. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  99443. }
  99444. ;
  99445. return true;
  99446. };
  99447. /**
  99448. * Free any resources and references associated to a mesh.
  99449. * Internal use
  99450. * @param mesh The mesh to free.
  99451. */
  99452. GlowLayer.prototype._disposeMesh = function (mesh) {
  99453. this.removeIncludedOnlyMesh(mesh);
  99454. this.removeExcludedMesh(mesh);
  99455. };
  99456. /**
  99457. * Gets the class name of the effect layer
  99458. * @returns the string with the class name of the effect layer
  99459. */
  99460. GlowLayer.prototype.getClassName = function () {
  99461. return "GlowLayer";
  99462. };
  99463. /**
  99464. * Serializes this glow layer
  99465. * @returns a serialized glow layer object
  99466. */
  99467. GlowLayer.prototype.serialize = function () {
  99468. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99469. serializationObject.customType = "BABYLON.GlowLayer";
  99470. var index;
  99471. // Included meshes
  99472. serializationObject.includedMeshes = [];
  99473. if (this._includedOnlyMeshes.length) {
  99474. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  99475. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  99476. if (mesh) {
  99477. serializationObject.includedMeshes.push(mesh.id);
  99478. }
  99479. }
  99480. }
  99481. // Excluded meshes
  99482. serializationObject.excludedMeshes = [];
  99483. if (this._excludedMeshes.length) {
  99484. for (index = 0; index < this._excludedMeshes.length; index++) {
  99485. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  99486. if (mesh) {
  99487. serializationObject.excludedMeshes.push(mesh.id);
  99488. }
  99489. }
  99490. }
  99491. return serializationObject;
  99492. };
  99493. /**
  99494. * Creates a Glow Layer from parsed glow layer data
  99495. * @param parsedGlowLayer defines glow layer data
  99496. * @param scene defines the current scene
  99497. * @param rootUrl defines the root URL containing the glow layer information
  99498. * @returns a parsed Glow Layer
  99499. */
  99500. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  99501. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  99502. var index;
  99503. // Excluded meshes
  99504. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  99505. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  99506. if (mesh) {
  99507. gl.addExcludedMesh(mesh);
  99508. }
  99509. }
  99510. // Included meshes
  99511. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  99512. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  99513. if (mesh) {
  99514. gl.addIncludedOnlyMesh(mesh);
  99515. }
  99516. }
  99517. return gl;
  99518. };
  99519. /**
  99520. * Effect Name of the layer.
  99521. */
  99522. GlowLayer.EffectName = "GlowLayer";
  99523. /**
  99524. * The default blur kernel size used for the glow.
  99525. */
  99526. GlowLayer.DefaultBlurKernelSize = 32;
  99527. /**
  99528. * The default texture size ratio used for the glow.
  99529. */
  99530. GlowLayer.DefaultTextureRatio = 0.5;
  99531. __decorate([
  99532. BABYLON.serialize()
  99533. ], GlowLayer.prototype, "blurKernelSize", null);
  99534. __decorate([
  99535. BABYLON.serialize()
  99536. ], GlowLayer.prototype, "intensity", null);
  99537. __decorate([
  99538. BABYLON.serialize("options")
  99539. ], GlowLayer.prototype, "_options", void 0);
  99540. return GlowLayer;
  99541. }(BABYLON.EffectLayer));
  99542. BABYLON.GlowLayer = GlowLayer;
  99543. })(BABYLON || (BABYLON = {}));
  99544. //# sourceMappingURL=babylon.glowLayer.js.map
  99545. var BABYLON;
  99546. (function (BABYLON) {
  99547. /**
  99548. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  99549. */
  99550. var AssetTaskState;
  99551. (function (AssetTaskState) {
  99552. /**
  99553. * Initialization
  99554. */
  99555. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  99556. /**
  99557. * Running
  99558. */
  99559. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  99560. /**
  99561. * Done
  99562. */
  99563. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  99564. /**
  99565. * Error
  99566. */
  99567. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  99568. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  99569. /**
  99570. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  99571. */
  99572. var AbstractAssetTask = /** @class */ (function () {
  99573. /**
  99574. * Creates a new {BABYLON.AssetsManager}
  99575. * @param name defines the name of the task
  99576. */
  99577. function AbstractAssetTask(
  99578. /**
  99579. * Task name
  99580. */ name) {
  99581. this.name = name;
  99582. this._isCompleted = false;
  99583. this._taskState = AssetTaskState.INIT;
  99584. }
  99585. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  99586. /**
  99587. * Get if the task is completed
  99588. */
  99589. get: function () {
  99590. return this._isCompleted;
  99591. },
  99592. enumerable: true,
  99593. configurable: true
  99594. });
  99595. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  99596. /**
  99597. * Gets the current state of the task
  99598. */
  99599. get: function () {
  99600. return this._taskState;
  99601. },
  99602. enumerable: true,
  99603. configurable: true
  99604. });
  99605. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  99606. /**
  99607. * Gets the current error object (if task is in error)
  99608. */
  99609. get: function () {
  99610. return this._errorObject;
  99611. },
  99612. enumerable: true,
  99613. configurable: true
  99614. });
  99615. /**
  99616. * Internal only
  99617. * @hidden
  99618. */
  99619. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  99620. if (this._errorObject) {
  99621. return;
  99622. }
  99623. this._errorObject = {
  99624. message: message,
  99625. exception: exception
  99626. };
  99627. };
  99628. /**
  99629. * Execute the current task
  99630. * @param scene defines the scene where you want your assets to be loaded
  99631. * @param onSuccess is a callback called when the task is successfully executed
  99632. * @param onError is a callback called if an error occurs
  99633. */
  99634. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  99635. var _this = this;
  99636. this._taskState = AssetTaskState.RUNNING;
  99637. this.runTask(scene, function () {
  99638. _this.onDoneCallback(onSuccess, onError);
  99639. }, function (msg, exception) {
  99640. _this.onErrorCallback(onError, msg, exception);
  99641. });
  99642. };
  99643. /**
  99644. * Execute the current task
  99645. * @param scene defines the scene where you want your assets to be loaded
  99646. * @param onSuccess is a callback called when the task is successfully executed
  99647. * @param onError is a callback called if an error occurs
  99648. */
  99649. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99650. throw new Error("runTask is not implemented");
  99651. };
  99652. /**
  99653. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  99654. * This can be used with failed tasks that have the reason for failure fixed.
  99655. */
  99656. AbstractAssetTask.prototype.reset = function () {
  99657. this._taskState = AssetTaskState.INIT;
  99658. };
  99659. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  99660. this._taskState = AssetTaskState.ERROR;
  99661. this._errorObject = {
  99662. message: message,
  99663. exception: exception
  99664. };
  99665. if (this.onError) {
  99666. this.onError(this, message, exception);
  99667. }
  99668. onError();
  99669. };
  99670. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  99671. try {
  99672. this._taskState = AssetTaskState.DONE;
  99673. this._isCompleted = true;
  99674. if (this.onSuccess) {
  99675. this.onSuccess(this);
  99676. }
  99677. onSuccess();
  99678. }
  99679. catch (e) {
  99680. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  99681. }
  99682. };
  99683. return AbstractAssetTask;
  99684. }());
  99685. BABYLON.AbstractAssetTask = AbstractAssetTask;
  99686. /**
  99687. * Class used to share progress information about assets loading
  99688. */
  99689. var AssetsProgressEvent = /** @class */ (function () {
  99690. /**
  99691. * Creates a {BABYLON.AssetsProgressEvent}
  99692. * @param remainingCount defines the number of remaining tasks to process
  99693. * @param totalCount defines the total number of tasks
  99694. * @param task defines the task that was just processed
  99695. */
  99696. function AssetsProgressEvent(remainingCount, totalCount, task) {
  99697. this.remainingCount = remainingCount;
  99698. this.totalCount = totalCount;
  99699. this.task = task;
  99700. }
  99701. return AssetsProgressEvent;
  99702. }());
  99703. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  99704. /**
  99705. * Define a task used by {BABYLON.AssetsManager} to load meshes
  99706. */
  99707. var MeshAssetTask = /** @class */ (function (_super) {
  99708. __extends(MeshAssetTask, _super);
  99709. /**
  99710. * Creates a new {BABYLON.MeshAssetTask}
  99711. * @param name defines the name of the task
  99712. * @param meshesNames defines the list of mesh's names you want to load
  99713. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  99714. * @param sceneFilename defines the filename of the scene to load from
  99715. */
  99716. function MeshAssetTask(
  99717. /**
  99718. * Defines the name of the task
  99719. */
  99720. name,
  99721. /**
  99722. * Defines the list of mesh's names you want to load
  99723. */
  99724. meshesNames,
  99725. /**
  99726. * Defines the root url to use as a base to load your meshes and associated resources
  99727. */
  99728. rootUrl,
  99729. /**
  99730. * Defines the filename of the scene to load from
  99731. */
  99732. sceneFilename) {
  99733. var _this = _super.call(this, name) || this;
  99734. _this.name = name;
  99735. _this.meshesNames = meshesNames;
  99736. _this.rootUrl = rootUrl;
  99737. _this.sceneFilename = sceneFilename;
  99738. return _this;
  99739. }
  99740. /**
  99741. * Execute the current task
  99742. * @param scene defines the scene where you want your assets to be loaded
  99743. * @param onSuccess is a callback called when the task is successfully executed
  99744. * @param onError is a callback called if an error occurs
  99745. */
  99746. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99747. var _this = this;
  99748. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  99749. _this.loadedMeshes = meshes;
  99750. _this.loadedParticleSystems = particleSystems;
  99751. _this.loadedSkeletons = skeletons;
  99752. onSuccess();
  99753. }, null, function (scene, message, exception) {
  99754. onError(message, exception);
  99755. });
  99756. };
  99757. return MeshAssetTask;
  99758. }(AbstractAssetTask));
  99759. BABYLON.MeshAssetTask = MeshAssetTask;
  99760. /**
  99761. * Define a task used by {BABYLON.AssetsManager} to load text content
  99762. */
  99763. var TextFileAssetTask = /** @class */ (function (_super) {
  99764. __extends(TextFileAssetTask, _super);
  99765. /**
  99766. * Creates a new TextFileAssetTask object
  99767. * @param name defines the name of the task
  99768. * @param url defines the location of the file to load
  99769. */
  99770. function TextFileAssetTask(
  99771. /**
  99772. * Defines the name of the task
  99773. */
  99774. name,
  99775. /**
  99776. * Defines the location of the file to load
  99777. */
  99778. url) {
  99779. var _this = _super.call(this, name) || this;
  99780. _this.name = name;
  99781. _this.url = url;
  99782. return _this;
  99783. }
  99784. /**
  99785. * Execute the current task
  99786. * @param scene defines the scene where you want your assets to be loaded
  99787. * @param onSuccess is a callback called when the task is successfully executed
  99788. * @param onError is a callback called if an error occurs
  99789. */
  99790. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99791. var _this = this;
  99792. scene._loadFile(this.url, function (data) {
  99793. _this.text = data;
  99794. onSuccess();
  99795. }, undefined, false, false, function (request, exception) {
  99796. if (request) {
  99797. onError(request.status + " " + request.statusText, exception);
  99798. }
  99799. });
  99800. };
  99801. return TextFileAssetTask;
  99802. }(AbstractAssetTask));
  99803. BABYLON.TextFileAssetTask = TextFileAssetTask;
  99804. /**
  99805. * Define a task used by {BABYLON.AssetsManager} to load binary data
  99806. */
  99807. var BinaryFileAssetTask = /** @class */ (function (_super) {
  99808. __extends(BinaryFileAssetTask, _super);
  99809. /**
  99810. * Creates a new BinaryFileAssetTask object
  99811. * @param name defines the name of the new task
  99812. * @param url defines the location of the file to load
  99813. */
  99814. function BinaryFileAssetTask(
  99815. /**
  99816. * Defines the name of the task
  99817. */
  99818. name,
  99819. /**
  99820. * Defines the location of the file to load
  99821. */
  99822. url) {
  99823. var _this = _super.call(this, name) || this;
  99824. _this.name = name;
  99825. _this.url = url;
  99826. return _this;
  99827. }
  99828. /**
  99829. * Execute the current task
  99830. * @param scene defines the scene where you want your assets to be loaded
  99831. * @param onSuccess is a callback called when the task is successfully executed
  99832. * @param onError is a callback called if an error occurs
  99833. */
  99834. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99835. var _this = this;
  99836. scene._loadFile(this.url, function (data) {
  99837. _this.data = data;
  99838. onSuccess();
  99839. }, undefined, true, true, function (request, exception) {
  99840. if (request) {
  99841. onError(request.status + " " + request.statusText, exception);
  99842. }
  99843. });
  99844. };
  99845. return BinaryFileAssetTask;
  99846. }(AbstractAssetTask));
  99847. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  99848. /**
  99849. * Define a task used by {BABYLON.AssetsManager} to load images
  99850. */
  99851. var ImageAssetTask = /** @class */ (function (_super) {
  99852. __extends(ImageAssetTask, _super);
  99853. /**
  99854. * Creates a new ImageAssetTask
  99855. * @param name defines the name of the task
  99856. * @param url defines the location of the image to load
  99857. */
  99858. function ImageAssetTask(
  99859. /**
  99860. * Defines the name of the task
  99861. */
  99862. name,
  99863. /**
  99864. * Defines the location of the image to load
  99865. */
  99866. url) {
  99867. var _this = _super.call(this, name) || this;
  99868. _this.name = name;
  99869. _this.url = url;
  99870. return _this;
  99871. }
  99872. /**
  99873. * Execute the current task
  99874. * @param scene defines the scene where you want your assets to be loaded
  99875. * @param onSuccess is a callback called when the task is successfully executed
  99876. * @param onError is a callback called if an error occurs
  99877. */
  99878. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99879. var _this = this;
  99880. var img = new Image();
  99881. BABYLON.Tools.SetCorsBehavior(this.url, img);
  99882. img.onload = function () {
  99883. _this.image = img;
  99884. onSuccess();
  99885. };
  99886. img.onerror = function (err) {
  99887. onError("Error loading image", err);
  99888. };
  99889. img.src = this.url;
  99890. };
  99891. return ImageAssetTask;
  99892. }(AbstractAssetTask));
  99893. BABYLON.ImageAssetTask = ImageAssetTask;
  99894. /**
  99895. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  99896. */
  99897. var TextureAssetTask = /** @class */ (function (_super) {
  99898. __extends(TextureAssetTask, _super);
  99899. /**
  99900. * Creates a new TextureAssetTask object
  99901. * @param name defines the name of the task
  99902. * @param url defines the location of the file to load
  99903. * @param noMipmap defines if mipmap should not be generated (default is false)
  99904. * @param invertY defines if texture must be inverted on Y axis (default is false)
  99905. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99906. */
  99907. function TextureAssetTask(
  99908. /**
  99909. * Defines the name of the task
  99910. */
  99911. name,
  99912. /**
  99913. * Defines the location of the file to load
  99914. */
  99915. url,
  99916. /**
  99917. * Defines if mipmap should not be generated (default is false)
  99918. */
  99919. noMipmap,
  99920. /**
  99921. * Defines if texture must be inverted on Y axis (default is false)
  99922. */
  99923. invertY,
  99924. /**
  99925. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99926. */
  99927. samplingMode) {
  99928. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99929. var _this = _super.call(this, name) || this;
  99930. _this.name = name;
  99931. _this.url = url;
  99932. _this.noMipmap = noMipmap;
  99933. _this.invertY = invertY;
  99934. _this.samplingMode = samplingMode;
  99935. return _this;
  99936. }
  99937. /**
  99938. * Execute the current task
  99939. * @param scene defines the scene where you want your assets to be loaded
  99940. * @param onSuccess is a callback called when the task is successfully executed
  99941. * @param onError is a callback called if an error occurs
  99942. */
  99943. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99944. var onload = function () {
  99945. onSuccess();
  99946. };
  99947. var onerror = function (message, exception) {
  99948. onError(message, exception);
  99949. };
  99950. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  99951. };
  99952. return TextureAssetTask;
  99953. }(AbstractAssetTask));
  99954. BABYLON.TextureAssetTask = TextureAssetTask;
  99955. /**
  99956. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  99957. */
  99958. var CubeTextureAssetTask = /** @class */ (function (_super) {
  99959. __extends(CubeTextureAssetTask, _super);
  99960. /**
  99961. * Creates a new CubeTextureAssetTask
  99962. * @param name defines the name of the task
  99963. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99964. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99965. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99966. * @param files defines the explicit list of files (undefined by default)
  99967. */
  99968. function CubeTextureAssetTask(
  99969. /**
  99970. * Defines the name of the task
  99971. */
  99972. name,
  99973. /**
  99974. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99975. */
  99976. url,
  99977. /**
  99978. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99979. */
  99980. extensions,
  99981. /**
  99982. * Defines if mipmaps should not be generated (default is false)
  99983. */
  99984. noMipmap,
  99985. /**
  99986. * Defines the explicit list of files (undefined by default)
  99987. */
  99988. files) {
  99989. var _this = _super.call(this, name) || this;
  99990. _this.name = name;
  99991. _this.url = url;
  99992. _this.extensions = extensions;
  99993. _this.noMipmap = noMipmap;
  99994. _this.files = files;
  99995. return _this;
  99996. }
  99997. /**
  99998. * Execute the current task
  99999. * @param scene defines the scene where you want your assets to be loaded
  100000. * @param onSuccess is a callback called when the task is successfully executed
  100001. * @param onError is a callback called if an error occurs
  100002. */
  100003. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100004. var onload = function () {
  100005. onSuccess();
  100006. };
  100007. var onerror = function (message, exception) {
  100008. onError(message, exception);
  100009. };
  100010. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  100011. };
  100012. return CubeTextureAssetTask;
  100013. }(AbstractAssetTask));
  100014. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  100015. /**
  100016. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  100017. */
  100018. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  100019. __extends(HDRCubeTextureAssetTask, _super);
  100020. /**
  100021. * Creates a new HDRCubeTextureAssetTask object
  100022. * @param name defines the name of the task
  100023. * @param url defines the location of the file to load
  100024. * @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.
  100025. * @param noMipmap defines if mipmaps should not be generated (default is false)
  100026. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  100027. * @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)
  100028. * @param reserved Internal use only
  100029. */
  100030. function HDRCubeTextureAssetTask(
  100031. /**
  100032. * Defines the name of the task
  100033. */
  100034. name,
  100035. /**
  100036. * Defines the location of the file to load
  100037. */
  100038. url,
  100039. /**
  100040. * Defines the desired size (the more it increases the longer the generation will be)
  100041. */
  100042. size,
  100043. /**
  100044. * Defines if mipmaps should not be generated (default is false)
  100045. */
  100046. noMipmap,
  100047. /**
  100048. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  100049. */
  100050. generateHarmonics,
  100051. /**
  100052. * 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)
  100053. */
  100054. gammaSpace,
  100055. /**
  100056. * Internal Use Only
  100057. */
  100058. reserved) {
  100059. if (noMipmap === void 0) { noMipmap = false; }
  100060. if (generateHarmonics === void 0) { generateHarmonics = true; }
  100061. if (gammaSpace === void 0) { gammaSpace = false; }
  100062. if (reserved === void 0) { reserved = false; }
  100063. var _this = _super.call(this, name) || this;
  100064. _this.name = name;
  100065. _this.url = url;
  100066. _this.size = size;
  100067. _this.noMipmap = noMipmap;
  100068. _this.generateHarmonics = generateHarmonics;
  100069. _this.gammaSpace = gammaSpace;
  100070. _this.reserved = reserved;
  100071. return _this;
  100072. }
  100073. /**
  100074. * Execute the current task
  100075. * @param scene defines the scene where you want your assets to be loaded
  100076. * @param onSuccess is a callback called when the task is successfully executed
  100077. * @param onError is a callback called if an error occurs
  100078. */
  100079. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  100080. var onload = function () {
  100081. onSuccess();
  100082. };
  100083. var onerror = function (message, exception) {
  100084. onError(message, exception);
  100085. };
  100086. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  100087. };
  100088. return HDRCubeTextureAssetTask;
  100089. }(AbstractAssetTask));
  100090. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  100091. /**
  100092. * This class can be used to easily import assets into a scene
  100093. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  100094. */
  100095. var AssetsManager = /** @class */ (function () {
  100096. /**
  100097. * Creates a new AssetsManager
  100098. * @param scene defines the scene to work on
  100099. */
  100100. function AssetsManager(scene) {
  100101. this._isLoading = false;
  100102. this._tasks = new Array();
  100103. this._waitingTasksCount = 0;
  100104. this._totalTasksCount = 0;
  100105. /**
  100106. * Observable called when all tasks are processed
  100107. */
  100108. this.onTaskSuccessObservable = new BABYLON.Observable();
  100109. /**
  100110. * Observable called when a task had an error
  100111. */
  100112. this.onTaskErrorObservable = new BABYLON.Observable();
  100113. /**
  100114. * Observable called when a task is successful
  100115. */
  100116. this.onTasksDoneObservable = new BABYLON.Observable();
  100117. /**
  100118. * Observable called when a task is done (whatever the result is)
  100119. */
  100120. this.onProgressObservable = new BABYLON.Observable();
  100121. /**
  100122. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  100123. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  100124. */
  100125. this.useDefaultLoadingScreen = true;
  100126. this._scene = scene;
  100127. }
  100128. /**
  100129. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  100130. * @param taskName defines the name of the new task
  100131. * @param meshesNames defines the name of meshes to load
  100132. * @param rootUrl defines the root url to use to locate files
  100133. * @param sceneFilename defines the filename of the scene file
  100134. * @returns a new {BABYLON.MeshAssetTask} object
  100135. */
  100136. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  100137. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  100138. this._tasks.push(task);
  100139. return task;
  100140. };
  100141. /**
  100142. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  100143. * @param taskName defines the name of the new task
  100144. * @param url defines the url of the file to load
  100145. * @returns a new {BABYLON.TextFileAssetTask} object
  100146. */
  100147. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  100148. var task = new TextFileAssetTask(taskName, url);
  100149. this._tasks.push(task);
  100150. return task;
  100151. };
  100152. /**
  100153. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  100154. * @param taskName defines the name of the new task
  100155. * @param url defines the url of the file to load
  100156. * @returns a new {BABYLON.BinaryFileAssetTask} object
  100157. */
  100158. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  100159. var task = new BinaryFileAssetTask(taskName, url);
  100160. this._tasks.push(task);
  100161. return task;
  100162. };
  100163. /**
  100164. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  100165. * @param taskName defines the name of the new task
  100166. * @param url defines the url of the file to load
  100167. * @returns a new {BABYLON.ImageAssetTask} object
  100168. */
  100169. AssetsManager.prototype.addImageTask = function (taskName, url) {
  100170. var task = new ImageAssetTask(taskName, url);
  100171. this._tasks.push(task);
  100172. return task;
  100173. };
  100174. /**
  100175. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  100176. * @param taskName defines the name of the new task
  100177. * @param url defines the url of the file to load
  100178. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  100179. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  100180. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  100181. * @returns a new {BABYLON.TextureAssetTask} object
  100182. */
  100183. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  100184. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100185. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  100186. this._tasks.push(task);
  100187. return task;
  100188. };
  100189. /**
  100190. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  100191. * @param taskName defines the name of the new task
  100192. * @param url defines the url of the file to load
  100193. * @param extensions defines the extension to use to load the cube map (can be null)
  100194. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  100195. * @param files defines the list of files to load (can be null)
  100196. * @returns a new {BABYLON.CubeTextureAssetTask} object
  100197. */
  100198. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  100199. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  100200. this._tasks.push(task);
  100201. return task;
  100202. };
  100203. /**
  100204. *
  100205. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  100206. * @param taskName defines the name of the new task
  100207. * @param url defines the url of the file to load
  100208. * @param size defines the size you want for the cubemap (can be null)
  100209. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  100210. * @param generateHarmonics defines if you want to automatically generate (true by default)
  100211. * @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)
  100212. * @param reserved Internal use only
  100213. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  100214. */
  100215. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  100216. if (noMipmap === void 0) { noMipmap = false; }
  100217. if (generateHarmonics === void 0) { generateHarmonics = true; }
  100218. if (gammaSpace === void 0) { gammaSpace = false; }
  100219. if (reserved === void 0) { reserved = false; }
  100220. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  100221. this._tasks.push(task);
  100222. return task;
  100223. };
  100224. /**
  100225. * Remove a task from the assets manager.
  100226. * @param task the task to remove
  100227. */
  100228. AssetsManager.prototype.removeTask = function (task) {
  100229. var index = this._tasks.indexOf(task);
  100230. if (index > -1) {
  100231. this._tasks.splice(index, 1);
  100232. }
  100233. };
  100234. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  100235. this._waitingTasksCount--;
  100236. try {
  100237. if (this.onProgress) {
  100238. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  100239. }
  100240. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  100241. }
  100242. catch (e) {
  100243. BABYLON.Tools.Error("Error running progress callbacks.");
  100244. console.log(e);
  100245. }
  100246. if (this._waitingTasksCount === 0) {
  100247. try {
  100248. if (this.onFinish) {
  100249. this.onFinish(this._tasks);
  100250. }
  100251. // Let's remove successfull tasks
  100252. var currentTasks = this._tasks.slice();
  100253. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  100254. var task = currentTasks_1[_i];
  100255. if (task.taskState === AssetTaskState.DONE) {
  100256. var index = this._tasks.indexOf(task);
  100257. if (index > -1) {
  100258. this._tasks.splice(index, 1);
  100259. }
  100260. }
  100261. }
  100262. this.onTasksDoneObservable.notifyObservers(this._tasks);
  100263. }
  100264. catch (e) {
  100265. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  100266. console.log(e);
  100267. }
  100268. this._isLoading = false;
  100269. this._scene.getEngine().hideLoadingUI();
  100270. }
  100271. };
  100272. AssetsManager.prototype._runTask = function (task) {
  100273. var _this = this;
  100274. var done = function () {
  100275. try {
  100276. if (_this.onTaskSuccess) {
  100277. _this.onTaskSuccess(task);
  100278. }
  100279. _this.onTaskSuccessObservable.notifyObservers(task);
  100280. _this._decreaseWaitingTasksCount(task);
  100281. }
  100282. catch (e) {
  100283. error("Error executing task success callbacks", e);
  100284. }
  100285. };
  100286. var error = function (message, exception) {
  100287. task._setErrorObject(message, exception);
  100288. if (_this.onTaskError) {
  100289. _this.onTaskError(task);
  100290. }
  100291. _this.onTaskErrorObservable.notifyObservers(task);
  100292. _this._decreaseWaitingTasksCount(task);
  100293. };
  100294. task.run(this._scene, done, error);
  100295. };
  100296. /**
  100297. * Reset the {BABYLON.AssetsManager} and remove all tasks
  100298. * @return the current instance of the {BABYLON.AssetsManager}
  100299. */
  100300. AssetsManager.prototype.reset = function () {
  100301. this._isLoading = false;
  100302. this._tasks = new Array();
  100303. return this;
  100304. };
  100305. /**
  100306. * Start the loading process
  100307. * @return the current instance of the {BABYLON.AssetsManager}
  100308. */
  100309. AssetsManager.prototype.load = function () {
  100310. if (this._isLoading) {
  100311. return this;
  100312. }
  100313. this._isLoading = true;
  100314. this._waitingTasksCount = this._tasks.length;
  100315. this._totalTasksCount = this._tasks.length;
  100316. if (this._waitingTasksCount === 0) {
  100317. this._isLoading = false;
  100318. if (this.onFinish) {
  100319. this.onFinish(this._tasks);
  100320. }
  100321. this.onTasksDoneObservable.notifyObservers(this._tasks);
  100322. return this;
  100323. }
  100324. if (this.useDefaultLoadingScreen) {
  100325. this._scene.getEngine().displayLoadingUI();
  100326. }
  100327. for (var index = 0; index < this._tasks.length; index++) {
  100328. var task = this._tasks[index];
  100329. if (task.taskState === AssetTaskState.INIT) {
  100330. this._runTask(task);
  100331. }
  100332. }
  100333. return this;
  100334. };
  100335. return AssetsManager;
  100336. }());
  100337. BABYLON.AssetsManager = AssetsManager;
  100338. })(BABYLON || (BABYLON = {}));
  100339. //# sourceMappingURL=babylon.assetsManager.js.map
  100340. var BABYLON;
  100341. (function (BABYLON) {
  100342. var serializedGeometries = [];
  100343. var serializeGeometry = function (geometry, serializationGeometries) {
  100344. if (serializedGeometries[geometry.id]) {
  100345. return;
  100346. }
  100347. if (geometry.doNotSerialize) {
  100348. return;
  100349. }
  100350. if (geometry instanceof BABYLON.BoxGeometry) {
  100351. serializationGeometries.boxes.push(geometry.serialize());
  100352. }
  100353. else if (geometry instanceof BABYLON.SphereGeometry) {
  100354. serializationGeometries.spheres.push(geometry.serialize());
  100355. }
  100356. else if (geometry instanceof BABYLON.CylinderGeometry) {
  100357. serializationGeometries.cylinders.push(geometry.serialize());
  100358. }
  100359. else if (geometry instanceof BABYLON.TorusGeometry) {
  100360. serializationGeometries.toruses.push(geometry.serialize());
  100361. }
  100362. else if (geometry instanceof BABYLON.GroundGeometry) {
  100363. serializationGeometries.grounds.push(geometry.serialize());
  100364. }
  100365. else if (geometry instanceof BABYLON.Plane) {
  100366. serializationGeometries.planes.push(geometry.serialize());
  100367. }
  100368. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  100369. serializationGeometries.torusKnots.push(geometry.serialize());
  100370. }
  100371. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  100372. throw new Error("Unknown primitive type");
  100373. }
  100374. else {
  100375. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  100376. }
  100377. serializedGeometries[geometry.id] = true;
  100378. };
  100379. var serializeMesh = function (mesh, serializationScene) {
  100380. var serializationObject = {};
  100381. // Geometry
  100382. var geometry = mesh._geometry;
  100383. if (geometry) {
  100384. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  100385. // 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
  100386. serializeGeometry(geometry, serializationScene.geometries);
  100387. }
  100388. }
  100389. // Custom
  100390. if (mesh.serialize) {
  100391. mesh.serialize(serializationObject);
  100392. }
  100393. return serializationObject;
  100394. };
  100395. var finalizeSingleMesh = function (mesh, serializationObject) {
  100396. //only works if the mesh is already loaded
  100397. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  100398. //serialize material
  100399. if (mesh.material) {
  100400. if (mesh.material instanceof BABYLON.MultiMaterial) {
  100401. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  100402. serializationObject.materials = serializationObject.materials || [];
  100403. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  100404. serializationObject.multiMaterials.push(mesh.material.serialize());
  100405. var _loop_1 = function (submaterial) {
  100406. if (submaterial) {
  100407. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  100408. serializationObject.materials.push(submaterial.serialize());
  100409. }
  100410. }
  100411. };
  100412. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  100413. var submaterial = _a[_i];
  100414. _loop_1(submaterial);
  100415. }
  100416. }
  100417. }
  100418. else {
  100419. serializationObject.materials = serializationObject.materials || [];
  100420. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  100421. serializationObject.materials.push(mesh.material.serialize());
  100422. }
  100423. }
  100424. }
  100425. //serialize geometry
  100426. var geometry = mesh._geometry;
  100427. if (geometry) {
  100428. if (!serializationObject.geometries) {
  100429. serializationObject.geometries = {};
  100430. serializationObject.geometries.boxes = [];
  100431. serializationObject.geometries.spheres = [];
  100432. serializationObject.geometries.cylinders = [];
  100433. serializationObject.geometries.toruses = [];
  100434. serializationObject.geometries.grounds = [];
  100435. serializationObject.geometries.planes = [];
  100436. serializationObject.geometries.torusKnots = [];
  100437. serializationObject.geometries.vertexData = [];
  100438. }
  100439. serializeGeometry(geometry, serializationObject.geometries);
  100440. }
  100441. // Skeletons
  100442. if (mesh.skeleton) {
  100443. serializationObject.skeletons = serializationObject.skeletons || [];
  100444. serializationObject.skeletons.push(mesh.skeleton.serialize());
  100445. }
  100446. //serialize the actual mesh
  100447. serializationObject.meshes = serializationObject.meshes || [];
  100448. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  100449. }
  100450. };
  100451. var SceneSerializer = /** @class */ (function () {
  100452. function SceneSerializer() {
  100453. }
  100454. SceneSerializer.ClearCache = function () {
  100455. serializedGeometries = [];
  100456. };
  100457. SceneSerializer.Serialize = function (scene) {
  100458. var serializationObject = {};
  100459. SceneSerializer.ClearCache();
  100460. // Scene
  100461. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  100462. serializationObject.autoClear = scene.autoClear;
  100463. serializationObject.clearColor = scene.clearColor.asArray();
  100464. serializationObject.ambientColor = scene.ambientColor.asArray();
  100465. serializationObject.gravity = scene.gravity.asArray();
  100466. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  100467. serializationObject.workerCollisions = scene.workerCollisions;
  100468. // Fog
  100469. if (scene.fogMode && scene.fogMode !== 0) {
  100470. serializationObject.fogMode = scene.fogMode;
  100471. serializationObject.fogColor = scene.fogColor.asArray();
  100472. serializationObject.fogStart = scene.fogStart;
  100473. serializationObject.fogEnd = scene.fogEnd;
  100474. serializationObject.fogDensity = scene.fogDensity;
  100475. }
  100476. //Physics
  100477. if (scene.isPhysicsEnabled()) {
  100478. var physicEngine = scene.getPhysicsEngine();
  100479. if (physicEngine) {
  100480. serializationObject.physicsEnabled = true;
  100481. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  100482. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  100483. }
  100484. }
  100485. // Metadata
  100486. if (scene.metadata) {
  100487. serializationObject.metadata = scene.metadata;
  100488. }
  100489. // Morph targets
  100490. serializationObject.morphTargetManagers = [];
  100491. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  100492. var abstractMesh = _a[_i];
  100493. var manager = abstractMesh.morphTargetManager;
  100494. if (manager) {
  100495. serializationObject.morphTargetManagers.push(manager.serialize());
  100496. }
  100497. }
  100498. // Lights
  100499. serializationObject.lights = [];
  100500. var index;
  100501. var light;
  100502. for (index = 0; index < scene.lights.length; index++) {
  100503. light = scene.lights[index];
  100504. if (!light.doNotSerialize) {
  100505. serializationObject.lights.push(light.serialize());
  100506. }
  100507. }
  100508. // Cameras
  100509. serializationObject.cameras = [];
  100510. for (index = 0; index < scene.cameras.length; index++) {
  100511. var camera = scene.cameras[index];
  100512. if (!camera.doNotSerialize) {
  100513. serializationObject.cameras.push(camera.serialize());
  100514. }
  100515. }
  100516. if (scene.activeCamera) {
  100517. serializationObject.activeCameraID = scene.activeCamera.id;
  100518. }
  100519. // Animations
  100520. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  100521. // Materials
  100522. serializationObject.materials = [];
  100523. serializationObject.multiMaterials = [];
  100524. var material;
  100525. for (index = 0; index < scene.materials.length; index++) {
  100526. material = scene.materials[index];
  100527. if (!material.doNotSerialize) {
  100528. serializationObject.materials.push(material.serialize());
  100529. }
  100530. }
  100531. // MultiMaterials
  100532. serializationObject.multiMaterials = [];
  100533. for (index = 0; index < scene.multiMaterials.length; index++) {
  100534. var multiMaterial = scene.multiMaterials[index];
  100535. serializationObject.multiMaterials.push(multiMaterial.serialize());
  100536. }
  100537. // Environment texture
  100538. if (scene.environmentTexture) {
  100539. serializationObject.environmentTexture = scene.environmentTexture.name;
  100540. }
  100541. // Skeletons
  100542. serializationObject.skeletons = [];
  100543. for (index = 0; index < scene.skeletons.length; index++) {
  100544. var skeleton = scene.skeletons[index];
  100545. if (!skeleton.doNotSerialize) {
  100546. serializationObject.skeletons.push(skeleton.serialize());
  100547. }
  100548. }
  100549. // Transform nodes
  100550. serializationObject.transformNodes = [];
  100551. for (index = 0; index < scene.transformNodes.length; index++) {
  100552. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  100553. }
  100554. // Geometries
  100555. serializationObject.geometries = {};
  100556. serializationObject.geometries.boxes = [];
  100557. serializationObject.geometries.spheres = [];
  100558. serializationObject.geometries.cylinders = [];
  100559. serializationObject.geometries.toruses = [];
  100560. serializationObject.geometries.grounds = [];
  100561. serializationObject.geometries.planes = [];
  100562. serializationObject.geometries.torusKnots = [];
  100563. serializationObject.geometries.vertexData = [];
  100564. serializedGeometries = [];
  100565. var geometries = scene.getGeometries();
  100566. for (index = 0; index < geometries.length; index++) {
  100567. var geometry = geometries[index];
  100568. if (geometry.isReady()) {
  100569. serializeGeometry(geometry, serializationObject.geometries);
  100570. }
  100571. }
  100572. // Meshes
  100573. serializationObject.meshes = [];
  100574. for (index = 0; index < scene.meshes.length; index++) {
  100575. var abstractMesh = scene.meshes[index];
  100576. if (abstractMesh instanceof BABYLON.Mesh) {
  100577. var mesh = abstractMesh;
  100578. if (!mesh.doNotSerialize) {
  100579. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  100580. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  100581. }
  100582. }
  100583. }
  100584. }
  100585. // Particles Systems
  100586. serializationObject.particleSystems = [];
  100587. for (index = 0; index < scene.particleSystems.length; index++) {
  100588. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  100589. }
  100590. // Shadows
  100591. serializationObject.shadowGenerators = [];
  100592. for (index = 0; index < scene.lights.length; index++) {
  100593. light = scene.lights[index];
  100594. var shadowGenerator = light.getShadowGenerator();
  100595. if (shadowGenerator) {
  100596. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  100597. }
  100598. }
  100599. // Action Manager
  100600. if (scene.actionManager) {
  100601. serializationObject.actions = scene.actionManager.serialize("scene");
  100602. }
  100603. // Audio
  100604. serializationObject.sounds = [];
  100605. for (index = 0; index < scene.soundTracks.length; index++) {
  100606. var soundtrack = scene.soundTracks[index];
  100607. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  100608. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  100609. }
  100610. }
  100611. // Components
  100612. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  100613. var component = _c[_b];
  100614. component.serialize(serializationObject);
  100615. }
  100616. return serializationObject;
  100617. };
  100618. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  100619. if (withParents === void 0) { withParents = false; }
  100620. if (withChildren === void 0) { withChildren = false; }
  100621. var serializationObject = {};
  100622. SceneSerializer.ClearCache();
  100623. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  100624. if (withParents || withChildren) {
  100625. //deliberate for loop! not for each, appended should be processed as well.
  100626. for (var i = 0; i < toSerialize.length; ++i) {
  100627. if (withChildren) {
  100628. toSerialize[i].getDescendants().forEach(function (node) {
  100629. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  100630. toSerialize.push(node);
  100631. }
  100632. });
  100633. }
  100634. //make sure the array doesn't contain the object already
  100635. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  100636. toSerialize.push(toSerialize[i].parent);
  100637. }
  100638. }
  100639. }
  100640. toSerialize.forEach(function (mesh) {
  100641. finalizeSingleMesh(mesh, serializationObject);
  100642. });
  100643. return serializationObject;
  100644. };
  100645. return SceneSerializer;
  100646. }());
  100647. BABYLON.SceneSerializer = SceneSerializer;
  100648. })(BABYLON || (BABYLON = {}));
  100649. //# sourceMappingURL=babylon.sceneSerializer.js.map
  100650. var BABYLON;
  100651. (function (BABYLON) {
  100652. /**
  100653. * Class used to generate realtime reflection / refraction cube textures
  100654. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  100655. */
  100656. var ReflectionProbe = /** @class */ (function () {
  100657. /**
  100658. * Creates a new reflection probe
  100659. * @param name defines the name of the probe
  100660. * @param size defines the texture resolution (for each face)
  100661. * @param scene defines the hosting scene
  100662. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  100663. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  100664. */
  100665. function ReflectionProbe(
  100666. /** defines the name of the probe */
  100667. name, size, scene, generateMipMaps, useFloat) {
  100668. if (generateMipMaps === void 0) { generateMipMaps = true; }
  100669. if (useFloat === void 0) { useFloat = false; }
  100670. var _this = this;
  100671. this.name = name;
  100672. this._viewMatrix = BABYLON.Matrix.Identity();
  100673. this._target = BABYLON.Vector3.Zero();
  100674. this._add = BABYLON.Vector3.Zero();
  100675. this._invertYAxis = false;
  100676. /** Gets or sets probe position (center of the cube map) */
  100677. this.position = BABYLON.Vector3.Zero();
  100678. this._scene = scene;
  100679. this._scene.reflectionProbes.push(this);
  100680. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  100681. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  100682. switch (faceIndex) {
  100683. case 0:
  100684. _this._add.copyFromFloats(1, 0, 0);
  100685. break;
  100686. case 1:
  100687. _this._add.copyFromFloats(-1, 0, 0);
  100688. break;
  100689. case 2:
  100690. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  100691. break;
  100692. case 3:
  100693. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  100694. break;
  100695. case 4:
  100696. _this._add.copyFromFloats(0, 0, 1);
  100697. break;
  100698. case 5:
  100699. _this._add.copyFromFloats(0, 0, -1);
  100700. break;
  100701. }
  100702. if (_this._attachedMesh) {
  100703. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  100704. }
  100705. _this.position.addToRef(_this._add, _this._target);
  100706. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  100707. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  100708. scene._forcedViewPosition = _this.position;
  100709. });
  100710. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  100711. scene._forcedViewPosition = null;
  100712. scene.updateTransformMatrix(true);
  100713. });
  100714. if (scene.activeCamera) {
  100715. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  100716. }
  100717. }
  100718. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  100719. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  100720. get: function () {
  100721. return this._renderTargetTexture.samples;
  100722. },
  100723. set: function (value) {
  100724. this._renderTargetTexture.samples = value;
  100725. },
  100726. enumerable: true,
  100727. configurable: true
  100728. });
  100729. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  100730. /** Gets or sets the refresh rate to use (on every frame by default) */
  100731. get: function () {
  100732. return this._renderTargetTexture.refreshRate;
  100733. },
  100734. set: function (value) {
  100735. this._renderTargetTexture.refreshRate = value;
  100736. },
  100737. enumerable: true,
  100738. configurable: true
  100739. });
  100740. /**
  100741. * Gets the hosting scene
  100742. * @returns a Scene
  100743. */
  100744. ReflectionProbe.prototype.getScene = function () {
  100745. return this._scene;
  100746. };
  100747. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  100748. /** Gets the internal CubeTexture used to render to */
  100749. get: function () {
  100750. return this._renderTargetTexture;
  100751. },
  100752. enumerable: true,
  100753. configurable: true
  100754. });
  100755. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  100756. /** Gets the list of meshes to render */
  100757. get: function () {
  100758. return this._renderTargetTexture.renderList;
  100759. },
  100760. enumerable: true,
  100761. configurable: true
  100762. });
  100763. /**
  100764. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  100765. * @param mesh defines the mesh to attach to
  100766. */
  100767. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  100768. this._attachedMesh = mesh;
  100769. };
  100770. /**
  100771. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  100772. * @param renderingGroupId The rendering group id corresponding to its index
  100773. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  100774. */
  100775. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  100776. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  100777. };
  100778. /**
  100779. * Clean all associated resources
  100780. */
  100781. ReflectionProbe.prototype.dispose = function () {
  100782. var index = this._scene.reflectionProbes.indexOf(this);
  100783. if (index !== -1) {
  100784. // Remove from the scene if found
  100785. this._scene.reflectionProbes.splice(index, 1);
  100786. }
  100787. if (this._renderTargetTexture) {
  100788. this._renderTargetTexture.dispose();
  100789. this._renderTargetTexture = null;
  100790. }
  100791. };
  100792. return ReflectionProbe;
  100793. }());
  100794. BABYLON.ReflectionProbe = ReflectionProbe;
  100795. })(BABYLON || (BABYLON = {}));
  100796. //# sourceMappingURL=babylon.reflectionProbe.js.map
  100797. var BABYLON;
  100798. (function (BABYLON) {
  100799. /**
  100800. * Defines the layer scene component responsible to manage any layers
  100801. * in a given scene.
  100802. */
  100803. var LayerSceneComponent = /** @class */ (function () {
  100804. /**
  100805. * Creates a new instance of the component for the given scene
  100806. * @param scene Defines the scene to register the component in
  100807. */
  100808. function LayerSceneComponent(scene) {
  100809. /**
  100810. * The component name helpfull to identify the component in the list of scene components.
  100811. */
  100812. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  100813. this.scene = scene;
  100814. this._engine = scene.getEngine();
  100815. scene.layers = new Array();
  100816. }
  100817. /**
  100818. * Registers the component in a given scene
  100819. */
  100820. LayerSceneComponent.prototype.register = function () {
  100821. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  100822. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  100823. };
  100824. /**
  100825. * Rebuilds the elements related to this component in case of
  100826. * context lost for instance.
  100827. */
  100828. LayerSceneComponent.prototype.rebuild = function () {
  100829. var layers = this.scene.layers;
  100830. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  100831. var layer = layers_1[_i];
  100832. layer._rebuild();
  100833. }
  100834. };
  100835. /**
  100836. * Disposes the component and the associated ressources.
  100837. */
  100838. LayerSceneComponent.prototype.dispose = function () {
  100839. var layers = this.scene.layers;
  100840. while (layers.length) {
  100841. layers[0].dispose();
  100842. }
  100843. };
  100844. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  100845. var layers = this.scene.layers;
  100846. if (layers.length) {
  100847. this._engine.setDepthBuffer(false);
  100848. var cameraLayerMask = camera.layerMask;
  100849. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  100850. var layer = layers_2[_i];
  100851. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  100852. layer.render();
  100853. }
  100854. }
  100855. this._engine.setDepthBuffer(true);
  100856. }
  100857. };
  100858. LayerSceneComponent.prototype._drawBackground = function (camera) {
  100859. this._draw(camera, true);
  100860. };
  100861. LayerSceneComponent.prototype._drawForeground = function (camera) {
  100862. this._draw(camera, false);
  100863. };
  100864. return LayerSceneComponent;
  100865. }());
  100866. BABYLON.LayerSceneComponent = LayerSceneComponent;
  100867. })(BABYLON || (BABYLON = {}));
  100868. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  100869. var BABYLON;
  100870. (function (BABYLON) {
  100871. var Layer = /** @class */ (function () {
  100872. function Layer(name, imgUrl, scene, isBackground, color) {
  100873. this.name = name;
  100874. this.scale = new BABYLON.Vector2(1, 1);
  100875. this.offset = new BABYLON.Vector2(0, 0);
  100876. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  100877. this.layerMask = 0x0FFFFFFF;
  100878. this._vertexBuffers = {};
  100879. // Events
  100880. /**
  100881. * An event triggered when the layer is disposed.
  100882. */
  100883. this.onDisposeObservable = new BABYLON.Observable();
  100884. /**
  100885. * An event triggered before rendering the scene
  100886. */
  100887. this.onBeforeRenderObservable = new BABYLON.Observable();
  100888. /**
  100889. * An event triggered after rendering the scene
  100890. */
  100891. this.onAfterRenderObservable = new BABYLON.Observable();
  100892. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  100893. this.isBackground = isBackground === undefined ? true : isBackground;
  100894. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  100895. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  100896. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  100897. if (!layerComponent) {
  100898. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  100899. this._scene._addComponent(layerComponent);
  100900. }
  100901. this._scene.layers.push(this);
  100902. var engine = this._scene.getEngine();
  100903. // VBO
  100904. var vertices = [];
  100905. vertices.push(1, 1);
  100906. vertices.push(-1, 1);
  100907. vertices.push(-1, -1);
  100908. vertices.push(1, -1);
  100909. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  100910. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  100911. this._createIndexBuffer();
  100912. // Effects
  100913. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  100914. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  100915. }
  100916. Object.defineProperty(Layer.prototype, "onDispose", {
  100917. set: function (callback) {
  100918. if (this._onDisposeObserver) {
  100919. this.onDisposeObservable.remove(this._onDisposeObserver);
  100920. }
  100921. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  100922. },
  100923. enumerable: true,
  100924. configurable: true
  100925. });
  100926. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  100927. set: function (callback) {
  100928. if (this._onBeforeRenderObserver) {
  100929. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  100930. }
  100931. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  100932. },
  100933. enumerable: true,
  100934. configurable: true
  100935. });
  100936. Object.defineProperty(Layer.prototype, "onAfterRender", {
  100937. set: function (callback) {
  100938. if (this._onAfterRenderObserver) {
  100939. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100940. }
  100941. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  100942. },
  100943. enumerable: true,
  100944. configurable: true
  100945. });
  100946. Layer.prototype._createIndexBuffer = function () {
  100947. var engine = this._scene.getEngine();
  100948. // Indices
  100949. var indices = [];
  100950. indices.push(0);
  100951. indices.push(1);
  100952. indices.push(2);
  100953. indices.push(0);
  100954. indices.push(2);
  100955. indices.push(3);
  100956. this._indexBuffer = engine.createIndexBuffer(indices);
  100957. };
  100958. Layer.prototype._rebuild = function () {
  100959. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100960. if (vb) {
  100961. vb._rebuild();
  100962. }
  100963. this._createIndexBuffer();
  100964. };
  100965. Layer.prototype.render = function () {
  100966. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  100967. // Check
  100968. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  100969. return;
  100970. var engine = this._scene.getEngine();
  100971. this.onBeforeRenderObservable.notifyObservers(this);
  100972. // Render
  100973. engine.enableEffect(currentEffect);
  100974. engine.setState(false);
  100975. // Texture
  100976. currentEffect.setTexture("textureSampler", this.texture);
  100977. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  100978. // Color
  100979. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  100980. // Scale / offset
  100981. currentEffect.setVector2("offset", this.offset);
  100982. currentEffect.setVector2("scale", this.scale);
  100983. // VBOs
  100984. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  100985. // Draw order
  100986. if (!this.alphaTest) {
  100987. engine.setAlphaMode(this.alphaBlendingMode);
  100988. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100989. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  100990. }
  100991. else {
  100992. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100993. }
  100994. this.onAfterRenderObservable.notifyObservers(this);
  100995. };
  100996. Layer.prototype.dispose = function () {
  100997. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100998. if (vertexBuffer) {
  100999. vertexBuffer.dispose();
  101000. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  101001. }
  101002. if (this._indexBuffer) {
  101003. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  101004. this._indexBuffer = null;
  101005. }
  101006. if (this.texture) {
  101007. this.texture.dispose();
  101008. this.texture = null;
  101009. }
  101010. // Remove from scene
  101011. var index = this._scene.layers.indexOf(this);
  101012. this._scene.layers.splice(index, 1);
  101013. // Callback
  101014. this.onDisposeObservable.notifyObservers(this);
  101015. this.onDisposeObservable.clear();
  101016. this.onAfterRenderObservable.clear();
  101017. this.onBeforeRenderObservable.clear();
  101018. };
  101019. return Layer;
  101020. }());
  101021. BABYLON.Layer = Layer;
  101022. })(BABYLON || (BABYLON = {}));
  101023. //# sourceMappingURL=babylon.layer.js.map
  101024. var BABYLON;
  101025. (function (BABYLON) {
  101026. var TextureTools = /** @class */ (function () {
  101027. function TextureTools() {
  101028. }
  101029. /**
  101030. * Uses the GPU to create a copy texture rescaled at a given size
  101031. * @param texture Texture to copy from
  101032. * @param width Desired width
  101033. * @param height Desired height
  101034. * @return Generated texture
  101035. */
  101036. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  101037. if (useBilinearMode === void 0) { useBilinearMode = true; }
  101038. var scene = texture.getScene();
  101039. var engine = scene.getEngine();
  101040. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  101041. rtt.wrapU = texture.wrapU;
  101042. rtt.wrapV = texture.wrapV;
  101043. rtt.uOffset = texture.uOffset;
  101044. rtt.vOffset = texture.vOffset;
  101045. rtt.uScale = texture.uScale;
  101046. rtt.vScale = texture.vScale;
  101047. rtt.uAng = texture.uAng;
  101048. rtt.vAng = texture.vAng;
  101049. rtt.wAng = texture.wAng;
  101050. rtt.coordinatesIndex = texture.coordinatesIndex;
  101051. rtt.level = texture.level;
  101052. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  101053. rtt._texture.isReady = false;
  101054. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101055. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101056. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  101057. passPostProcess.getEffect().executeWhenCompiled(function () {
  101058. passPostProcess.onApply = function (effect) {
  101059. effect.setTexture("textureSampler", texture);
  101060. };
  101061. var internalTexture = rtt.getInternalTexture();
  101062. if (internalTexture) {
  101063. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  101064. engine.unBindFramebuffer(internalTexture);
  101065. rtt.disposeFramebufferObjects();
  101066. passPostProcess.dispose();
  101067. internalTexture.isReady = true;
  101068. }
  101069. });
  101070. return rtt;
  101071. };
  101072. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  101073. if (!scene._environmentBRDFTexture) {
  101074. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101075. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101076. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101077. scene._environmentBRDFTexture = texture;
  101078. }
  101079. return scene._environmentBRDFTexture;
  101080. };
  101081. 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=";
  101082. return TextureTools;
  101083. }());
  101084. BABYLON.TextureTools = TextureTools;
  101085. })(BABYLON || (BABYLON = {}));
  101086. //# sourceMappingURL=babylon.textureTools.js.map
  101087. var BABYLON;
  101088. (function (BABYLON) {
  101089. var FramingBehavior = /** @class */ (function () {
  101090. function FramingBehavior() {
  101091. this._mode = FramingBehavior.FitFrustumSidesMode;
  101092. this._radiusScale = 1.0;
  101093. this._positionScale = 0.5;
  101094. this._defaultElevation = 0.3;
  101095. this._elevationReturnTime = 1500;
  101096. this._elevationReturnWaitTime = 1000;
  101097. this._zoomStopsAnimation = false;
  101098. this._framingTime = 1500;
  101099. this._isPointerDown = false;
  101100. this._lastInteractionTime = -Infinity;
  101101. // Framing control
  101102. this._animatables = new Array();
  101103. this._betaIsAnimating = false;
  101104. }
  101105. Object.defineProperty(FramingBehavior.prototype, "name", {
  101106. get: function () {
  101107. return "Framing";
  101108. },
  101109. enumerable: true,
  101110. configurable: true
  101111. });
  101112. Object.defineProperty(FramingBehavior.prototype, "mode", {
  101113. /**
  101114. * Gets current mode used by the behavior.
  101115. */
  101116. get: function () {
  101117. return this._mode;
  101118. },
  101119. /**
  101120. * Sets the current mode used by the behavior
  101121. */
  101122. set: function (mode) {
  101123. this._mode = mode;
  101124. },
  101125. enumerable: true,
  101126. configurable: true
  101127. });
  101128. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  101129. /**
  101130. * Gets the scale applied to the radius
  101131. */
  101132. get: function () {
  101133. return this._radiusScale;
  101134. },
  101135. /**
  101136. * Sets the scale applied to the radius (1 by default)
  101137. */
  101138. set: function (radius) {
  101139. this._radiusScale = radius;
  101140. },
  101141. enumerable: true,
  101142. configurable: true
  101143. });
  101144. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  101145. /**
  101146. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  101147. */
  101148. get: function () {
  101149. return this._positionScale;
  101150. },
  101151. /**
  101152. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  101153. */
  101154. set: function (scale) {
  101155. this._positionScale = scale;
  101156. },
  101157. enumerable: true,
  101158. configurable: true
  101159. });
  101160. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  101161. /**
  101162. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  101163. * behaviour is triggered, in radians.
  101164. */
  101165. get: function () {
  101166. return this._defaultElevation;
  101167. },
  101168. /**
  101169. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  101170. * behaviour is triggered, in radians.
  101171. */
  101172. set: function (elevation) {
  101173. this._defaultElevation = elevation;
  101174. },
  101175. enumerable: true,
  101176. configurable: true
  101177. });
  101178. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  101179. /**
  101180. * Gets the time (in milliseconds) taken to return to the default beta position.
  101181. * Negative value indicates camera should not return to default.
  101182. */
  101183. get: function () {
  101184. return this._elevationReturnTime;
  101185. },
  101186. /**
  101187. * Sets the time (in milliseconds) taken to return to the default beta position.
  101188. * Negative value indicates camera should not return to default.
  101189. */
  101190. set: function (speed) {
  101191. this._elevationReturnTime = speed;
  101192. },
  101193. enumerable: true,
  101194. configurable: true
  101195. });
  101196. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  101197. /**
  101198. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  101199. */
  101200. get: function () {
  101201. return this._elevationReturnWaitTime;
  101202. },
  101203. /**
  101204. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  101205. */
  101206. set: function (time) {
  101207. this._elevationReturnWaitTime = time;
  101208. },
  101209. enumerable: true,
  101210. configurable: true
  101211. });
  101212. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  101213. /**
  101214. * Gets the flag that indicates if user zooming should stop animation.
  101215. */
  101216. get: function () {
  101217. return this._zoomStopsAnimation;
  101218. },
  101219. /**
  101220. * Sets the flag that indicates if user zooming should stop animation.
  101221. */
  101222. set: function (flag) {
  101223. this._zoomStopsAnimation = flag;
  101224. },
  101225. enumerable: true,
  101226. configurable: true
  101227. });
  101228. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  101229. /**
  101230. * Gets the transition time when framing the mesh, in milliseconds
  101231. */
  101232. get: function () {
  101233. return this._framingTime;
  101234. },
  101235. /**
  101236. * Sets the transition time when framing the mesh, in milliseconds
  101237. */
  101238. set: function (time) {
  101239. this._framingTime = time;
  101240. },
  101241. enumerable: true,
  101242. configurable: true
  101243. });
  101244. FramingBehavior.prototype.init = function () {
  101245. // Do notihng
  101246. };
  101247. FramingBehavior.prototype.attach = function (camera) {
  101248. var _this = this;
  101249. this._attachedCamera = camera;
  101250. var scene = this._attachedCamera.getScene();
  101251. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  101252. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  101253. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  101254. _this._isPointerDown = true;
  101255. return;
  101256. }
  101257. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  101258. _this._isPointerDown = false;
  101259. }
  101260. });
  101261. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  101262. if (mesh) {
  101263. _this.zoomOnMesh(mesh);
  101264. }
  101265. });
  101266. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101267. // Stop the animation if there is user interaction and the animation should stop for this interaction
  101268. _this._applyUserInteraction();
  101269. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  101270. // back to the default position after a given timeout
  101271. _this._maintainCameraAboveGround();
  101272. });
  101273. };
  101274. FramingBehavior.prototype.detach = function () {
  101275. if (!this._attachedCamera) {
  101276. return;
  101277. }
  101278. var scene = this._attachedCamera.getScene();
  101279. if (this._onPrePointerObservableObserver) {
  101280. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  101281. }
  101282. if (this._onAfterCheckInputsObserver) {
  101283. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101284. }
  101285. if (this._onMeshTargetChangedObserver) {
  101286. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  101287. }
  101288. this._attachedCamera = null;
  101289. };
  101290. /**
  101291. * Targets the given mesh and updates zoom level accordingly.
  101292. * @param mesh The mesh to target.
  101293. * @param radius Optional. If a cached radius position already exists, overrides default.
  101294. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101295. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101296. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101297. */
  101298. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  101299. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101300. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101301. mesh.computeWorldMatrix(true);
  101302. var boundingBox = mesh.getBoundingInfo().boundingBox;
  101303. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  101304. };
  101305. /**
  101306. * Targets the given mesh with its children and updates zoom level accordingly.
  101307. * @param mesh The mesh to target.
  101308. * @param radius Optional. If a cached radius position already exists, overrides default.
  101309. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101310. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101311. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101312. */
  101313. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  101314. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101315. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101316. mesh.computeWorldMatrix(true);
  101317. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  101318. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  101319. };
  101320. /**
  101321. * Targets the given meshes with their children and updates zoom level accordingly.
  101322. * @param meshes The mesh to target.
  101323. * @param radius Optional. If a cached radius position already exists, overrides default.
  101324. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101325. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101326. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101327. */
  101328. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  101329. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101330. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101331. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  101332. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  101333. for (var i = 0; i < meshes.length; i++) {
  101334. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  101335. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  101336. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  101337. }
  101338. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  101339. };
  101340. /**
  101341. * Targets the given mesh and updates zoom level accordingly.
  101342. * @param mesh The mesh to target.
  101343. * @param radius Optional. If a cached radius position already exists, overrides default.
  101344. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101345. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101346. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101347. */
  101348. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  101349. var _this = this;
  101350. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101351. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101352. var zoomTarget;
  101353. if (!this._attachedCamera) {
  101354. return;
  101355. }
  101356. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  101357. var bottom = minimumWorld.y;
  101358. var top = maximumWorld.y;
  101359. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  101360. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  101361. if (focusOnOriginXZ) {
  101362. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  101363. }
  101364. else {
  101365. var centerWorld = minimumWorld.add(radiusWorld);
  101366. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  101367. }
  101368. if (!this._vectorTransition) {
  101369. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  101370. }
  101371. this._betaIsAnimating = true;
  101372. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  101373. if (animatable) {
  101374. this._animatables.push(animatable);
  101375. }
  101376. // sets the radius and lower radius bounds
  101377. // Small delta ensures camera is not always at lower zoom limit.
  101378. var radius = 0;
  101379. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  101380. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  101381. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  101382. radius = position;
  101383. }
  101384. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  101385. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  101386. if (this._attachedCamera.lowerRadiusLimit === null) {
  101387. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  101388. }
  101389. }
  101390. // Set sensibilities
  101391. var extend = maximumWorld.subtract(minimumWorld).length();
  101392. this._attachedCamera.panningSensibility = 5000 / extend;
  101393. this._attachedCamera.wheelPrecision = 100 / radius;
  101394. // transition to new radius
  101395. if (!this._radiusTransition) {
  101396. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  101397. }
  101398. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  101399. _this.stopAllAnimations();
  101400. if (onAnimationEnd) {
  101401. onAnimationEnd();
  101402. }
  101403. if (_this._attachedCamera) {
  101404. _this._attachedCamera.storeState();
  101405. }
  101406. });
  101407. if (animatable) {
  101408. this._animatables.push(animatable);
  101409. }
  101410. };
  101411. /**
  101412. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  101413. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  101414. * frustum width.
  101415. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  101416. * to fully enclose the mesh in the viewing frustum.
  101417. */
  101418. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  101419. var size = maximumWorld.subtract(minimumWorld);
  101420. var boxVectorGlobalDiagonal = size.length();
  101421. var frustumSlope = this._getFrustumSlope();
  101422. // Formula for setting distance
  101423. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  101424. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  101425. // Horizon distance
  101426. var radius = radiusWithoutFraming * this._radiusScale;
  101427. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  101428. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  101429. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  101430. var camera = this._attachedCamera;
  101431. if (!camera) {
  101432. return 0;
  101433. }
  101434. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  101435. // Don't exceed the requested limit
  101436. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  101437. }
  101438. // Don't exceed the upper radius limit
  101439. if (camera.upperRadiusLimit) {
  101440. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  101441. }
  101442. return distance;
  101443. };
  101444. /**
  101445. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  101446. * is automatically returned to its default position (expected to be above ground plane).
  101447. */
  101448. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  101449. var _this = this;
  101450. if (this._elevationReturnTime < 0) {
  101451. return;
  101452. }
  101453. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  101454. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  101455. var limitBeta = Math.PI * 0.5;
  101456. // Bring the camera back up if below the ground plane
  101457. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  101458. this._betaIsAnimating = true;
  101459. //Transition to new position
  101460. this.stopAllAnimations();
  101461. if (!this._betaTransition) {
  101462. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  101463. }
  101464. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  101465. _this._clearAnimationLocks();
  101466. _this.stopAllAnimations();
  101467. });
  101468. if (animatabe) {
  101469. this._animatables.push(animatabe);
  101470. }
  101471. }
  101472. };
  101473. /**
  101474. * Returns the frustum slope based on the canvas ratio and camera FOV
  101475. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  101476. */
  101477. FramingBehavior.prototype._getFrustumSlope = function () {
  101478. // Calculate the viewport ratio
  101479. // Aspect Ratio is Height/Width.
  101480. var camera = this._attachedCamera;
  101481. if (!camera) {
  101482. return BABYLON.Vector2.Zero();
  101483. }
  101484. var engine = camera.getScene().getEngine();
  101485. var aspectRatio = engine.getAspectRatio(camera);
  101486. // Camera FOV is the vertical field of view (top-bottom) in radians.
  101487. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  101488. var frustumSlopeY = Math.tan(camera.fov / 2);
  101489. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  101490. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  101491. // along the forward vector.
  101492. var frustumSlopeX = frustumSlopeY * aspectRatio;
  101493. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  101494. };
  101495. /**
  101496. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  101497. */
  101498. FramingBehavior.prototype._clearAnimationLocks = function () {
  101499. this._betaIsAnimating = false;
  101500. };
  101501. /**
  101502. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  101503. */
  101504. FramingBehavior.prototype._applyUserInteraction = function () {
  101505. if (this.isUserIsMoving) {
  101506. this._lastInteractionTime = BABYLON.Tools.Now;
  101507. this.stopAllAnimations();
  101508. this._clearAnimationLocks();
  101509. }
  101510. };
  101511. /**
  101512. * Stops and removes all animations that have been applied to the camera
  101513. */
  101514. FramingBehavior.prototype.stopAllAnimations = function () {
  101515. if (this._attachedCamera) {
  101516. this._attachedCamera.animations = [];
  101517. }
  101518. while (this._animatables.length) {
  101519. if (this._animatables[0]) {
  101520. this._animatables[0].onAnimationEnd = null;
  101521. this._animatables[0].stop();
  101522. }
  101523. this._animatables.shift();
  101524. }
  101525. };
  101526. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  101527. /**
  101528. * Gets a value indicating if the user is moving the camera
  101529. */
  101530. get: function () {
  101531. if (!this._attachedCamera) {
  101532. return false;
  101533. }
  101534. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  101535. this._attachedCamera.inertialBetaOffset !== 0 ||
  101536. this._attachedCamera.inertialRadiusOffset !== 0 ||
  101537. this._attachedCamera.inertialPanningX !== 0 ||
  101538. this._attachedCamera.inertialPanningY !== 0 ||
  101539. this._isPointerDown;
  101540. },
  101541. enumerable: true,
  101542. configurable: true
  101543. });
  101544. /**
  101545. * The easing function used by animations
  101546. */
  101547. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  101548. /**
  101549. * The easing mode used by animations
  101550. */
  101551. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  101552. // Statics
  101553. /**
  101554. * The camera can move all the way towards the mesh.
  101555. */
  101556. FramingBehavior.IgnoreBoundsSizeMode = 0;
  101557. /**
  101558. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  101559. */
  101560. FramingBehavior.FitFrustumSidesMode = 1;
  101561. return FramingBehavior;
  101562. }());
  101563. BABYLON.FramingBehavior = FramingBehavior;
  101564. })(BABYLON || (BABYLON = {}));
  101565. //# sourceMappingURL=babylon.framingBehavior.js.map
  101566. var BABYLON;
  101567. (function (BABYLON) {
  101568. /**
  101569. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  101570. */
  101571. var BouncingBehavior = /** @class */ (function () {
  101572. function BouncingBehavior() {
  101573. /**
  101574. * The duration of the animation, in milliseconds
  101575. */
  101576. this.transitionDuration = 450;
  101577. /**
  101578. * Length of the distance animated by the transition when lower radius is reached
  101579. */
  101580. this.lowerRadiusTransitionRange = 2;
  101581. /**
  101582. * Length of the distance animated by the transition when upper radius is reached
  101583. */
  101584. this.upperRadiusTransitionRange = -2;
  101585. this._autoTransitionRange = false;
  101586. // Animations
  101587. this._radiusIsAnimating = false;
  101588. this._radiusBounceTransition = null;
  101589. this._animatables = new Array();
  101590. }
  101591. Object.defineProperty(BouncingBehavior.prototype, "name", {
  101592. get: function () {
  101593. return "Bouncing";
  101594. },
  101595. enumerable: true,
  101596. configurable: true
  101597. });
  101598. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  101599. /**
  101600. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  101601. */
  101602. get: function () {
  101603. return this._autoTransitionRange;
  101604. },
  101605. /**
  101606. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  101607. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  101608. */
  101609. set: function (value) {
  101610. var _this = this;
  101611. if (this._autoTransitionRange === value) {
  101612. return;
  101613. }
  101614. this._autoTransitionRange = value;
  101615. var camera = this._attachedCamera;
  101616. if (!camera) {
  101617. return;
  101618. }
  101619. if (value) {
  101620. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  101621. if (!mesh) {
  101622. return;
  101623. }
  101624. mesh.computeWorldMatrix(true);
  101625. var diagonal = mesh.getBoundingInfo().diagonalLength;
  101626. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  101627. _this.upperRadiusTransitionRange = diagonal * 0.05;
  101628. });
  101629. }
  101630. else if (this._onMeshTargetChangedObserver) {
  101631. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  101632. }
  101633. },
  101634. enumerable: true,
  101635. configurable: true
  101636. });
  101637. BouncingBehavior.prototype.init = function () {
  101638. // Do notihng
  101639. };
  101640. BouncingBehavior.prototype.attach = function (camera) {
  101641. var _this = this;
  101642. this._attachedCamera = camera;
  101643. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101644. if (!_this._attachedCamera) {
  101645. return;
  101646. }
  101647. // Add the bounce animation to the lower radius limit
  101648. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  101649. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  101650. }
  101651. // Add the bounce animation to the upper radius limit
  101652. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  101653. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  101654. }
  101655. });
  101656. };
  101657. BouncingBehavior.prototype.detach = function () {
  101658. if (!this._attachedCamera) {
  101659. return;
  101660. }
  101661. if (this._onAfterCheckInputsObserver) {
  101662. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101663. }
  101664. if (this._onMeshTargetChangedObserver) {
  101665. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  101666. }
  101667. this._attachedCamera = null;
  101668. };
  101669. /**
  101670. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  101671. * @param radiusLimit The limit to check against.
  101672. * @return Bool to indicate if at limit.
  101673. */
  101674. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  101675. if (!this._attachedCamera) {
  101676. return false;
  101677. }
  101678. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  101679. return true;
  101680. }
  101681. return false;
  101682. };
  101683. /**
  101684. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  101685. * @param radiusDelta The delta by which to animate to. Can be negative.
  101686. */
  101687. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  101688. var _this = this;
  101689. if (!this._attachedCamera) {
  101690. return;
  101691. }
  101692. if (!this._radiusBounceTransition) {
  101693. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  101694. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  101695. }
  101696. // Prevent zoom until bounce has completed
  101697. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  101698. this._attachedCamera.wheelPrecision = Infinity;
  101699. this._attachedCamera.inertialRadiusOffset = 0;
  101700. // Animate to the radius limit
  101701. this.stopAllAnimations();
  101702. this._radiusIsAnimating = true;
  101703. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  101704. if (animatable) {
  101705. this._animatables.push(animatable);
  101706. }
  101707. };
  101708. /**
  101709. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  101710. */
  101711. BouncingBehavior.prototype._clearAnimationLocks = function () {
  101712. this._radiusIsAnimating = false;
  101713. if (this._attachedCamera) {
  101714. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  101715. }
  101716. };
  101717. /**
  101718. * Stops and removes all animations that have been applied to the camera
  101719. */
  101720. BouncingBehavior.prototype.stopAllAnimations = function () {
  101721. if (this._attachedCamera) {
  101722. this._attachedCamera.animations = [];
  101723. }
  101724. while (this._animatables.length) {
  101725. this._animatables[0].onAnimationEnd = null;
  101726. this._animatables[0].stop();
  101727. this._animatables.shift();
  101728. }
  101729. };
  101730. /**
  101731. * The easing function used by animations
  101732. */
  101733. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  101734. /**
  101735. * The easing mode used by animations
  101736. */
  101737. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  101738. return BouncingBehavior;
  101739. }());
  101740. BABYLON.BouncingBehavior = BouncingBehavior;
  101741. })(BABYLON || (BABYLON = {}));
  101742. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  101743. var BABYLON;
  101744. (function (BABYLON) {
  101745. var AutoRotationBehavior = /** @class */ (function () {
  101746. function AutoRotationBehavior() {
  101747. this._zoomStopsAnimation = false;
  101748. this._idleRotationSpeed = 0.05;
  101749. this._idleRotationWaitTime = 2000;
  101750. this._idleRotationSpinupTime = 2000;
  101751. this._isPointerDown = false;
  101752. this._lastFrameTime = null;
  101753. this._lastInteractionTime = -Infinity;
  101754. this._cameraRotationSpeed = 0;
  101755. this._lastFrameRadius = 0;
  101756. }
  101757. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  101758. get: function () {
  101759. return "AutoRotation";
  101760. },
  101761. enumerable: true,
  101762. configurable: true
  101763. });
  101764. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  101765. /**
  101766. * Gets the flag that indicates if user zooming should stop animation.
  101767. */
  101768. get: function () {
  101769. return this._zoomStopsAnimation;
  101770. },
  101771. /**
  101772. * Sets the flag that indicates if user zooming should stop animation.
  101773. */
  101774. set: function (flag) {
  101775. this._zoomStopsAnimation = flag;
  101776. },
  101777. enumerable: true,
  101778. configurable: true
  101779. });
  101780. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  101781. /**
  101782. * Gets the default speed at which the camera rotates around the model.
  101783. */
  101784. get: function () {
  101785. return this._idleRotationSpeed;
  101786. },
  101787. /**
  101788. * Sets the default speed at which the camera rotates around the model.
  101789. */
  101790. set: function (speed) {
  101791. this._idleRotationSpeed = speed;
  101792. },
  101793. enumerable: true,
  101794. configurable: true
  101795. });
  101796. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  101797. /**
  101798. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  101799. */
  101800. get: function () {
  101801. return this._idleRotationWaitTime;
  101802. },
  101803. /**
  101804. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  101805. */
  101806. set: function (time) {
  101807. this._idleRotationWaitTime = time;
  101808. },
  101809. enumerable: true,
  101810. configurable: true
  101811. });
  101812. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  101813. /**
  101814. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  101815. */
  101816. get: function () {
  101817. return this._idleRotationSpinupTime;
  101818. },
  101819. /**
  101820. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  101821. */
  101822. set: function (time) {
  101823. this._idleRotationSpinupTime = time;
  101824. },
  101825. enumerable: true,
  101826. configurable: true
  101827. });
  101828. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  101829. /**
  101830. * Gets a value indicating if the camera is currently rotating because of this behavior
  101831. */
  101832. get: function () {
  101833. return Math.abs(this._cameraRotationSpeed) > 0;
  101834. },
  101835. enumerable: true,
  101836. configurable: true
  101837. });
  101838. AutoRotationBehavior.prototype.init = function () {
  101839. // Do notihng
  101840. };
  101841. AutoRotationBehavior.prototype.attach = function (camera) {
  101842. var _this = this;
  101843. this._attachedCamera = camera;
  101844. var scene = this._attachedCamera.getScene();
  101845. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  101846. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  101847. _this._isPointerDown = true;
  101848. return;
  101849. }
  101850. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  101851. _this._isPointerDown = false;
  101852. }
  101853. });
  101854. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101855. var now = BABYLON.Tools.Now;
  101856. var dt = 0;
  101857. if (_this._lastFrameTime != null) {
  101858. dt = now - _this._lastFrameTime;
  101859. }
  101860. _this._lastFrameTime = now;
  101861. // Stop the animation if there is user interaction and the animation should stop for this interaction
  101862. _this._applyUserInteraction();
  101863. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  101864. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  101865. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  101866. // Step camera rotation by rotation speed
  101867. if (_this._attachedCamera) {
  101868. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  101869. }
  101870. });
  101871. };
  101872. AutoRotationBehavior.prototype.detach = function () {
  101873. if (!this._attachedCamera) {
  101874. return;
  101875. }
  101876. var scene = this._attachedCamera.getScene();
  101877. if (this._onPrePointerObservableObserver) {
  101878. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  101879. }
  101880. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101881. this._attachedCamera = null;
  101882. };
  101883. /**
  101884. * Returns true if user is scrolling.
  101885. * @return true if user is scrolling.
  101886. */
  101887. AutoRotationBehavior.prototype._userIsZooming = function () {
  101888. if (!this._attachedCamera) {
  101889. return false;
  101890. }
  101891. return this._attachedCamera.inertialRadiusOffset !== 0;
  101892. };
  101893. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  101894. if (!this._attachedCamera) {
  101895. return false;
  101896. }
  101897. var zoomHasHitLimit = false;
  101898. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  101899. zoomHasHitLimit = true;
  101900. }
  101901. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  101902. this._lastFrameRadius = this._attachedCamera.radius;
  101903. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  101904. };
  101905. /**
  101906. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  101907. */
  101908. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  101909. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  101910. this._lastInteractionTime = BABYLON.Tools.Now;
  101911. }
  101912. };
  101913. // Tools
  101914. AutoRotationBehavior.prototype._userIsMoving = function () {
  101915. if (!this._attachedCamera) {
  101916. return false;
  101917. }
  101918. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  101919. this._attachedCamera.inertialBetaOffset !== 0 ||
  101920. this._attachedCamera.inertialRadiusOffset !== 0 ||
  101921. this._attachedCamera.inertialPanningX !== 0 ||
  101922. this._attachedCamera.inertialPanningY !== 0 ||
  101923. this._isPointerDown;
  101924. };
  101925. return AutoRotationBehavior;
  101926. }());
  101927. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  101928. })(BABYLON || (BABYLON = {}));
  101929. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  101930. var BABYLON;
  101931. (function (BABYLON) {
  101932. var NullEngineOptions = /** @class */ (function () {
  101933. function NullEngineOptions() {
  101934. this.renderWidth = 512;
  101935. this.renderHeight = 256;
  101936. this.textureSize = 512;
  101937. this.deterministicLockstep = false;
  101938. this.lockstepMaxSteps = 4;
  101939. }
  101940. return NullEngineOptions;
  101941. }());
  101942. BABYLON.NullEngineOptions = NullEngineOptions;
  101943. /**
  101944. * The null engine class provides support for headless version of babylon.js.
  101945. * This can be used in server side scenario or for testing purposes
  101946. */
  101947. var NullEngine = /** @class */ (function (_super) {
  101948. __extends(NullEngine, _super);
  101949. function NullEngine(options) {
  101950. if (options === void 0) { options = new NullEngineOptions(); }
  101951. var _this = _super.call(this, null) || this;
  101952. if (options.deterministicLockstep === undefined) {
  101953. options.deterministicLockstep = false;
  101954. }
  101955. if (options.lockstepMaxSteps === undefined) {
  101956. options.lockstepMaxSteps = 4;
  101957. }
  101958. _this._options = options;
  101959. // Init caps
  101960. // We consider we are on a webgl1 capable device
  101961. _this._caps = new BABYLON.EngineCapabilities();
  101962. _this._caps.maxTexturesImageUnits = 16;
  101963. _this._caps.maxVertexTextureImageUnits = 16;
  101964. _this._caps.maxTextureSize = 512;
  101965. _this._caps.maxCubemapTextureSize = 512;
  101966. _this._caps.maxRenderTextureSize = 512;
  101967. _this._caps.maxVertexAttribs = 16;
  101968. _this._caps.maxVaryingVectors = 16;
  101969. _this._caps.maxFragmentUniformVectors = 16;
  101970. _this._caps.maxVertexUniformVectors = 16;
  101971. // Extensions
  101972. _this._caps.standardDerivatives = false;
  101973. _this._caps.astc = null;
  101974. _this._caps.s3tc = null;
  101975. _this._caps.pvrtc = null;
  101976. _this._caps.etc1 = null;
  101977. _this._caps.etc2 = null;
  101978. _this._caps.textureAnisotropicFilterExtension = null;
  101979. _this._caps.maxAnisotropy = 0;
  101980. _this._caps.uintIndices = false;
  101981. _this._caps.fragmentDepthSupported = false;
  101982. _this._caps.highPrecisionShaderSupported = true;
  101983. _this._caps.colorBufferFloat = false;
  101984. _this._caps.textureFloat = false;
  101985. _this._caps.textureFloatLinearFiltering = false;
  101986. _this._caps.textureFloatRender = false;
  101987. _this._caps.textureHalfFloat = false;
  101988. _this._caps.textureHalfFloatLinearFiltering = false;
  101989. _this._caps.textureHalfFloatRender = false;
  101990. _this._caps.textureLOD = false;
  101991. _this._caps.drawBuffersExtension = false;
  101992. _this._caps.depthTextureExtension = false;
  101993. _this._caps.vertexArrayObject = false;
  101994. _this._caps.instancedArrays = false;
  101995. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  101996. // Wrappers
  101997. if (typeof URL === "undefined") {
  101998. URL = {
  101999. createObjectURL: function () { },
  102000. revokeObjectURL: function () { }
  102001. };
  102002. }
  102003. if (typeof Blob === "undefined") {
  102004. Blob = function () { };
  102005. }
  102006. return _this;
  102007. }
  102008. NullEngine.prototype.isDeterministicLockStep = function () {
  102009. return this._options.deterministicLockstep;
  102010. };
  102011. NullEngine.prototype.getLockstepMaxSteps = function () {
  102012. return this._options.lockstepMaxSteps;
  102013. };
  102014. NullEngine.prototype.getHardwareScalingLevel = function () {
  102015. return 1.0;
  102016. };
  102017. NullEngine.prototype.createVertexBuffer = function (vertices) {
  102018. return {
  102019. capacity: 0,
  102020. references: 1,
  102021. is32Bits: false
  102022. };
  102023. };
  102024. NullEngine.prototype.createIndexBuffer = function (indices) {
  102025. return {
  102026. capacity: 0,
  102027. references: 1,
  102028. is32Bits: false
  102029. };
  102030. };
  102031. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  102032. if (stencil === void 0) { stencil = false; }
  102033. };
  102034. NullEngine.prototype.getRenderWidth = function (useScreen) {
  102035. if (useScreen === void 0) { useScreen = false; }
  102036. if (!useScreen && this._currentRenderTarget) {
  102037. return this._currentRenderTarget.width;
  102038. }
  102039. return this._options.renderWidth;
  102040. };
  102041. NullEngine.prototype.getRenderHeight = function (useScreen) {
  102042. if (useScreen === void 0) { useScreen = false; }
  102043. if (!useScreen && this._currentRenderTarget) {
  102044. return this._currentRenderTarget.height;
  102045. }
  102046. return this._options.renderHeight;
  102047. };
  102048. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  102049. this._cachedViewport = viewport;
  102050. };
  102051. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  102052. return {
  102053. transformFeedback: null,
  102054. __SPECTOR_rebuildProgram: null
  102055. };
  102056. };
  102057. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  102058. return [];
  102059. };
  102060. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  102061. return [];
  102062. };
  102063. NullEngine.prototype.bindSamplers = function (effect) {
  102064. this._currentEffect = null;
  102065. };
  102066. NullEngine.prototype.enableEffect = function (effect) {
  102067. this._currentEffect = effect;
  102068. if (effect.onBind) {
  102069. effect.onBind(effect);
  102070. }
  102071. if (effect._onBindObservable) {
  102072. effect._onBindObservable.notifyObservers(effect);
  102073. }
  102074. };
  102075. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  102076. if (zOffset === void 0) { zOffset = 0; }
  102077. if (reverseSide === void 0) { reverseSide = false; }
  102078. };
  102079. NullEngine.prototype.setIntArray = function (uniform, array) {
  102080. };
  102081. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  102082. };
  102083. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  102084. };
  102085. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  102086. };
  102087. NullEngine.prototype.setFloatArray = function (uniform, array) {
  102088. };
  102089. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  102090. };
  102091. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  102092. };
  102093. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  102094. };
  102095. NullEngine.prototype.setArray = function (uniform, array) {
  102096. };
  102097. NullEngine.prototype.setArray2 = function (uniform, array) {
  102098. };
  102099. NullEngine.prototype.setArray3 = function (uniform, array) {
  102100. };
  102101. NullEngine.prototype.setArray4 = function (uniform, array) {
  102102. };
  102103. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  102104. };
  102105. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  102106. };
  102107. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  102108. };
  102109. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  102110. };
  102111. NullEngine.prototype.setFloat = function (uniform, value) {
  102112. };
  102113. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  102114. };
  102115. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  102116. };
  102117. NullEngine.prototype.setBool = function (uniform, bool) {
  102118. };
  102119. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  102120. };
  102121. NullEngine.prototype.setColor3 = function (uniform, color3) {
  102122. };
  102123. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  102124. };
  102125. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  102126. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  102127. if (this._alphaMode === mode) {
  102128. return;
  102129. }
  102130. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  102131. if (!noDepthWriteChange) {
  102132. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  102133. }
  102134. this._alphaMode = mode;
  102135. };
  102136. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  102137. };
  102138. NullEngine.prototype.wipeCaches = function (bruteForce) {
  102139. if (this.preventCacheWipeBetweenFrames) {
  102140. return;
  102141. }
  102142. this.resetTextureCache();
  102143. this._currentEffect = null;
  102144. if (bruteForce) {
  102145. this._currentProgram = null;
  102146. this._stencilState.reset();
  102147. this._depthCullingState.reset();
  102148. this._alphaState.reset();
  102149. }
  102150. this._cachedVertexBuffers = null;
  102151. this._cachedIndexBuffer = null;
  102152. this._cachedEffectForVertexBuffers = null;
  102153. };
  102154. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  102155. };
  102156. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  102157. };
  102158. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  102159. };
  102160. NullEngine.prototype._createTexture = function () {
  102161. return {};
  102162. };
  102163. NullEngine.prototype._releaseTexture = function (texture) {
  102164. };
  102165. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  102166. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  102167. if (onLoad === void 0) { onLoad = null; }
  102168. if (onError === void 0) { onError = null; }
  102169. if (buffer === void 0) { buffer = null; }
  102170. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  102171. var url = String(urlArg);
  102172. texture.url = url;
  102173. texture.generateMipMaps = !noMipmap;
  102174. texture.samplingMode = samplingMode;
  102175. texture.invertY = invertY;
  102176. texture.baseWidth = this._options.textureSize;
  102177. texture.baseHeight = this._options.textureSize;
  102178. texture.width = this._options.textureSize;
  102179. texture.height = this._options.textureSize;
  102180. if (format) {
  102181. texture.format = format;
  102182. }
  102183. texture.isReady = true;
  102184. if (onLoad) {
  102185. onLoad();
  102186. }
  102187. this._internalTexturesCache.push(texture);
  102188. return texture;
  102189. };
  102190. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  102191. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  102192. if (options !== undefined && typeof options === "object") {
  102193. fullOptions.generateMipMaps = options.generateMipMaps;
  102194. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  102195. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  102196. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  102197. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  102198. }
  102199. else {
  102200. fullOptions.generateMipMaps = options;
  102201. fullOptions.generateDepthBuffer = true;
  102202. fullOptions.generateStencilBuffer = false;
  102203. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102204. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  102205. }
  102206. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  102207. var width = size.width || size;
  102208. var height = size.height || size;
  102209. texture._depthStencilBuffer = {};
  102210. texture._framebuffer = {};
  102211. texture.baseWidth = width;
  102212. texture.baseHeight = height;
  102213. texture.width = width;
  102214. texture.height = height;
  102215. texture.isReady = true;
  102216. texture.samples = 1;
  102217. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  102218. texture.samplingMode = fullOptions.samplingMode;
  102219. texture.type = fullOptions.type;
  102220. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  102221. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  102222. this._internalTexturesCache.push(texture);
  102223. return texture;
  102224. };
  102225. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  102226. texture.samplingMode = samplingMode;
  102227. };
  102228. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  102229. if (this._currentRenderTarget) {
  102230. this.unBindFramebuffer(this._currentRenderTarget);
  102231. }
  102232. this._currentRenderTarget = texture;
  102233. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  102234. if (this._cachedViewport && !forceFullscreenViewport) {
  102235. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  102236. }
  102237. };
  102238. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  102239. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  102240. this._currentRenderTarget = null;
  102241. if (onBeforeUnbind) {
  102242. if (texture._MSAAFramebuffer) {
  102243. this._currentFramebuffer = texture._framebuffer;
  102244. }
  102245. onBeforeUnbind();
  102246. }
  102247. this._currentFramebuffer = null;
  102248. };
  102249. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  102250. var vbo = {
  102251. capacity: 1,
  102252. references: 1,
  102253. is32Bits: false
  102254. };
  102255. return vbo;
  102256. };
  102257. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  102258. if (premulAlpha === void 0) { premulAlpha = false; }
  102259. };
  102260. /**
  102261. * Get the current error code of the webGL context
  102262. * @returns the error code
  102263. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  102264. */
  102265. NullEngine.prototype.getError = function () {
  102266. return 0;
  102267. };
  102268. /** @hidden */
  102269. NullEngine.prototype._getUnpackAlignement = function () {
  102270. return 1;
  102271. };
  102272. /** @hidden */
  102273. NullEngine.prototype._unpackFlipY = function (value) {
  102274. };
  102275. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  102276. if (offset === void 0) { offset = 0; }
  102277. };
  102278. /**
  102279. * Updates a dynamic vertex buffer.
  102280. * @param vertexBuffer the vertex buffer to update
  102281. * @param data the data used to update the vertex buffer
  102282. * @param byteOffset the byte offset of the data (optional)
  102283. * @param byteLength the byte length of the data (optional)
  102284. */
  102285. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  102286. };
  102287. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  102288. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  102289. this._boundTexturesCache[this._activeChannel] = texture;
  102290. return true;
  102291. }
  102292. return false;
  102293. };
  102294. NullEngine.prototype._bindTexture = function (channel, texture) {
  102295. if (channel < 0) {
  102296. return;
  102297. }
  102298. this._bindTextureDirectly(0, texture);
  102299. };
  102300. NullEngine.prototype._releaseBuffer = function (buffer) {
  102301. buffer.references--;
  102302. if (buffer.references === 0) {
  102303. return true;
  102304. }
  102305. return false;
  102306. };
  102307. NullEngine.prototype.releaseEffects = function () {
  102308. };
  102309. NullEngine.prototype.displayLoadingUI = function () {
  102310. };
  102311. NullEngine.prototype.hideLoadingUI = function () {
  102312. };
  102313. /** @hidden */
  102314. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  102315. if (faceIndex === void 0) { faceIndex = 0; }
  102316. if (lod === void 0) { lod = 0; }
  102317. };
  102318. /** @hidden */
  102319. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  102320. if (faceIndex === void 0) { faceIndex = 0; }
  102321. if (lod === void 0) { lod = 0; }
  102322. };
  102323. /** @hidden */
  102324. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  102325. if (faceIndex === void 0) { faceIndex = 0; }
  102326. if (lod === void 0) { lod = 0; }
  102327. };
  102328. /** @hidden */
  102329. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  102330. if (faceIndex === void 0) { faceIndex = 0; }
  102331. if (lod === void 0) { lod = 0; }
  102332. };
  102333. return NullEngine;
  102334. }(BABYLON.Engine));
  102335. BABYLON.NullEngine = NullEngine;
  102336. })(BABYLON || (BABYLON = {}));
  102337. //# sourceMappingURL=babylon.nullEngine.js.map
  102338. var BABYLON;
  102339. (function (BABYLON) {
  102340. /**
  102341. * This class can be used to get instrumentation data from a Babylon engine
  102342. */
  102343. var EngineInstrumentation = /** @class */ (function () {
  102344. function EngineInstrumentation(engine) {
  102345. this.engine = engine;
  102346. this._captureGPUFrameTime = false;
  102347. this._gpuFrameTime = new BABYLON.PerfCounter();
  102348. this._captureShaderCompilationTime = false;
  102349. this._shaderCompilationTime = new BABYLON.PerfCounter();
  102350. // Observers
  102351. this._onBeginFrameObserver = null;
  102352. this._onEndFrameObserver = null;
  102353. this._onBeforeShaderCompilationObserver = null;
  102354. this._onAfterShaderCompilationObserver = null;
  102355. }
  102356. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  102357. // Properties
  102358. /**
  102359. * Gets the perf counter used for GPU frame time
  102360. */
  102361. get: function () {
  102362. return this._gpuFrameTime;
  102363. },
  102364. enumerable: true,
  102365. configurable: true
  102366. });
  102367. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  102368. /**
  102369. * Gets the GPU frame time capture status
  102370. */
  102371. get: function () {
  102372. return this._captureGPUFrameTime;
  102373. },
  102374. /**
  102375. * Enable or disable the GPU frame time capture
  102376. */
  102377. set: function (value) {
  102378. var _this = this;
  102379. if (value === this._captureGPUFrameTime) {
  102380. return;
  102381. }
  102382. this._captureGPUFrameTime = value;
  102383. if (value) {
  102384. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  102385. if (!_this._gpuFrameTimeToken) {
  102386. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  102387. }
  102388. });
  102389. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  102390. if (!_this._gpuFrameTimeToken) {
  102391. return;
  102392. }
  102393. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  102394. if (time > -1) {
  102395. _this._gpuFrameTimeToken = null;
  102396. _this._gpuFrameTime.fetchNewFrame();
  102397. _this._gpuFrameTime.addCount(time, true);
  102398. }
  102399. });
  102400. }
  102401. else {
  102402. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  102403. this._onBeginFrameObserver = null;
  102404. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  102405. this._onEndFrameObserver = null;
  102406. }
  102407. },
  102408. enumerable: true,
  102409. configurable: true
  102410. });
  102411. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  102412. /**
  102413. * Gets the perf counter used for shader compilation time
  102414. */
  102415. get: function () {
  102416. return this._shaderCompilationTime;
  102417. },
  102418. enumerable: true,
  102419. configurable: true
  102420. });
  102421. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  102422. /**
  102423. * Gets the shader compilation time capture status
  102424. */
  102425. get: function () {
  102426. return this._captureShaderCompilationTime;
  102427. },
  102428. /**
  102429. * Enable or disable the shader compilation time capture
  102430. */
  102431. set: function (value) {
  102432. var _this = this;
  102433. if (value === this._captureShaderCompilationTime) {
  102434. return;
  102435. }
  102436. this._captureShaderCompilationTime = value;
  102437. if (value) {
  102438. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  102439. _this._shaderCompilationTime.fetchNewFrame();
  102440. _this._shaderCompilationTime.beginMonitoring();
  102441. });
  102442. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  102443. _this._shaderCompilationTime.endMonitoring();
  102444. });
  102445. }
  102446. else {
  102447. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  102448. this._onBeforeShaderCompilationObserver = null;
  102449. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  102450. this._onAfterShaderCompilationObserver = null;
  102451. }
  102452. },
  102453. enumerable: true,
  102454. configurable: true
  102455. });
  102456. EngineInstrumentation.prototype.dispose = function () {
  102457. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  102458. this._onBeginFrameObserver = null;
  102459. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  102460. this._onEndFrameObserver = null;
  102461. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  102462. this._onBeforeShaderCompilationObserver = null;
  102463. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  102464. this._onAfterShaderCompilationObserver = null;
  102465. this.engine = null;
  102466. };
  102467. return EngineInstrumentation;
  102468. }());
  102469. BABYLON.EngineInstrumentation = EngineInstrumentation;
  102470. })(BABYLON || (BABYLON = {}));
  102471. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  102472. var BABYLON;
  102473. (function (BABYLON) {
  102474. /**
  102475. * This class can be used to get instrumentation data from a Babylon engine
  102476. */
  102477. var SceneInstrumentation = /** @class */ (function () {
  102478. function SceneInstrumentation(scene) {
  102479. var _this = this;
  102480. this.scene = scene;
  102481. this._captureActiveMeshesEvaluationTime = false;
  102482. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  102483. this._captureRenderTargetsRenderTime = false;
  102484. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  102485. this._captureFrameTime = false;
  102486. this._frameTime = new BABYLON.PerfCounter();
  102487. this._captureRenderTime = false;
  102488. this._renderTime = new BABYLON.PerfCounter();
  102489. this._captureInterFrameTime = false;
  102490. this._interFrameTime = new BABYLON.PerfCounter();
  102491. this._captureParticlesRenderTime = false;
  102492. this._particlesRenderTime = new BABYLON.PerfCounter();
  102493. this._captureSpritesRenderTime = false;
  102494. this._spritesRenderTime = new BABYLON.PerfCounter();
  102495. this._capturePhysicsTime = false;
  102496. this._physicsTime = new BABYLON.PerfCounter();
  102497. this._captureAnimationsTime = false;
  102498. this._animationsTime = new BABYLON.PerfCounter();
  102499. this._captureCameraRenderTime = false;
  102500. this._cameraRenderTime = new BABYLON.PerfCounter();
  102501. // Observers
  102502. this._onBeforeActiveMeshesEvaluationObserver = null;
  102503. this._onAfterActiveMeshesEvaluationObserver = null;
  102504. this._onBeforeRenderTargetsRenderObserver = null;
  102505. this._onAfterRenderTargetsRenderObserver = null;
  102506. this._onAfterRenderObserver = null;
  102507. this._onBeforeDrawPhaseObserver = null;
  102508. this._onAfterDrawPhaseObserver = null;
  102509. this._onBeforeAnimationsObserver = null;
  102510. this._onBeforeParticlesRenderingObserver = null;
  102511. this._onAfterParticlesRenderingObserver = null;
  102512. this._onBeforeSpritesRenderingObserver = null;
  102513. this._onAfterSpritesRenderingObserver = null;
  102514. this._onBeforePhysicsObserver = null;
  102515. this._onAfterPhysicsObserver = null;
  102516. this._onAfterAnimationsObserver = null;
  102517. this._onBeforeCameraRenderObserver = null;
  102518. this._onAfterCameraRenderObserver = null;
  102519. // Before render
  102520. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  102521. if (_this._captureActiveMeshesEvaluationTime) {
  102522. _this._activeMeshesEvaluationTime.fetchNewFrame();
  102523. }
  102524. if (_this._captureRenderTargetsRenderTime) {
  102525. _this._renderTargetsRenderTime.fetchNewFrame();
  102526. }
  102527. if (_this._captureFrameTime) {
  102528. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  102529. _this._frameTime.beginMonitoring();
  102530. }
  102531. if (_this._captureInterFrameTime) {
  102532. _this._interFrameTime.endMonitoring();
  102533. }
  102534. if (_this._captureParticlesRenderTime) {
  102535. _this._particlesRenderTime.fetchNewFrame();
  102536. }
  102537. if (_this._captureSpritesRenderTime) {
  102538. _this._spritesRenderTime.fetchNewFrame();
  102539. }
  102540. if (_this._captureAnimationsTime) {
  102541. _this._animationsTime.beginMonitoring();
  102542. }
  102543. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  102544. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  102545. });
  102546. // After render
  102547. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  102548. if (_this._captureFrameTime) {
  102549. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  102550. _this._frameTime.endMonitoring();
  102551. }
  102552. if (_this._captureRenderTime) {
  102553. _this._renderTime.endMonitoring(false);
  102554. }
  102555. if (_this._captureInterFrameTime) {
  102556. _this._interFrameTime.beginMonitoring();
  102557. }
  102558. });
  102559. }
  102560. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  102561. // Properties
  102562. /**
  102563. * Gets the perf counter used for active meshes evaluation time
  102564. */
  102565. get: function () {
  102566. return this._activeMeshesEvaluationTime;
  102567. },
  102568. enumerable: true,
  102569. configurable: true
  102570. });
  102571. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  102572. /**
  102573. * Gets the active meshes evaluation time capture status
  102574. */
  102575. get: function () {
  102576. return this._captureActiveMeshesEvaluationTime;
  102577. },
  102578. /**
  102579. * Enable or disable the active meshes evaluation time capture
  102580. */
  102581. set: function (value) {
  102582. var _this = this;
  102583. if (value === this._captureActiveMeshesEvaluationTime) {
  102584. return;
  102585. }
  102586. this._captureActiveMeshesEvaluationTime = value;
  102587. if (value) {
  102588. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  102589. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  102590. _this._activeMeshesEvaluationTime.beginMonitoring();
  102591. });
  102592. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  102593. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  102594. _this._activeMeshesEvaluationTime.endMonitoring();
  102595. });
  102596. }
  102597. else {
  102598. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  102599. this._onBeforeActiveMeshesEvaluationObserver = null;
  102600. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  102601. this._onAfterActiveMeshesEvaluationObserver = null;
  102602. }
  102603. },
  102604. enumerable: true,
  102605. configurable: true
  102606. });
  102607. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  102608. /**
  102609. * Gets the perf counter used for render targets render time
  102610. */
  102611. get: function () {
  102612. return this._renderTargetsRenderTime;
  102613. },
  102614. enumerable: true,
  102615. configurable: true
  102616. });
  102617. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  102618. /**
  102619. * Gets the render targets render time capture status
  102620. */
  102621. get: function () {
  102622. return this._captureRenderTargetsRenderTime;
  102623. },
  102624. /**
  102625. * Enable or disable the render targets render time capture
  102626. */
  102627. set: function (value) {
  102628. var _this = this;
  102629. if (value === this._captureRenderTargetsRenderTime) {
  102630. return;
  102631. }
  102632. this._captureRenderTargetsRenderTime = value;
  102633. if (value) {
  102634. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  102635. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  102636. _this._renderTargetsRenderTime.beginMonitoring();
  102637. });
  102638. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  102639. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  102640. _this._renderTargetsRenderTime.endMonitoring(false);
  102641. });
  102642. }
  102643. else {
  102644. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  102645. this._onBeforeRenderTargetsRenderObserver = null;
  102646. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  102647. this._onAfterRenderTargetsRenderObserver = null;
  102648. }
  102649. },
  102650. enumerable: true,
  102651. configurable: true
  102652. });
  102653. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  102654. /**
  102655. * Gets the perf counter used for particles render time
  102656. */
  102657. get: function () {
  102658. return this._particlesRenderTime;
  102659. },
  102660. enumerable: true,
  102661. configurable: true
  102662. });
  102663. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  102664. /**
  102665. * Gets the particles render time capture status
  102666. */
  102667. get: function () {
  102668. return this._captureParticlesRenderTime;
  102669. },
  102670. /**
  102671. * Enable or disable the particles render time capture
  102672. */
  102673. set: function (value) {
  102674. var _this = this;
  102675. if (value === this._captureParticlesRenderTime) {
  102676. return;
  102677. }
  102678. this._captureParticlesRenderTime = value;
  102679. if (value) {
  102680. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  102681. BABYLON.Tools.StartPerformanceCounter("Particles");
  102682. _this._particlesRenderTime.beginMonitoring();
  102683. });
  102684. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  102685. BABYLON.Tools.EndPerformanceCounter("Particles");
  102686. _this._particlesRenderTime.endMonitoring(false);
  102687. });
  102688. }
  102689. else {
  102690. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  102691. this._onBeforeParticlesRenderingObserver = null;
  102692. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  102693. this._onAfterParticlesRenderingObserver = null;
  102694. }
  102695. },
  102696. enumerable: true,
  102697. configurable: true
  102698. });
  102699. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  102700. /**
  102701. * Gets the perf counter used for sprites render time
  102702. */
  102703. get: function () {
  102704. return this._spritesRenderTime;
  102705. },
  102706. enumerable: true,
  102707. configurable: true
  102708. });
  102709. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  102710. /**
  102711. * Gets the sprites render time capture status
  102712. */
  102713. get: function () {
  102714. return this._captureSpritesRenderTime;
  102715. },
  102716. /**
  102717. * Enable or disable the sprites render time capture
  102718. */
  102719. set: function (value) {
  102720. var _this = this;
  102721. if (value === this._captureSpritesRenderTime) {
  102722. return;
  102723. }
  102724. this._captureSpritesRenderTime = value;
  102725. if (value) {
  102726. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  102727. BABYLON.Tools.StartPerformanceCounter("Sprites");
  102728. _this._spritesRenderTime.beginMonitoring();
  102729. });
  102730. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  102731. BABYLON.Tools.EndPerformanceCounter("Sprites");
  102732. _this._spritesRenderTime.endMonitoring(false);
  102733. });
  102734. }
  102735. else {
  102736. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  102737. this._onBeforeSpritesRenderingObserver = null;
  102738. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  102739. this._onAfterSpritesRenderingObserver = null;
  102740. }
  102741. },
  102742. enumerable: true,
  102743. configurable: true
  102744. });
  102745. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  102746. /**
  102747. * Gets the perf counter used for physics time
  102748. */
  102749. get: function () {
  102750. return this._physicsTime;
  102751. },
  102752. enumerable: true,
  102753. configurable: true
  102754. });
  102755. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  102756. /**
  102757. * Gets the physics time capture status
  102758. */
  102759. get: function () {
  102760. return this._capturePhysicsTime;
  102761. },
  102762. /**
  102763. * Enable or disable the physics time capture
  102764. */
  102765. set: function (value) {
  102766. var _this = this;
  102767. if (value === this._capturePhysicsTime) {
  102768. return;
  102769. }
  102770. this._capturePhysicsTime = value;
  102771. if (value) {
  102772. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  102773. BABYLON.Tools.StartPerformanceCounter("Physics");
  102774. _this._physicsTime.beginMonitoring();
  102775. });
  102776. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  102777. BABYLON.Tools.EndPerformanceCounter("Physics");
  102778. _this._physicsTime.endMonitoring();
  102779. });
  102780. }
  102781. else {
  102782. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  102783. this._onBeforePhysicsObserver = null;
  102784. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  102785. this._onAfterPhysicsObserver = null;
  102786. }
  102787. },
  102788. enumerable: true,
  102789. configurable: true
  102790. });
  102791. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  102792. /**
  102793. * Gets the perf counter used for animations time
  102794. */
  102795. get: function () {
  102796. return this._animationsTime;
  102797. },
  102798. enumerable: true,
  102799. configurable: true
  102800. });
  102801. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  102802. /**
  102803. * Gets the animations time capture status
  102804. */
  102805. get: function () {
  102806. return this._captureAnimationsTime;
  102807. },
  102808. /**
  102809. * Enable or disable the animations time capture
  102810. */
  102811. set: function (value) {
  102812. var _this = this;
  102813. if (value === this._captureAnimationsTime) {
  102814. return;
  102815. }
  102816. this._captureAnimationsTime = value;
  102817. if (value) {
  102818. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  102819. _this._animationsTime.endMonitoring();
  102820. });
  102821. }
  102822. else {
  102823. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  102824. this._onAfterAnimationsObserver = null;
  102825. }
  102826. },
  102827. enumerable: true,
  102828. configurable: true
  102829. });
  102830. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  102831. /**
  102832. * Gets the perf counter used for frame time capture
  102833. */
  102834. get: function () {
  102835. return this._frameTime;
  102836. },
  102837. enumerable: true,
  102838. configurable: true
  102839. });
  102840. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  102841. /**
  102842. * Gets the frame time capture status
  102843. */
  102844. get: function () {
  102845. return this._captureFrameTime;
  102846. },
  102847. /**
  102848. * Enable or disable the frame time capture
  102849. */
  102850. set: function (value) {
  102851. this._captureFrameTime = value;
  102852. },
  102853. enumerable: true,
  102854. configurable: true
  102855. });
  102856. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  102857. /**
  102858. * Gets the perf counter used for inter-frames time capture
  102859. */
  102860. get: function () {
  102861. return this._interFrameTime;
  102862. },
  102863. enumerable: true,
  102864. configurable: true
  102865. });
  102866. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  102867. /**
  102868. * Gets the inter-frames time capture status
  102869. */
  102870. get: function () {
  102871. return this._captureInterFrameTime;
  102872. },
  102873. /**
  102874. * Enable or disable the inter-frames time capture
  102875. */
  102876. set: function (value) {
  102877. this._captureInterFrameTime = value;
  102878. },
  102879. enumerable: true,
  102880. configurable: true
  102881. });
  102882. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  102883. /**
  102884. * Gets the perf counter used for render time capture
  102885. */
  102886. get: function () {
  102887. return this._renderTime;
  102888. },
  102889. enumerable: true,
  102890. configurable: true
  102891. });
  102892. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  102893. /**
  102894. * Gets the render time capture status
  102895. */
  102896. get: function () {
  102897. return this._captureRenderTime;
  102898. },
  102899. /**
  102900. * Enable or disable the render time capture
  102901. */
  102902. set: function (value) {
  102903. var _this = this;
  102904. if (value === this._captureRenderTime) {
  102905. return;
  102906. }
  102907. this._captureRenderTime = value;
  102908. if (value) {
  102909. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  102910. _this._renderTime.beginMonitoring();
  102911. BABYLON.Tools.StartPerformanceCounter("Main render");
  102912. });
  102913. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  102914. _this._renderTime.endMonitoring(false);
  102915. BABYLON.Tools.EndPerformanceCounter("Main render");
  102916. });
  102917. }
  102918. else {
  102919. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102920. this._onBeforeDrawPhaseObserver = null;
  102921. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102922. this._onAfterDrawPhaseObserver = null;
  102923. }
  102924. },
  102925. enumerable: true,
  102926. configurable: true
  102927. });
  102928. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  102929. /**
  102930. * Gets the perf counter used for camera render time capture
  102931. */
  102932. get: function () {
  102933. return this._cameraRenderTime;
  102934. },
  102935. enumerable: true,
  102936. configurable: true
  102937. });
  102938. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  102939. /**
  102940. * Gets the camera render time capture status
  102941. */
  102942. get: function () {
  102943. return this._captureCameraRenderTime;
  102944. },
  102945. /**
  102946. * Enable or disable the camera render time capture
  102947. */
  102948. set: function (value) {
  102949. var _this = this;
  102950. if (value === this._captureCameraRenderTime) {
  102951. return;
  102952. }
  102953. this._captureCameraRenderTime = value;
  102954. if (value) {
  102955. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  102956. _this._cameraRenderTime.beginMonitoring();
  102957. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  102958. });
  102959. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  102960. _this._cameraRenderTime.endMonitoring(false);
  102961. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  102962. });
  102963. }
  102964. else {
  102965. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102966. this._onBeforeCameraRenderObserver = null;
  102967. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102968. this._onAfterCameraRenderObserver = null;
  102969. }
  102970. },
  102971. enumerable: true,
  102972. configurable: true
  102973. });
  102974. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  102975. /**
  102976. * Gets the perf counter used for draw calls
  102977. */
  102978. get: function () {
  102979. return this.scene.getEngine()._drawCalls;
  102980. },
  102981. enumerable: true,
  102982. configurable: true
  102983. });
  102984. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  102985. /**
  102986. * Gets the perf counter used for texture collisions
  102987. */
  102988. get: function () {
  102989. return this.scene.getEngine()._textureCollisions;
  102990. },
  102991. enumerable: true,
  102992. configurable: true
  102993. });
  102994. SceneInstrumentation.prototype.dispose = function () {
  102995. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  102996. this._onAfterRenderObserver = null;
  102997. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  102998. this._onBeforeActiveMeshesEvaluationObserver = null;
  102999. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  103000. this._onAfterActiveMeshesEvaluationObserver = null;
  103001. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  103002. this._onBeforeRenderTargetsRenderObserver = null;
  103003. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  103004. this._onAfterRenderTargetsRenderObserver = null;
  103005. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  103006. this._onBeforeAnimationsObserver = null;
  103007. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  103008. this._onBeforeParticlesRenderingObserver = null;
  103009. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  103010. this._onAfterParticlesRenderingObserver = null;
  103011. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  103012. this._onBeforeSpritesRenderingObserver = null;
  103013. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  103014. this._onAfterSpritesRenderingObserver = null;
  103015. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  103016. this._onBeforeDrawPhaseObserver = null;
  103017. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  103018. this._onAfterDrawPhaseObserver = null;
  103019. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  103020. this._onBeforePhysicsObserver = null;
  103021. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  103022. this._onAfterPhysicsObserver = null;
  103023. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  103024. this._onAfterAnimationsObserver = null;
  103025. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  103026. this._onBeforeCameraRenderObserver = null;
  103027. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  103028. this._onAfterCameraRenderObserver = null;
  103029. this.scene = null;
  103030. };
  103031. return SceneInstrumentation;
  103032. }());
  103033. BABYLON.SceneInstrumentation = SceneInstrumentation;
  103034. })(BABYLON || (BABYLON = {}));
  103035. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  103036. var BABYLON;
  103037. (function (BABYLON) {
  103038. /**
  103039. * @hidden
  103040. **/
  103041. var _TimeToken = /** @class */ (function () {
  103042. function _TimeToken() {
  103043. this._timeElapsedQueryEnded = false;
  103044. }
  103045. return _TimeToken;
  103046. }());
  103047. BABYLON._TimeToken = _TimeToken;
  103048. })(BABYLON || (BABYLON = {}));
  103049. //# sourceMappingURL=babylon.timeToken.js.map
  103050. var BABYLON;
  103051. (function (BABYLON) {
  103052. /**
  103053. * Background material defines definition.
  103054. * @hidden Mainly internal Use
  103055. */
  103056. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  103057. __extends(BackgroundMaterialDefines, _super);
  103058. /**
  103059. * Constructor of the defines.
  103060. */
  103061. function BackgroundMaterialDefines() {
  103062. var _this = _super.call(this) || this;
  103063. /**
  103064. * True if the diffuse texture is in use.
  103065. */
  103066. _this.DIFFUSE = false;
  103067. /**
  103068. * The direct UV channel to use.
  103069. */
  103070. _this.DIFFUSEDIRECTUV = 0;
  103071. /**
  103072. * True if the diffuse texture is in gamma space.
  103073. */
  103074. _this.GAMMADIFFUSE = false;
  103075. /**
  103076. * True if the diffuse texture has opacity in the alpha channel.
  103077. */
  103078. _this.DIFFUSEHASALPHA = false;
  103079. /**
  103080. * True if you want the material to fade to transparent at grazing angle.
  103081. */
  103082. _this.OPACITYFRESNEL = false;
  103083. /**
  103084. * True if an extra blur needs to be added in the reflection.
  103085. */
  103086. _this.REFLECTIONBLUR = false;
  103087. /**
  103088. * True if you want the material to fade to reflection at grazing angle.
  103089. */
  103090. _this.REFLECTIONFRESNEL = false;
  103091. /**
  103092. * True if you want the material to falloff as far as you move away from the scene center.
  103093. */
  103094. _this.REFLECTIONFALLOFF = false;
  103095. /**
  103096. * False if the current Webgl implementation does not support the texture lod extension.
  103097. */
  103098. _this.TEXTURELODSUPPORT = false;
  103099. /**
  103100. * True to ensure the data are premultiplied.
  103101. */
  103102. _this.PREMULTIPLYALPHA = false;
  103103. /**
  103104. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  103105. */
  103106. _this.USERGBCOLOR = false;
  103107. /**
  103108. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  103109. * stays aligned with the desired configuration.
  103110. */
  103111. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  103112. /**
  103113. * True to add noise in order to reduce the banding effect.
  103114. */
  103115. _this.NOISE = false;
  103116. /**
  103117. * is the reflection texture in BGR color scheme?
  103118. * Mainly used to solve a bug in ios10 video tag
  103119. */
  103120. _this.REFLECTIONBGR = false;
  103121. _this.IMAGEPROCESSING = false;
  103122. _this.VIGNETTE = false;
  103123. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  103124. _this.VIGNETTEBLENDMODEOPAQUE = false;
  103125. _this.TONEMAPPING = false;
  103126. _this.CONTRAST = false;
  103127. _this.COLORCURVES = false;
  103128. _this.COLORGRADING = false;
  103129. _this.COLORGRADING3D = false;
  103130. _this.SAMPLER3DGREENDEPTH = false;
  103131. _this.SAMPLER3DBGRMAP = false;
  103132. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  103133. _this.EXPOSURE = false;
  103134. // Reflection.
  103135. _this.REFLECTION = false;
  103136. _this.REFLECTIONMAP_3D = false;
  103137. _this.REFLECTIONMAP_SPHERICAL = false;
  103138. _this.REFLECTIONMAP_PLANAR = false;
  103139. _this.REFLECTIONMAP_CUBIC = false;
  103140. _this.REFLECTIONMAP_PROJECTION = false;
  103141. _this.REFLECTIONMAP_SKYBOX = false;
  103142. _this.REFLECTIONMAP_EXPLICIT = false;
  103143. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  103144. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  103145. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  103146. _this.INVERTCUBICMAP = false;
  103147. _this.REFLECTIONMAP_OPPOSITEZ = false;
  103148. _this.LODINREFLECTIONALPHA = false;
  103149. _this.GAMMAREFLECTION = false;
  103150. _this.RGBDREFLECTION = false;
  103151. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  103152. // Default BJS.
  103153. _this.MAINUV1 = false;
  103154. _this.MAINUV2 = false;
  103155. _this.UV1 = false;
  103156. _this.UV2 = false;
  103157. _this.CLIPPLANE = false;
  103158. _this.POINTSIZE = false;
  103159. _this.FOG = false;
  103160. _this.NORMAL = false;
  103161. _this.NUM_BONE_INFLUENCERS = 0;
  103162. _this.BonesPerMesh = 0;
  103163. _this.INSTANCES = false;
  103164. _this.SHADOWFLOAT = false;
  103165. _this.rebuild();
  103166. return _this;
  103167. }
  103168. return BackgroundMaterialDefines;
  103169. }(BABYLON.MaterialDefines));
  103170. /**
  103171. * Background material used to create an efficient environement around your scene.
  103172. */
  103173. var BackgroundMaterial = /** @class */ (function (_super) {
  103174. __extends(BackgroundMaterial, _super);
  103175. /**
  103176. * Instantiates a Background Material in the given scene
  103177. * @param name The friendly name of the material
  103178. * @param scene The scene to add the material to
  103179. */
  103180. function BackgroundMaterial(name, scene) {
  103181. var _this = _super.call(this, name, scene) || this;
  103182. /**
  103183. * Key light Color (multiply against the environement texture)
  103184. */
  103185. _this.primaryColor = BABYLON.Color3.White();
  103186. _this._primaryColorShadowLevel = 0;
  103187. _this._primaryColorHighlightLevel = 0;
  103188. /**
  103189. * Reflection Texture used in the material.
  103190. * Should be author in a specific way for the best result (refer to the documentation).
  103191. */
  103192. _this.reflectionTexture = null;
  103193. /**
  103194. * Reflection Texture level of blur.
  103195. *
  103196. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  103197. * texture twice.
  103198. */
  103199. _this.reflectionBlur = 0;
  103200. /**
  103201. * Diffuse Texture used in the material.
  103202. * Should be author in a specific way for the best result (refer to the documentation).
  103203. */
  103204. _this.diffuseTexture = null;
  103205. _this._shadowLights = null;
  103206. /**
  103207. * Specify the list of lights casting shadow on the material.
  103208. * All scene shadow lights will be included if null.
  103209. */
  103210. _this.shadowLights = null;
  103211. /**
  103212. * Helps adjusting the shadow to a softer level if required.
  103213. * 0 means black shadows and 1 means no shadows.
  103214. */
  103215. _this.shadowLevel = 0;
  103216. /**
  103217. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  103218. * It is usually zero but might be interesting to modify according to your setup.
  103219. */
  103220. _this.sceneCenter = BABYLON.Vector3.Zero();
  103221. /**
  103222. * This helps specifying that the material is falling off to the sky box at grazing angle.
  103223. * This helps ensuring a nice transition when the camera goes under the ground.
  103224. */
  103225. _this.opacityFresnel = true;
  103226. /**
  103227. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  103228. * This helps adding a mirror texture on the ground.
  103229. */
  103230. _this.reflectionFresnel = false;
  103231. /**
  103232. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  103233. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  103234. */
  103235. _this.reflectionFalloffDistance = 0.0;
  103236. /**
  103237. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  103238. */
  103239. _this.reflectionAmount = 1.0;
  103240. /**
  103241. * This specifies the weight of the reflection at grazing angle.
  103242. */
  103243. _this.reflectionReflectance0 = 0.05;
  103244. /**
  103245. * This specifies the weight of the reflection at a perpendicular point of view.
  103246. */
  103247. _this.reflectionReflectance90 = 0.5;
  103248. /**
  103249. * Helps to directly use the maps channels instead of their level.
  103250. */
  103251. _this.useRGBColor = true;
  103252. /**
  103253. * This helps reducing the banding effect that could occur on the background.
  103254. */
  103255. _this.enableNoise = false;
  103256. _this._fovMultiplier = 1.0;
  103257. /**
  103258. * Enable the FOV adjustment feature controlled by fovMultiplier.
  103259. */
  103260. _this.useEquirectangularFOV = false;
  103261. _this._maxSimultaneousLights = 4;
  103262. /**
  103263. * Number of Simultaneous lights allowed on the material.
  103264. */
  103265. _this.maxSimultaneousLights = 4;
  103266. /**
  103267. * Keep track of the image processing observer to allow dispose and replace.
  103268. */
  103269. _this._imageProcessingObserver = null;
  103270. /**
  103271. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  103272. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  103273. */
  103274. _this.switchToBGR = false;
  103275. // Temp values kept as cache in the material.
  103276. _this._renderTargets = new BABYLON.SmartArray(16);
  103277. _this._reflectionControls = BABYLON.Vector4.Zero();
  103278. _this._white = BABYLON.Color3.White();
  103279. _this._primaryShadowColor = BABYLON.Color3.Black();
  103280. _this._primaryHighlightColor = BABYLON.Color3.Black();
  103281. // Setup the default processing configuration to the scene.
  103282. _this._attachImageProcessingConfiguration(null);
  103283. _this.getRenderTargetTextures = function () {
  103284. _this._renderTargets.reset();
  103285. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  103286. _this._renderTargets.push(_this._diffuseTexture);
  103287. }
  103288. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  103289. _this._renderTargets.push(_this._reflectionTexture);
  103290. }
  103291. return _this._renderTargets;
  103292. };
  103293. return _this;
  103294. }
  103295. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  103296. /**
  103297. * Experimental Internal Use Only.
  103298. *
  103299. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  103300. * This acts as a helper to set the primary color to a more "human friendly" value.
  103301. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  103302. * output color as close as possible from the chosen value.
  103303. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  103304. * part of lighting setup.)
  103305. */
  103306. get: function () {
  103307. return this.__perceptualColor;
  103308. },
  103309. set: function (value) {
  103310. this.__perceptualColor = value;
  103311. this._computePrimaryColorFromPerceptualColor();
  103312. this._markAllSubMeshesAsLightsDirty();
  103313. },
  103314. enumerable: true,
  103315. configurable: true
  103316. });
  103317. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  103318. /**
  103319. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  103320. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  103321. */
  103322. get: function () {
  103323. return this._primaryColorShadowLevel;
  103324. },
  103325. set: function (value) {
  103326. this._primaryColorShadowLevel = value;
  103327. this._computePrimaryColors();
  103328. this._markAllSubMeshesAsLightsDirty();
  103329. },
  103330. enumerable: true,
  103331. configurable: true
  103332. });
  103333. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  103334. /**
  103335. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  103336. * The primary color is used at the level chosen to define what the white area would look.
  103337. */
  103338. get: function () {
  103339. return this._primaryColorHighlightLevel;
  103340. },
  103341. set: function (value) {
  103342. this._primaryColorHighlightLevel = value;
  103343. this._computePrimaryColors();
  103344. this._markAllSubMeshesAsLightsDirty();
  103345. },
  103346. enumerable: true,
  103347. configurable: true
  103348. });
  103349. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  103350. /**
  103351. * Sets the reflection reflectance fresnel values according to the default standard
  103352. * empirically know to work well :-)
  103353. */
  103354. set: function (value) {
  103355. var reflectionWeight = value;
  103356. if (reflectionWeight < 0.5) {
  103357. reflectionWeight = reflectionWeight * 2.0;
  103358. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  103359. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  103360. }
  103361. else {
  103362. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  103363. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  103364. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  103365. }
  103366. },
  103367. enumerable: true,
  103368. configurable: true
  103369. });
  103370. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  103371. /**
  103372. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103373. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  103374. * Recommended to be keep at 1.0 except for special cases.
  103375. */
  103376. get: function () {
  103377. return this._fovMultiplier;
  103378. },
  103379. set: function (value) {
  103380. if (isNaN(value)) {
  103381. value = 1.0;
  103382. }
  103383. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  103384. },
  103385. enumerable: true,
  103386. configurable: true
  103387. });
  103388. /**
  103389. * Attaches a new image processing configuration to the PBR Material.
  103390. * @param configuration (if null the scene configuration will be use)
  103391. */
  103392. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  103393. var _this = this;
  103394. if (configuration === this._imageProcessingConfiguration) {
  103395. return;
  103396. }
  103397. // Detaches observer.
  103398. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  103399. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  103400. }
  103401. // Pick the scene configuration if needed.
  103402. if (!configuration) {
  103403. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  103404. }
  103405. else {
  103406. this._imageProcessingConfiguration = configuration;
  103407. }
  103408. // Attaches observer.
  103409. if (this._imageProcessingConfiguration) {
  103410. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  103411. _this._computePrimaryColorFromPerceptualColor();
  103412. _this._markAllSubMeshesAsImageProcessingDirty();
  103413. });
  103414. }
  103415. };
  103416. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  103417. /**
  103418. * Gets the image processing configuration used either in this material.
  103419. */
  103420. get: function () {
  103421. return this._imageProcessingConfiguration;
  103422. },
  103423. /**
  103424. * Sets the Default image processing configuration used either in the this material.
  103425. *
  103426. * If sets to null, the scene one is in use.
  103427. */
  103428. set: function (value) {
  103429. this._attachImageProcessingConfiguration(value);
  103430. // Ensure the effect will be rebuilt.
  103431. this._markAllSubMeshesAsTexturesDirty();
  103432. },
  103433. enumerable: true,
  103434. configurable: true
  103435. });
  103436. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  103437. /**
  103438. * Gets wether the color curves effect is enabled.
  103439. */
  103440. get: function () {
  103441. return this.imageProcessingConfiguration.colorCurvesEnabled;
  103442. },
  103443. /**
  103444. * Sets wether the color curves effect is enabled.
  103445. */
  103446. set: function (value) {
  103447. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  103448. },
  103449. enumerable: true,
  103450. configurable: true
  103451. });
  103452. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  103453. /**
  103454. * Gets wether the color grading effect is enabled.
  103455. */
  103456. get: function () {
  103457. return this.imageProcessingConfiguration.colorGradingEnabled;
  103458. },
  103459. /**
  103460. * Gets wether the color grading effect is enabled.
  103461. */
  103462. set: function (value) {
  103463. this.imageProcessingConfiguration.colorGradingEnabled = value;
  103464. },
  103465. enumerable: true,
  103466. configurable: true
  103467. });
  103468. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  103469. /**
  103470. * Gets wether tonemapping is enabled or not.
  103471. */
  103472. get: function () {
  103473. return this._imageProcessingConfiguration.toneMappingEnabled;
  103474. },
  103475. /**
  103476. * Sets wether tonemapping is enabled or not
  103477. */
  103478. set: function (value) {
  103479. this._imageProcessingConfiguration.toneMappingEnabled = value;
  103480. },
  103481. enumerable: true,
  103482. configurable: true
  103483. });
  103484. ;
  103485. ;
  103486. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  103487. /**
  103488. * The camera exposure used on this material.
  103489. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  103490. * This corresponds to a photographic exposure.
  103491. */
  103492. get: function () {
  103493. return this._imageProcessingConfiguration.exposure;
  103494. },
  103495. /**
  103496. * The camera exposure used on this material.
  103497. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  103498. * This corresponds to a photographic exposure.
  103499. */
  103500. set: function (value) {
  103501. this._imageProcessingConfiguration.exposure = value;
  103502. },
  103503. enumerable: true,
  103504. configurable: true
  103505. });
  103506. ;
  103507. ;
  103508. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  103509. /**
  103510. * Gets The camera contrast used on this material.
  103511. */
  103512. get: function () {
  103513. return this._imageProcessingConfiguration.contrast;
  103514. },
  103515. /**
  103516. * Sets The camera contrast used on this material.
  103517. */
  103518. set: function (value) {
  103519. this._imageProcessingConfiguration.contrast = value;
  103520. },
  103521. enumerable: true,
  103522. configurable: true
  103523. });
  103524. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  103525. /**
  103526. * Gets the Color Grading 2D Lookup Texture.
  103527. */
  103528. get: function () {
  103529. return this._imageProcessingConfiguration.colorGradingTexture;
  103530. },
  103531. /**
  103532. * Sets the Color Grading 2D Lookup Texture.
  103533. */
  103534. set: function (value) {
  103535. this.imageProcessingConfiguration.colorGradingTexture = value;
  103536. },
  103537. enumerable: true,
  103538. configurable: true
  103539. });
  103540. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  103541. /**
  103542. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  103543. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  103544. * 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;
  103545. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  103546. */
  103547. get: function () {
  103548. return this.imageProcessingConfiguration.colorCurves;
  103549. },
  103550. /**
  103551. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  103552. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  103553. * 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;
  103554. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  103555. */
  103556. set: function (value) {
  103557. this.imageProcessingConfiguration.colorCurves = value;
  103558. },
  103559. enumerable: true,
  103560. configurable: true
  103561. });
  103562. /**
  103563. * The entire material has been created in order to prevent overdraw.
  103564. * @returns false
  103565. */
  103566. BackgroundMaterial.prototype.needAlphaTesting = function () {
  103567. return true;
  103568. };
  103569. /**
  103570. * The entire material has been created in order to prevent overdraw.
  103571. * @returns true if blending is enable
  103572. */
  103573. BackgroundMaterial.prototype.needAlphaBlending = function () {
  103574. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  103575. };
  103576. /**
  103577. * Checks wether the material is ready to be rendered for a given mesh.
  103578. * @param mesh The mesh to render
  103579. * @param subMesh The submesh to check against
  103580. * @param useInstances Specify wether or not the material is used with instances
  103581. * @returns true if all the dependencies are ready (Textures, Effects...)
  103582. */
  103583. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  103584. var _this = this;
  103585. if (useInstances === void 0) { useInstances = false; }
  103586. if (subMesh.effect && this.isFrozen) {
  103587. if (this._wasPreviouslyReady) {
  103588. return true;
  103589. }
  103590. }
  103591. if (!subMesh._materialDefines) {
  103592. subMesh._materialDefines = new BackgroundMaterialDefines();
  103593. }
  103594. var scene = this.getScene();
  103595. var defines = subMesh._materialDefines;
  103596. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  103597. if (defines._renderId === scene.getRenderId()) {
  103598. return true;
  103599. }
  103600. }
  103601. var engine = scene.getEngine();
  103602. // Lights
  103603. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  103604. defines._needNormals = true;
  103605. // Textures
  103606. if (defines._areTexturesDirty) {
  103607. defines._needUVs = false;
  103608. if (scene.texturesEnabled) {
  103609. if (scene.getEngine().getCaps().textureLOD) {
  103610. defines.TEXTURELODSUPPORT = true;
  103611. }
  103612. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103613. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  103614. return false;
  103615. }
  103616. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  103617. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  103618. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  103619. defines.OPACITYFRESNEL = this._opacityFresnel;
  103620. }
  103621. else {
  103622. defines.DIFFUSE = false;
  103623. defines.DIFFUSEHASALPHA = false;
  103624. defines.GAMMADIFFUSE = false;
  103625. defines.OPACITYFRESNEL = false;
  103626. }
  103627. var reflectionTexture = this._reflectionTexture;
  103628. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103629. if (!reflectionTexture.isReadyOrNotBlocking()) {
  103630. return false;
  103631. }
  103632. defines.REFLECTION = true;
  103633. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  103634. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  103635. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  103636. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  103637. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  103638. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  103639. defines.REFLECTIONBGR = this.switchToBGR;
  103640. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  103641. defines.INVERTCUBICMAP = true;
  103642. }
  103643. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  103644. switch (reflectionTexture.coordinatesMode) {
  103645. case BABYLON.Texture.EXPLICIT_MODE:
  103646. defines.REFLECTIONMAP_EXPLICIT = true;
  103647. break;
  103648. case BABYLON.Texture.PLANAR_MODE:
  103649. defines.REFLECTIONMAP_PLANAR = true;
  103650. break;
  103651. case BABYLON.Texture.PROJECTION_MODE:
  103652. defines.REFLECTIONMAP_PROJECTION = true;
  103653. break;
  103654. case BABYLON.Texture.SKYBOX_MODE:
  103655. defines.REFLECTIONMAP_SKYBOX = true;
  103656. break;
  103657. case BABYLON.Texture.SPHERICAL_MODE:
  103658. defines.REFLECTIONMAP_SPHERICAL = true;
  103659. break;
  103660. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  103661. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  103662. break;
  103663. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  103664. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  103665. break;
  103666. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  103667. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  103668. break;
  103669. case BABYLON.Texture.CUBIC_MODE:
  103670. case BABYLON.Texture.INVCUBIC_MODE:
  103671. default:
  103672. defines.REFLECTIONMAP_CUBIC = true;
  103673. break;
  103674. }
  103675. if (this.reflectionFresnel) {
  103676. defines.REFLECTIONFRESNEL = true;
  103677. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  103678. this._reflectionControls.x = this.reflectionAmount;
  103679. this._reflectionControls.y = this.reflectionReflectance0;
  103680. this._reflectionControls.z = this.reflectionReflectance90;
  103681. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  103682. }
  103683. else {
  103684. defines.REFLECTIONFRESNEL = false;
  103685. defines.REFLECTIONFALLOFF = false;
  103686. }
  103687. }
  103688. else {
  103689. defines.REFLECTION = false;
  103690. defines.REFLECTIONFRESNEL = false;
  103691. defines.REFLECTIONFALLOFF = false;
  103692. defines.REFLECTIONBLUR = false;
  103693. defines.REFLECTIONMAP_3D = false;
  103694. defines.REFLECTIONMAP_SPHERICAL = false;
  103695. defines.REFLECTIONMAP_PLANAR = false;
  103696. defines.REFLECTIONMAP_CUBIC = false;
  103697. defines.REFLECTIONMAP_PROJECTION = false;
  103698. defines.REFLECTIONMAP_SKYBOX = false;
  103699. defines.REFLECTIONMAP_EXPLICIT = false;
  103700. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  103701. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  103702. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  103703. defines.INVERTCUBICMAP = false;
  103704. defines.REFLECTIONMAP_OPPOSITEZ = false;
  103705. defines.LODINREFLECTIONALPHA = false;
  103706. defines.GAMMAREFLECTION = false;
  103707. defines.RGBDREFLECTION = false;
  103708. }
  103709. }
  103710. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  103711. defines.USERGBCOLOR = this._useRGBColor;
  103712. defines.NOISE = this._enableNoise;
  103713. }
  103714. if (defines._areLightsDirty) {
  103715. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  103716. }
  103717. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  103718. if (!this._imageProcessingConfiguration.isReady()) {
  103719. return false;
  103720. }
  103721. this._imageProcessingConfiguration.prepareDefines(defines);
  103722. }
  103723. // Misc.
  103724. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  103725. // Values that need to be evaluated on every frame
  103726. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  103727. // Attribs
  103728. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  103729. if (mesh) {
  103730. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  103731. mesh.createNormals(true);
  103732. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  103733. }
  103734. }
  103735. }
  103736. // Get correct effect
  103737. if (defines.isDirty) {
  103738. defines.markAsProcessed();
  103739. scene.resetCachedMaterial();
  103740. // Fallbacks
  103741. var fallbacks = new BABYLON.EffectFallbacks();
  103742. if (defines.FOG) {
  103743. fallbacks.addFallback(0, "FOG");
  103744. }
  103745. if (defines.POINTSIZE) {
  103746. fallbacks.addFallback(1, "POINTSIZE");
  103747. }
  103748. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  103749. if (defines.NUM_BONE_INFLUENCERS > 0) {
  103750. fallbacks.addCPUSkinningFallback(0, mesh);
  103751. }
  103752. //Attributes
  103753. var attribs = [BABYLON.VertexBuffer.PositionKind];
  103754. if (defines.NORMAL) {
  103755. attribs.push(BABYLON.VertexBuffer.NormalKind);
  103756. }
  103757. if (defines.UV1) {
  103758. attribs.push(BABYLON.VertexBuffer.UVKind);
  103759. }
  103760. if (defines.UV2) {
  103761. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  103762. }
  103763. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  103764. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  103765. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  103766. "vFogInfos", "vFogColor", "pointSize",
  103767. "vClipPlane", "mBones",
  103768. "vPrimaryColor", "vPrimaryColorShadow",
  103769. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  103770. "shadowLevel", "alpha",
  103771. "vBackgroundCenter", "vReflectionControl",
  103772. "vDiffuseInfos", "diffuseMatrix",
  103773. ];
  103774. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  103775. var uniformBuffers = ["Material", "Scene"];
  103776. if (BABYLON.ImageProcessingConfiguration) {
  103777. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  103778. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  103779. }
  103780. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  103781. uniformsNames: uniforms,
  103782. uniformBuffersNames: uniformBuffers,
  103783. samplers: samplers,
  103784. defines: defines,
  103785. maxSimultaneousLights: this._maxSimultaneousLights
  103786. });
  103787. var onCompiled = function (effect) {
  103788. if (_this.onCompiled) {
  103789. _this.onCompiled(effect);
  103790. }
  103791. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  103792. };
  103793. var join = defines.toString();
  103794. subMesh.setEffect(scene.getEngine().createEffect("background", {
  103795. attributes: attribs,
  103796. uniformsNames: uniforms,
  103797. uniformBuffersNames: uniformBuffers,
  103798. samplers: samplers,
  103799. defines: join,
  103800. fallbacks: fallbacks,
  103801. onCompiled: onCompiled,
  103802. onError: this.onError,
  103803. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  103804. }, engine), defines);
  103805. this.buildUniformLayout();
  103806. }
  103807. if (!subMesh.effect || !subMesh.effect.isReady()) {
  103808. return false;
  103809. }
  103810. defines._renderId = scene.getRenderId();
  103811. this._wasPreviouslyReady = true;
  103812. return true;
  103813. };
  103814. /**
  103815. * Compute the primary color according to the chosen perceptual color.
  103816. */
  103817. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  103818. if (!this.__perceptualColor) {
  103819. return;
  103820. }
  103821. this._primaryColor.copyFrom(this.__perceptualColor);
  103822. // Revert gamma space.
  103823. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  103824. // Revert image processing configuration.
  103825. if (this._imageProcessingConfiguration) {
  103826. // Revert Exposure.
  103827. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  103828. }
  103829. this._computePrimaryColors();
  103830. };
  103831. /**
  103832. * Compute the highlights and shadow colors according to their chosen levels.
  103833. */
  103834. BackgroundMaterial.prototype._computePrimaryColors = function () {
  103835. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  103836. return;
  103837. }
  103838. // Find the highlight color based on the configuration.
  103839. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  103840. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  103841. // Find the shadow color based on the configuration.
  103842. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  103843. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  103844. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  103845. };
  103846. /**
  103847. * Build the uniform buffer used in the material.
  103848. */
  103849. BackgroundMaterial.prototype.buildUniformLayout = function () {
  103850. // Order is important !
  103851. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  103852. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  103853. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  103854. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  103855. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  103856. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  103857. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  103858. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  103859. this._uniformBuffer.addUniform("pointSize", 1);
  103860. this._uniformBuffer.addUniform("shadowLevel", 1);
  103861. this._uniformBuffer.addUniform("alpha", 1);
  103862. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  103863. this._uniformBuffer.addUniform("vReflectionControl", 4);
  103864. this._uniformBuffer.create();
  103865. };
  103866. /**
  103867. * Unbind the material.
  103868. */
  103869. BackgroundMaterial.prototype.unbind = function () {
  103870. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  103871. this._uniformBuffer.setTexture("diffuseSampler", null);
  103872. }
  103873. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  103874. this._uniformBuffer.setTexture("reflectionSampler", null);
  103875. }
  103876. _super.prototype.unbind.call(this);
  103877. };
  103878. /**
  103879. * Bind only the world matrix to the material.
  103880. * @param world The world matrix to bind.
  103881. */
  103882. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  103883. this._activeEffect.setMatrix("world", world);
  103884. };
  103885. /**
  103886. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  103887. * @param world The world matrix to bind.
  103888. * @param subMesh The submesh to bind for.
  103889. */
  103890. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  103891. var scene = this.getScene();
  103892. var defines = subMesh._materialDefines;
  103893. if (!defines) {
  103894. return;
  103895. }
  103896. var effect = subMesh.effect;
  103897. if (!effect) {
  103898. return;
  103899. }
  103900. this._activeEffect = effect;
  103901. // Matrices
  103902. this.bindOnlyWorldMatrix(world);
  103903. // Bones
  103904. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  103905. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  103906. if (mustRebind) {
  103907. this._uniformBuffer.bindToEffect(effect, "Material");
  103908. this.bindViewProjection(effect);
  103909. var reflectionTexture = this._reflectionTexture;
  103910. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  103911. // Texture uniforms
  103912. if (scene.texturesEnabled) {
  103913. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103914. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  103915. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  103916. }
  103917. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103918. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  103919. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  103920. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  103921. }
  103922. }
  103923. if (this.shadowLevel > 0) {
  103924. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  103925. }
  103926. this._uniformBuffer.updateFloat("alpha", this.alpha);
  103927. // Point size
  103928. if (this.pointsCloud) {
  103929. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  103930. }
  103931. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  103932. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  103933. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  103934. }
  103935. else {
  103936. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  103937. }
  103938. }
  103939. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  103940. // Textures
  103941. if (scene.texturesEnabled) {
  103942. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103943. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  103944. }
  103945. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103946. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  103947. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103948. }
  103949. else if (!defines.REFLECTIONBLUR) {
  103950. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103951. }
  103952. else {
  103953. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  103954. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  103955. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  103956. }
  103957. if (defines.REFLECTIONFRESNEL) {
  103958. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  103959. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  103960. }
  103961. }
  103962. }
  103963. // Clip plane
  103964. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  103965. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  103966. }
  103967. if (mustRebind || !this.isFrozen) {
  103968. if (scene.lightsEnabled) {
  103969. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  103970. }
  103971. // View
  103972. this.bindView(effect);
  103973. // Fog
  103974. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  103975. // image processing
  103976. if (this._imageProcessingConfiguration) {
  103977. this._imageProcessingConfiguration.bind(this._activeEffect);
  103978. }
  103979. }
  103980. this._uniformBuffer.update();
  103981. this._afterBind(mesh, this._activeEffect);
  103982. };
  103983. /**
  103984. * Dispose the material.
  103985. * @param forceDisposeEffect Force disposal of the associated effect.
  103986. * @param forceDisposeTextures Force disposal of the associated textures.
  103987. */
  103988. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  103989. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  103990. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  103991. if (forceDisposeTextures) {
  103992. if (this.diffuseTexture) {
  103993. this.diffuseTexture.dispose();
  103994. }
  103995. if (this.reflectionTexture) {
  103996. this.reflectionTexture.dispose();
  103997. }
  103998. }
  103999. this._renderTargets.dispose();
  104000. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  104001. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  104002. }
  104003. _super.prototype.dispose.call(this, forceDisposeEffect);
  104004. };
  104005. /**
  104006. * Clones the material.
  104007. * @param name The cloned name.
  104008. * @returns The cloned material.
  104009. */
  104010. BackgroundMaterial.prototype.clone = function (name) {
  104011. var _this = this;
  104012. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  104013. };
  104014. /**
  104015. * Serializes the current material to its JSON representation.
  104016. * @returns The JSON representation.
  104017. */
  104018. BackgroundMaterial.prototype.serialize = function () {
  104019. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  104020. serializationObject.customType = "BABYLON.BackgroundMaterial";
  104021. return serializationObject;
  104022. };
  104023. /**
  104024. * Gets the class name of the material
  104025. * @returns "BackgroundMaterial"
  104026. */
  104027. BackgroundMaterial.prototype.getClassName = function () {
  104028. return "BackgroundMaterial";
  104029. };
  104030. /**
  104031. * Parse a JSON input to create back a background material.
  104032. * @param source The JSON data to parse
  104033. * @param scene The scene to create the parsed material in
  104034. * @param rootUrl The root url of the assets the material depends upon
  104035. * @returns the instantiated BackgroundMaterial.
  104036. */
  104037. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  104038. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  104039. };
  104040. /**
  104041. * Standard reflectance value at parallel view angle.
  104042. */
  104043. BackgroundMaterial.StandardReflectance0 = 0.05;
  104044. /**
  104045. * Standard reflectance value at grazing angle.
  104046. */
  104047. BackgroundMaterial.StandardReflectance90 = 0.5;
  104048. __decorate([
  104049. BABYLON.serializeAsColor3()
  104050. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  104051. __decorate([
  104052. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  104053. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  104054. __decorate([
  104055. BABYLON.serializeAsColor3()
  104056. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  104057. __decorate([
  104058. BABYLON.serialize()
  104059. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  104060. __decorate([
  104061. BABYLON.serialize()
  104062. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  104063. __decorate([
  104064. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  104065. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  104066. __decorate([
  104067. BABYLON.serializeAsTexture()
  104068. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  104069. __decorate([
  104070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104071. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  104072. __decorate([
  104073. BABYLON.serialize()
  104074. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  104075. __decorate([
  104076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104077. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  104078. __decorate([
  104079. BABYLON.serializeAsTexture()
  104080. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  104081. __decorate([
  104082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104083. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  104084. __decorate([
  104085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104086. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  104087. __decorate([
  104088. BABYLON.serialize()
  104089. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  104090. __decorate([
  104091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104092. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  104093. __decorate([
  104094. BABYLON.serializeAsVector3()
  104095. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  104096. __decorate([
  104097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104098. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  104099. __decorate([
  104100. BABYLON.serialize()
  104101. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  104102. __decorate([
  104103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104104. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  104105. __decorate([
  104106. BABYLON.serialize()
  104107. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  104108. __decorate([
  104109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104110. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  104111. __decorate([
  104112. BABYLON.serialize()
  104113. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  104114. __decorate([
  104115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104116. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  104117. __decorate([
  104118. BABYLON.serialize()
  104119. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  104120. __decorate([
  104121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104122. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  104123. __decorate([
  104124. BABYLON.serialize()
  104125. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  104126. __decorate([
  104127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104128. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  104129. __decorate([
  104130. BABYLON.serialize()
  104131. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  104132. __decorate([
  104133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104134. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  104135. __decorate([
  104136. BABYLON.serialize()
  104137. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  104138. __decorate([
  104139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104140. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  104141. __decorate([
  104142. BABYLON.serialize()
  104143. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  104144. __decorate([
  104145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104146. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  104147. __decorate([
  104148. BABYLON.serialize()
  104149. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  104150. __decorate([
  104151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104152. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  104153. __decorate([
  104154. BABYLON.serializeAsImageProcessingConfiguration()
  104155. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  104156. return BackgroundMaterial;
  104157. }(BABYLON.PushMaterial));
  104158. BABYLON.BackgroundMaterial = BackgroundMaterial;
  104159. })(BABYLON || (BABYLON = {}));
  104160. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  104161. var __assign = (this && this.__assign) || Object.assign || function(t) {
  104162. for (var s, i = 1, n = arguments.length; i < n; i++) {
  104163. s = arguments[i];
  104164. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  104165. t[p] = s[p];
  104166. }
  104167. return t;
  104168. };
  104169. var BABYLON;
  104170. (function (BABYLON) {
  104171. /**
  104172. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  104173. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  104174. * It also helps with the default setup of your imageProcessing configuration.
  104175. */
  104176. var EnvironmentHelper = /** @class */ (function () {
  104177. /**
  104178. * constructor
  104179. * @param options
  104180. * @param scene The scene to add the material to
  104181. */
  104182. function EnvironmentHelper(options, scene) {
  104183. var _this = this;
  104184. this._errorHandler = function (message, exception) {
  104185. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  104186. };
  104187. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  104188. this._scene = scene;
  104189. this.onErrorObservable = new BABYLON.Observable();
  104190. this._setupBackground();
  104191. this._setupImageProcessing();
  104192. }
  104193. /**
  104194. * Creates the default options for the helper.
  104195. */
  104196. EnvironmentHelper._getDefaultOptions = function () {
  104197. return {
  104198. createGround: true,
  104199. groundSize: 15,
  104200. groundTexture: this._groundTextureCDNUrl,
  104201. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  104202. groundOpacity: 0.9,
  104203. enableGroundShadow: true,
  104204. groundShadowLevel: 0.5,
  104205. enableGroundMirror: false,
  104206. groundMirrorSizeRatio: 0.3,
  104207. groundMirrorBlurKernel: 64,
  104208. groundMirrorAmount: 1,
  104209. groundMirrorFresnelWeight: 1,
  104210. groundMirrorFallOffDistance: 0,
  104211. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  104212. groundYBias: 0.00001,
  104213. createSkybox: true,
  104214. skyboxSize: 20,
  104215. skyboxTexture: this._skyboxTextureCDNUrl,
  104216. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  104217. backgroundYRotation: 0,
  104218. sizeAuto: true,
  104219. rootPosition: BABYLON.Vector3.Zero(),
  104220. setupImageProcessing: true,
  104221. environmentTexture: this._environmentTextureCDNUrl,
  104222. cameraExposure: 0.8,
  104223. cameraContrast: 1.2,
  104224. toneMappingEnabled: true,
  104225. };
  104226. };
  104227. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  104228. /**
  104229. * Gets the root mesh created by the helper.
  104230. */
  104231. get: function () {
  104232. return this._rootMesh;
  104233. },
  104234. enumerable: true,
  104235. configurable: true
  104236. });
  104237. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  104238. /**
  104239. * Gets the skybox created by the helper.
  104240. */
  104241. get: function () {
  104242. return this._skybox;
  104243. },
  104244. enumerable: true,
  104245. configurable: true
  104246. });
  104247. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  104248. /**
  104249. * Gets the skybox texture created by the helper.
  104250. */
  104251. get: function () {
  104252. return this._skyboxTexture;
  104253. },
  104254. enumerable: true,
  104255. configurable: true
  104256. });
  104257. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  104258. /**
  104259. * Gets the skybox material created by the helper.
  104260. */
  104261. get: function () {
  104262. return this._skyboxMaterial;
  104263. },
  104264. enumerable: true,
  104265. configurable: true
  104266. });
  104267. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  104268. /**
  104269. * Gets the ground mesh created by the helper.
  104270. */
  104271. get: function () {
  104272. return this._ground;
  104273. },
  104274. enumerable: true,
  104275. configurable: true
  104276. });
  104277. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  104278. /**
  104279. * Gets the ground texture created by the helper.
  104280. */
  104281. get: function () {
  104282. return this._groundTexture;
  104283. },
  104284. enumerable: true,
  104285. configurable: true
  104286. });
  104287. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  104288. /**
  104289. * Gets the ground mirror created by the helper.
  104290. */
  104291. get: function () {
  104292. return this._groundMirror;
  104293. },
  104294. enumerable: true,
  104295. configurable: true
  104296. });
  104297. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  104298. /**
  104299. * Gets the ground mirror render list to helps pushing the meshes
  104300. * you wish in the ground reflection.
  104301. */
  104302. get: function () {
  104303. if (this._groundMirror) {
  104304. return this._groundMirror.renderList;
  104305. }
  104306. return null;
  104307. },
  104308. enumerable: true,
  104309. configurable: true
  104310. });
  104311. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  104312. /**
  104313. * Gets the ground material created by the helper.
  104314. */
  104315. get: function () {
  104316. return this._groundMaterial;
  104317. },
  104318. enumerable: true,
  104319. configurable: true
  104320. });
  104321. /**
  104322. * Updates the background according to the new options
  104323. * @param options
  104324. */
  104325. EnvironmentHelper.prototype.updateOptions = function (options) {
  104326. var newOptions = __assign({}, this._options, options);
  104327. if (this._ground && !newOptions.createGround) {
  104328. this._ground.dispose();
  104329. this._ground = null;
  104330. }
  104331. if (this._groundMaterial && !newOptions.createGround) {
  104332. this._groundMaterial.dispose();
  104333. this._groundMaterial = null;
  104334. }
  104335. if (this._groundTexture) {
  104336. if (this._options.groundTexture != newOptions.groundTexture) {
  104337. this._groundTexture.dispose();
  104338. this._groundTexture = null;
  104339. }
  104340. }
  104341. if (this._skybox && !newOptions.createSkybox) {
  104342. this._skybox.dispose();
  104343. this._skybox = null;
  104344. }
  104345. if (this._skyboxMaterial && !newOptions.createSkybox) {
  104346. this._skyboxMaterial.dispose();
  104347. this._skyboxMaterial = null;
  104348. }
  104349. if (this._skyboxTexture) {
  104350. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  104351. this._skyboxTexture.dispose();
  104352. this._skyboxTexture = null;
  104353. }
  104354. }
  104355. if (this._groundMirror && !newOptions.enableGroundMirror) {
  104356. this._groundMirror.dispose();
  104357. this._groundMirror = null;
  104358. }
  104359. if (this._scene.environmentTexture) {
  104360. if (this._options.environmentTexture != newOptions.environmentTexture) {
  104361. this._scene.environmentTexture.dispose();
  104362. }
  104363. }
  104364. this._options = newOptions;
  104365. this._setupBackground();
  104366. this._setupImageProcessing();
  104367. };
  104368. /**
  104369. * Sets the primary color of all the available elements.
  104370. * @param color the main color to affect to the ground and the background
  104371. */
  104372. EnvironmentHelper.prototype.setMainColor = function (color) {
  104373. if (this.groundMaterial) {
  104374. this.groundMaterial.primaryColor = color;
  104375. }
  104376. if (this.skyboxMaterial) {
  104377. this.skyboxMaterial.primaryColor = color;
  104378. }
  104379. if (this.groundMirror) {
  104380. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  104381. }
  104382. };
  104383. /**
  104384. * Setup the image processing according to the specified options.
  104385. */
  104386. EnvironmentHelper.prototype._setupImageProcessing = function () {
  104387. if (this._options.setupImageProcessing) {
  104388. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  104389. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  104390. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  104391. this._setupEnvironmentTexture();
  104392. }
  104393. };
  104394. /**
  104395. * Setup the environment texture according to the specified options.
  104396. */
  104397. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  104398. if (this._scene.environmentTexture) {
  104399. return;
  104400. }
  104401. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  104402. this._scene.environmentTexture = this._options.environmentTexture;
  104403. return;
  104404. }
  104405. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  104406. this._scene.environmentTexture = environmentTexture;
  104407. };
  104408. /**
  104409. * Setup the background according to the specified options.
  104410. */
  104411. EnvironmentHelper.prototype._setupBackground = function () {
  104412. if (!this._rootMesh) {
  104413. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  104414. }
  104415. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  104416. var sceneSize = this._getSceneSize();
  104417. if (this._options.createGround) {
  104418. this._setupGround(sceneSize);
  104419. this._setupGroundMaterial();
  104420. this._setupGroundDiffuseTexture();
  104421. if (this._options.enableGroundMirror) {
  104422. this._setupGroundMirrorTexture(sceneSize);
  104423. }
  104424. this._setupMirrorInGroundMaterial();
  104425. }
  104426. if (this._options.createSkybox) {
  104427. this._setupSkybox(sceneSize);
  104428. this._setupSkyboxMaterial();
  104429. this._setupSkyboxReflectionTexture();
  104430. }
  104431. this._rootMesh.position.x = sceneSize.rootPosition.x;
  104432. this._rootMesh.position.z = sceneSize.rootPosition.z;
  104433. this._rootMesh.position.y = sceneSize.rootPosition.y;
  104434. };
  104435. /**
  104436. * Get the scene sizes according to the setup.
  104437. */
  104438. EnvironmentHelper.prototype._getSceneSize = function () {
  104439. var _this = this;
  104440. var groundSize = this._options.groundSize;
  104441. var skyboxSize = this._options.skyboxSize;
  104442. var rootPosition = this._options.rootPosition;
  104443. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  104444. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  104445. }
  104446. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  104447. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  104448. });
  104449. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  104450. if (this._options.sizeAuto) {
  104451. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  104452. this._scene.activeCamera.upperRadiusLimit) {
  104453. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  104454. skyboxSize = groundSize;
  104455. }
  104456. var sceneDiagonalLenght = sceneDiagonal.length();
  104457. if (sceneDiagonalLenght > groundSize) {
  104458. groundSize = sceneDiagonalLenght * 2;
  104459. skyboxSize = groundSize;
  104460. }
  104461. // 10 % bigger.
  104462. groundSize *= 1.1;
  104463. skyboxSize *= 1.5;
  104464. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  104465. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  104466. }
  104467. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  104468. };
  104469. /**
  104470. * Setup the ground according to the specified options.
  104471. */
  104472. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  104473. var _this = this;
  104474. if (!this._ground || this._ground.isDisposed()) {
  104475. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  104476. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  104477. this._ground.parent = this._rootMesh;
  104478. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  104479. }
  104480. this._ground.receiveShadows = this._options.enableGroundShadow;
  104481. };
  104482. /**
  104483. * Setup the ground material according to the specified options.
  104484. */
  104485. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  104486. if (!this._groundMaterial) {
  104487. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  104488. }
  104489. this._groundMaterial.alpha = this._options.groundOpacity;
  104490. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  104491. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  104492. this._groundMaterial.primaryColor = this._options.groundColor;
  104493. this._groundMaterial.useRGBColor = false;
  104494. this._groundMaterial.enableNoise = true;
  104495. if (this._ground) {
  104496. this._ground.material = this._groundMaterial;
  104497. }
  104498. };
  104499. /**
  104500. * Setup the ground diffuse texture according to the specified options.
  104501. */
  104502. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  104503. if (!this._groundMaterial) {
  104504. return;
  104505. }
  104506. if (this._groundTexture) {
  104507. return;
  104508. }
  104509. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  104510. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  104511. return;
  104512. }
  104513. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  104514. diffuseTexture.gammaSpace = false;
  104515. diffuseTexture.hasAlpha = true;
  104516. this._groundMaterial.diffuseTexture = diffuseTexture;
  104517. };
  104518. /**
  104519. * Setup the ground mirror texture according to the specified options.
  104520. */
  104521. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  104522. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104523. if (!this._groundMirror) {
  104524. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  104525. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  104526. this._groundMirror.anisotropicFilteringLevel = 1;
  104527. this._groundMirror.wrapU = wrapping;
  104528. this._groundMirror.wrapV = wrapping;
  104529. this._groundMirror.gammaSpace = false;
  104530. if (this._groundMirror.renderList) {
  104531. for (var i = 0; i < this._scene.meshes.length; i++) {
  104532. var mesh = this._scene.meshes[i];
  104533. if (mesh !== this._ground &&
  104534. mesh !== this._skybox &&
  104535. mesh !== this._rootMesh) {
  104536. this._groundMirror.renderList.push(mesh);
  104537. }
  104538. }
  104539. }
  104540. }
  104541. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  104542. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  104543. };
  104544. /**
  104545. * Setup the ground to receive the mirror texture.
  104546. */
  104547. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  104548. if (this._groundMaterial) {
  104549. this._groundMaterial.reflectionTexture = this._groundMirror;
  104550. this._groundMaterial.reflectionFresnel = true;
  104551. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  104552. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  104553. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  104554. }
  104555. };
  104556. /**
  104557. * Setup the skybox according to the specified options.
  104558. */
  104559. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  104560. var _this = this;
  104561. if (!this._skybox || this._skybox.isDisposed()) {
  104562. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  104563. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  104564. }
  104565. this._skybox.parent = this._rootMesh;
  104566. };
  104567. /**
  104568. * Setup the skybox material according to the specified options.
  104569. */
  104570. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  104571. if (!this._skybox) {
  104572. return;
  104573. }
  104574. if (!this._skyboxMaterial) {
  104575. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  104576. }
  104577. this._skyboxMaterial.useRGBColor = false;
  104578. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  104579. this._skyboxMaterial.enableNoise = true;
  104580. this._skybox.material = this._skyboxMaterial;
  104581. };
  104582. /**
  104583. * Setup the skybox reflection texture according to the specified options.
  104584. */
  104585. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  104586. if (!this._skyboxMaterial) {
  104587. return;
  104588. }
  104589. if (this._skyboxTexture) {
  104590. return;
  104591. }
  104592. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  104593. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  104594. return;
  104595. }
  104596. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  104597. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  104598. this._skyboxTexture.gammaSpace = false;
  104599. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  104600. };
  104601. /**
  104602. * Dispose all the elements created by the Helper.
  104603. */
  104604. EnvironmentHelper.prototype.dispose = function () {
  104605. if (this._groundMaterial) {
  104606. this._groundMaterial.dispose(true, true);
  104607. }
  104608. if (this._skyboxMaterial) {
  104609. this._skyboxMaterial.dispose(true, true);
  104610. }
  104611. this._rootMesh.dispose(false);
  104612. };
  104613. /**
  104614. * Default ground texture URL.
  104615. */
  104616. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  104617. /**
  104618. * Default skybox texture URL.
  104619. */
  104620. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  104621. /**
  104622. * Default environment texture URL.
  104623. */
  104624. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  104625. return EnvironmentHelper;
  104626. }());
  104627. BABYLON.EnvironmentHelper = EnvironmentHelper;
  104628. })(BABYLON || (BABYLON = {}));
  104629. //# sourceMappingURL=babylon.environmentHelper.js.map
  104630. var BABYLON;
  104631. (function (BABYLON) {
  104632. /** Internal class used to store shapes for emitters */
  104633. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  104634. function ParticleSystemSetEmitterCreationOptions() {
  104635. }
  104636. return ParticleSystemSetEmitterCreationOptions;
  104637. }());
  104638. /**
  104639. * Represents a set of particle systems working together to create a specific effect
  104640. */
  104641. var ParticleSystemSet = /** @class */ (function () {
  104642. function ParticleSystemSet() {
  104643. /**
  104644. * Gets the particle system list
  104645. */
  104646. this.systems = new Array();
  104647. }
  104648. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  104649. /**
  104650. * Gets the emitter node used with this set
  104651. */
  104652. get: function () {
  104653. return this._emitterNode;
  104654. },
  104655. enumerable: true,
  104656. configurable: true
  104657. });
  104658. /**
  104659. * Creates a new emitter mesh as a sphere
  104660. * @param options defines the options used to create the sphere
  104661. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  104662. * @param scene defines the hosting scene
  104663. */
  104664. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  104665. if (this._emitterNode) {
  104666. this._emitterNode.dispose();
  104667. }
  104668. this._emitterCreationOptions = {
  104669. kind: "Sphere",
  104670. options: options,
  104671. renderingGroupId: renderingGroupId
  104672. };
  104673. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  104674. emitterMesh.renderingGroupId = renderingGroupId;
  104675. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  104676. material.emissiveColor = options.color;
  104677. emitterMesh.material = material;
  104678. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104679. var system = _a[_i];
  104680. system.emitter = emitterMesh;
  104681. }
  104682. this._emitterNode = emitterMesh;
  104683. };
  104684. /**
  104685. * Starts all particle systems of the set
  104686. * @param emitter defines an optional mesh to use as emitter for the particle systems
  104687. */
  104688. ParticleSystemSet.prototype.start = function (emitter) {
  104689. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104690. var system = _a[_i];
  104691. if (emitter) {
  104692. system.emitter = emitter;
  104693. }
  104694. system.start();
  104695. }
  104696. };
  104697. /**
  104698. * Release all associated resources
  104699. */
  104700. ParticleSystemSet.prototype.dispose = function () {
  104701. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104702. var system = _a[_i];
  104703. system.dispose();
  104704. }
  104705. this.systems = [];
  104706. if (this._emitterNode) {
  104707. this._emitterNode.dispose();
  104708. this._emitterNode = null;
  104709. }
  104710. };
  104711. /**
  104712. * Serialize the set into a JSON compatible object
  104713. * @returns a JSON compatible representation of the set
  104714. */
  104715. ParticleSystemSet.prototype.serialize = function () {
  104716. var result = {};
  104717. result.systems = [];
  104718. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104719. var system = _a[_i];
  104720. result.systems.push(system.serialize());
  104721. }
  104722. if (this._emitterNode) {
  104723. result.emitter = this._emitterCreationOptions;
  104724. }
  104725. return result;
  104726. };
  104727. /**
  104728. * Parse a new ParticleSystemSet from a serialized source
  104729. * @param data defines a JSON compatible representation of the set
  104730. * @param scene defines the hosting scene
  104731. * @param gpu defines if we want GPU particles or CPU particles
  104732. * @returns a new ParticleSystemSet
  104733. */
  104734. ParticleSystemSet.Parse = function (data, scene, gpu) {
  104735. if (gpu === void 0) { gpu = false; }
  104736. var result = new ParticleSystemSet();
  104737. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  104738. scene = scene || BABYLON.Engine.LastCreatedScene;
  104739. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  104740. var system = _a[_i];
  104741. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  104742. }
  104743. if (data.emitter) {
  104744. var options = data.emitter.options;
  104745. switch (data.emitter.kind) {
  104746. case "Sphere":
  104747. result.setEmitterAsSphere({
  104748. diameter: options.diameter,
  104749. segments: options.segments,
  104750. color: BABYLON.Color3.FromArray(options.color)
  104751. }, data.emitter.renderingGroupId, scene);
  104752. break;
  104753. }
  104754. }
  104755. return result;
  104756. };
  104757. return ParticleSystemSet;
  104758. }());
  104759. BABYLON.ParticleSystemSet = ParticleSystemSet;
  104760. })(BABYLON || (BABYLON = {}));
  104761. //# sourceMappingURL=babylon.particleSystemSet.js.map
  104762. var BABYLON;
  104763. (function (BABYLON) {
  104764. /**
  104765. * This class is made for on one-liner static method to help creating particle system set.
  104766. */
  104767. var ParticleHelper = /** @class */ (function () {
  104768. function ParticleHelper() {
  104769. }
  104770. /**
  104771. * Create a default particle system that you can tweak
  104772. * @param emitter defines the emitter to use
  104773. * @param capacity defines the system capacity (default is 500 particles)
  104774. * @param scene defines the hosting scene
  104775. * @returns the new Particle system
  104776. */
  104777. ParticleHelper.CreateDefault = function (emitter, capacity, scene) {
  104778. if (capacity === void 0) { capacity = 500; }
  104779. var system = new BABYLON.ParticleSystem("default system", capacity, scene);
  104780. system.emitter = emitter;
  104781. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  104782. system.createConeEmitter(0.1, Math.PI / 4);
  104783. // Particle color
  104784. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  104785. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  104786. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  104787. // Particle Size
  104788. system.minSize = 0.1;
  104789. system.maxSize = 0.1;
  104790. // Emission speed
  104791. system.minEmitPower = 2;
  104792. system.maxEmitPower = 2;
  104793. // Update speed
  104794. system.updateSpeed = 1 / 60;
  104795. system.emitRate = 30;
  104796. return system;
  104797. };
  104798. /**
  104799. * This is the main static method (one-liner) of this helper to create different particle systems
  104800. * @param type This string represents the type to the particle system to create
  104801. * @param scene The scene where the particle system should live
  104802. * @param gpu If the system will use gpu
  104803. * @returns the ParticleSystemSet created
  104804. */
  104805. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  104806. if (gpu === void 0) { gpu = false; }
  104807. if (!scene) {
  104808. scene = BABYLON.Engine.LastCreatedScene;
  104809. ;
  104810. }
  104811. var token = {};
  104812. scene._addPendingData(token);
  104813. return new Promise(function (resolve, reject) {
  104814. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  104815. scene._removePendingData(token);
  104816. return reject("Particle system with GPU is not supported.");
  104817. }
  104818. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  104819. scene._removePendingData(token);
  104820. var newData = JSON.parse(data.toString());
  104821. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  104822. }, undefined, undefined, undefined, function (req, exception) {
  104823. scene._removePendingData(token);
  104824. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  104825. });
  104826. });
  104827. };
  104828. /**
  104829. * Static function used to export a particle system to a ParticleSystemSet variable.
  104830. * Please note that the emitter shape is not exported
  104831. * @param system defines the particle systems to export
  104832. */
  104833. ParticleHelper.ExportSet = function (systems) {
  104834. var set = new BABYLON.ParticleSystemSet();
  104835. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  104836. var system = systems_1[_i];
  104837. set.systems.push(system);
  104838. }
  104839. return set;
  104840. };
  104841. /**
  104842. * Gets or sets base Assets URL
  104843. */
  104844. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  104845. return ParticleHelper;
  104846. }());
  104847. BABYLON.ParticleHelper = ParticleHelper;
  104848. })(BABYLON || (BABYLON = {}));
  104849. //# sourceMappingURL=babylon.particleHelper.js.map
  104850. var BABYLON;
  104851. (function (BABYLON) {
  104852. /**
  104853. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  104854. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  104855. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  104856. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104857. */
  104858. var VideoDome = /** @class */ (function (_super) {
  104859. __extends(VideoDome, _super);
  104860. /**
  104861. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  104862. * @param name Element's name, child elements will append suffixes for their own names.
  104863. * @param urlsOrVideo defines the url(s) or the video element to use
  104864. * @param options An object containing optional or exposed sub element properties
  104865. */
  104866. function VideoDome(name, urlsOrVideo, options, scene) {
  104867. var _this = _super.call(this, name, scene) || this;
  104868. _this._useDirectMapping = false;
  104869. // set defaults and manage values
  104870. name = name || "videoDome";
  104871. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104872. options.clickToPlay = Boolean(options.clickToPlay);
  104873. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  104874. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  104875. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104876. if (options.useDirectMapping === undefined) {
  104877. _this._useDirectMapping = true;
  104878. }
  104879. else {
  104880. _this._useDirectMapping = options.useDirectMapping;
  104881. }
  104882. _this._setReady(false);
  104883. // create
  104884. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  104885. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104886. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  104887. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104888. texture.onLoadObservable.addOnce(function () {
  104889. _this._setReady(true);
  104890. });
  104891. // configure material
  104892. material.useEquirectangularFOV = true;
  104893. material.fovMultiplier = 1.0;
  104894. material.opacityFresnel = false;
  104895. if (_this._useDirectMapping) {
  104896. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104897. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104898. material.diffuseTexture = texture;
  104899. }
  104900. else {
  104901. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104902. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104903. material.reflectionTexture = texture;
  104904. }
  104905. // configure mesh
  104906. _this._mesh.material = material;
  104907. _this._mesh.parent = _this;
  104908. // optional configuration
  104909. if (options.clickToPlay) {
  104910. scene.onPointerUp = function () {
  104911. _this._videoTexture.video.play();
  104912. };
  104913. }
  104914. return _this;
  104915. }
  104916. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  104917. /**
  104918. * Gets the video texture being displayed on the sphere
  104919. */
  104920. get: function () {
  104921. return this._videoTexture;
  104922. },
  104923. enumerable: true,
  104924. configurable: true
  104925. });
  104926. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  104927. /**
  104928. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104929. * Also see the options.resolution property.
  104930. */
  104931. get: function () {
  104932. return this._material.fovMultiplier;
  104933. },
  104934. set: function (value) {
  104935. this._material.fovMultiplier = value;
  104936. },
  104937. enumerable: true,
  104938. configurable: true
  104939. });
  104940. /**
  104941. * Releases resources associated with this node.
  104942. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104943. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104944. */
  104945. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104946. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104947. this._videoTexture.dispose();
  104948. this._mesh.dispose();
  104949. this._material.dispose();
  104950. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104951. };
  104952. return VideoDome;
  104953. }(BABYLON.Node));
  104954. BABYLON.VideoDome = VideoDome;
  104955. })(BABYLON || (BABYLON = {}));
  104956. //# sourceMappingURL=babylon.videoDome.js.map
  104957. var BABYLON;
  104958. (function (BABYLON) {
  104959. /**
  104960. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  104961. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  104962. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  104963. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104964. */
  104965. var PhotoDome = /** @class */ (function (_super) {
  104966. __extends(PhotoDome, _super);
  104967. /**
  104968. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  104969. * @param name Element's name, child elements will append suffixes for their own names.
  104970. * @param urlsOfPhoto define the url of the photo to display
  104971. * @param options An object containing optional or exposed sub element properties
  104972. */
  104973. function PhotoDome(name, urlOfPhoto, options, scene) {
  104974. var _this = _super.call(this, name, scene) || this;
  104975. _this._useDirectMapping = false;
  104976. // set defaults and manage values
  104977. name = name || "photoDome";
  104978. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104979. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104980. if (options.useDirectMapping === undefined) {
  104981. _this._useDirectMapping = true;
  104982. }
  104983. else {
  104984. _this._useDirectMapping = options.useDirectMapping;
  104985. }
  104986. _this._setReady(false);
  104987. // create
  104988. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104989. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104990. // configure material
  104991. material.opacityFresnel = false;
  104992. material.useEquirectangularFOV = true;
  104993. material.fovMultiplier = 1.0;
  104994. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  104995. _this.photoTexture.onLoadObservable.addOnce(function () {
  104996. _this._setReady(true);
  104997. });
  104998. // configure mesh
  104999. _this._mesh.material = material;
  105000. _this._mesh.parent = _this;
  105001. return _this;
  105002. }
  105003. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  105004. /**
  105005. * Gets or sets the texture being displayed on the sphere
  105006. */
  105007. get: function () {
  105008. return this._photoTexture;
  105009. },
  105010. set: function (value) {
  105011. if (this._photoTexture === value) {
  105012. return;
  105013. }
  105014. this._photoTexture = value;
  105015. if (this._useDirectMapping) {
  105016. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105017. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105018. this._material.diffuseTexture = this._photoTexture;
  105019. }
  105020. else {
  105021. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  105022. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105023. this._material.reflectionTexture = this._photoTexture;
  105024. }
  105025. },
  105026. enumerable: true,
  105027. configurable: true
  105028. });
  105029. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  105030. /**
  105031. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  105032. * Also see the options.resolution property.
  105033. */
  105034. get: function () {
  105035. return this._material.fovMultiplier;
  105036. },
  105037. set: function (value) {
  105038. this._material.fovMultiplier = value;
  105039. },
  105040. enumerable: true,
  105041. configurable: true
  105042. });
  105043. /**
  105044. * Releases resources associated with this node.
  105045. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  105046. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  105047. */
  105048. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  105049. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  105050. this._photoTexture.dispose();
  105051. this._mesh.dispose();
  105052. this._material.dispose();
  105053. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  105054. };
  105055. return PhotoDome;
  105056. }(BABYLON.Node));
  105057. BABYLON.PhotoDome = PhotoDome;
  105058. })(BABYLON || (BABYLON = {}));
  105059. //# sourceMappingURL=babylon.photoDome.js.map
  105060. var BABYLON;
  105061. (function (BABYLON) {
  105062. BABYLON.Engine.prototype.createQuery = function () {
  105063. return this._gl.createQuery();
  105064. };
  105065. BABYLON.Engine.prototype.deleteQuery = function (query) {
  105066. this._gl.deleteQuery(query);
  105067. return this;
  105068. };
  105069. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  105070. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  105071. };
  105072. BABYLON.Engine.prototype.getQueryResult = function (query) {
  105073. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  105074. };
  105075. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  105076. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  105077. this._gl.beginQuery(glAlgorithm, query);
  105078. return this;
  105079. };
  105080. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  105081. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  105082. this._gl.endQuery(glAlgorithm);
  105083. return this;
  105084. };
  105085. BABYLON.Engine.prototype._createTimeQuery = function () {
  105086. var timerQuery = this.getCaps().timerQuery;
  105087. if (timerQuery.createQueryEXT) {
  105088. return timerQuery.createQueryEXT();
  105089. }
  105090. return this.createQuery();
  105091. };
  105092. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  105093. var timerQuery = this.getCaps().timerQuery;
  105094. if (timerQuery.deleteQueryEXT) {
  105095. timerQuery.deleteQueryEXT(query);
  105096. return;
  105097. }
  105098. this.deleteQuery(query);
  105099. };
  105100. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  105101. var timerQuery = this.getCaps().timerQuery;
  105102. if (timerQuery.getQueryObjectEXT) {
  105103. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  105104. }
  105105. return this.getQueryResult(query);
  105106. };
  105107. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  105108. var timerQuery = this.getCaps().timerQuery;
  105109. if (timerQuery.getQueryObjectEXT) {
  105110. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  105111. }
  105112. return this.isQueryResultAvailable(query);
  105113. };
  105114. BABYLON.Engine.prototype.startTimeQuery = function () {
  105115. var caps = this.getCaps();
  105116. var timerQuery = caps.timerQuery;
  105117. if (!timerQuery) {
  105118. return null;
  105119. }
  105120. var token = new BABYLON._TimeToken();
  105121. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  105122. if (caps.canUseTimestampForTimerQuery) {
  105123. token._startTimeQuery = this._createTimeQuery();
  105124. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  105125. }
  105126. else {
  105127. if (this._currentNonTimestampToken) {
  105128. return this._currentNonTimestampToken;
  105129. }
  105130. token._timeElapsedQuery = this._createTimeQuery();
  105131. if (timerQuery.beginQueryEXT) {
  105132. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  105133. }
  105134. else {
  105135. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  105136. }
  105137. this._currentNonTimestampToken = token;
  105138. }
  105139. return token;
  105140. };
  105141. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  105142. var caps = this.getCaps();
  105143. var timerQuery = caps.timerQuery;
  105144. if (!timerQuery || !token) {
  105145. return -1;
  105146. }
  105147. if (caps.canUseTimestampForTimerQuery) {
  105148. if (!token._startTimeQuery) {
  105149. return -1;
  105150. }
  105151. if (!token._endTimeQuery) {
  105152. token._endTimeQuery = this._createTimeQuery();
  105153. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  105154. }
  105155. }
  105156. else if (!token._timeElapsedQueryEnded) {
  105157. if (!token._timeElapsedQuery) {
  105158. return -1;
  105159. }
  105160. if (timerQuery.endQueryEXT) {
  105161. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  105162. }
  105163. else {
  105164. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  105165. }
  105166. token._timeElapsedQueryEnded = true;
  105167. }
  105168. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  105169. var available = false;
  105170. if (token._endTimeQuery) {
  105171. available = this._getTimeQueryAvailability(token._endTimeQuery);
  105172. }
  105173. else if (token._timeElapsedQuery) {
  105174. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  105175. }
  105176. if (available && !disjoint) {
  105177. var result = 0;
  105178. if (caps.canUseTimestampForTimerQuery) {
  105179. if (!token._startTimeQuery || !token._endTimeQuery) {
  105180. return -1;
  105181. }
  105182. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  105183. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  105184. result = timeEnd - timeStart;
  105185. this._deleteTimeQuery(token._startTimeQuery);
  105186. this._deleteTimeQuery(token._endTimeQuery);
  105187. token._startTimeQuery = null;
  105188. token._endTimeQuery = null;
  105189. }
  105190. else {
  105191. if (!token._timeElapsedQuery) {
  105192. return -1;
  105193. }
  105194. result = this._getTimeQueryResult(token._timeElapsedQuery);
  105195. this._deleteTimeQuery(token._timeElapsedQuery);
  105196. token._timeElapsedQuery = null;
  105197. token._timeElapsedQueryEnded = false;
  105198. this._currentNonTimestampToken = null;
  105199. }
  105200. return result;
  105201. }
  105202. return -1;
  105203. };
  105204. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  105205. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  105206. };
  105207. // We also need to update AbstractMesh as there is a portion of the code there
  105208. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  105209. var engine = this.getEngine();
  105210. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  105211. this._isOccluded = false;
  105212. return;
  105213. }
  105214. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  105215. this._isOccluded = false;
  105216. return;
  105217. }
  105218. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  105219. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  105220. if (isOcclusionQueryAvailable) {
  105221. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  105222. this._isOcclusionQueryInProgress = false;
  105223. this._occlusionInternalRetryCounter = 0;
  105224. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  105225. }
  105226. else {
  105227. this._occlusionInternalRetryCounter++;
  105228. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  105229. this._isOcclusionQueryInProgress = false;
  105230. this._occlusionInternalRetryCounter = 0;
  105231. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  105232. // if strict continue the last state of the object.
  105233. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  105234. }
  105235. else {
  105236. return;
  105237. }
  105238. }
  105239. }
  105240. var scene = this.getScene();
  105241. if (scene.getBoundingBoxRenderer) {
  105242. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  105243. if (!this._occlusionQuery) {
  105244. this._occlusionQuery = engine.createQuery();
  105245. }
  105246. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  105247. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  105248. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  105249. this._isOcclusionQueryInProgress = true;
  105250. }
  105251. };
  105252. })(BABYLON || (BABYLON = {}));
  105253. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  105254. var BABYLON;
  105255. (function (BABYLON) {
  105256. /**
  105257. * Class used to generate noise procedural textures
  105258. */
  105259. var NoiseProceduralTexture = /** @class */ (function (_super) {
  105260. __extends(NoiseProceduralTexture, _super);
  105261. /**
  105262. * Creates a new NoiseProceduralTexture
  105263. * @param name defines the name fo the texture
  105264. * @param size defines the size of the texture (default is 256)
  105265. * @param scene defines the hosting scene
  105266. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  105267. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  105268. */
  105269. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  105270. if (size === void 0) { size = 256; }
  105271. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  105272. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  105273. _this._time = 0;
  105274. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  105275. _this.brightness = 0.2;
  105276. /** Defines the number of octaves to process */
  105277. _this.octaves = 3;
  105278. /** Defines the level of persistence (0.8 by default) */
  105279. _this.persistence = 0.8;
  105280. /** Gets or sets animation speed factor (default is 1) */
  105281. _this.animationSpeedFactor = 1;
  105282. _this._updateShaderUniforms();
  105283. return _this;
  105284. }
  105285. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  105286. var scene = this.getScene();
  105287. if (!scene) {
  105288. return;
  105289. }
  105290. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  105291. this.setFloat("brightness", this.brightness);
  105292. this.setInt("octaves", this.octaves);
  105293. this.setFloat("persistence", this.persistence);
  105294. this.setFloat("timeScale", this._time);
  105295. };
  105296. /** Generate the current state of the procedural texture */
  105297. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  105298. this._updateShaderUniforms();
  105299. _super.prototype.render.call(this, useCameraPostProcess);
  105300. };
  105301. /**
  105302. * Serializes this noise procedural texture
  105303. * @returns a serialized noise procedural texture object
  105304. */
  105305. NoiseProceduralTexture.prototype.serialize = function () {
  105306. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  105307. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  105308. return serializationObject;
  105309. };
  105310. /**
  105311. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  105312. * @param parsedTexture defines parsed texture data
  105313. * @param scene defines the current scene
  105314. * @param rootUrl defines the root URL containing noise procedural texture information
  105315. * @returns a parsed NoiseProceduralTexture
  105316. */
  105317. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  105318. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  105319. return texture;
  105320. };
  105321. return NoiseProceduralTexture;
  105322. }(BABYLON.ProceduralTexture));
  105323. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  105324. })(BABYLON || (BABYLON = {}));
  105325. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  105326. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","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#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef 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 CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef 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(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform int octaves;\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"};
  105327. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\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 POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\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 vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#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}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  105328. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  105329. globalObject["BABYLON"] = BABYLON;
  105330. //backwards compatibility
  105331. if(typeof earcut !== 'undefined') {
  105332. globalObject["Earcut"] = {
  105333. earcut: earcut
  105334. };
  105335. }
  105336. return BABYLON;
  105337. });